code
stringlengths
0
30.8k
source
stringclasses
6 values
language
stringclasses
9 values
__index_level_0__
int64
0
100k
void runWorker(bool useMPIFabric) { auto offloadDevice = ospray::api::Device::current; OSPDevice distribDevice = ospNewDevice("mpiDistributed"); ospDeviceSetParam( distribDevice, "worldCommunicator", OSP_VOID_PTR, &worker.comm); ospDeviceCommit(distribDevice); ospSetCurrentDevice(distribDevice); char hostname[HOST_NAME_MAX] = {0}; gethostname(hostname, HOST_NAME_MAX); postStatusMsg(OSP_LOG_DEBUG) << "#w: running MPI worker process " << workerRank() << "/" << workerSize() << " on pid " << getpid() << "@" << hostname; #ifdef ENABLE_PROFILING const std::string worker_log_file = std::string(hostname) + "_" + std::to_string(workerRank()) + ".txt"; std::ofstream fout(worker_log_file.c_str()); fout << "Worker rank " << workerRank() << " on '" << hostname << "'\n" << "/proc/self/status:\n" << getProcStatus() << "\n=====\n"; #endif std::unique_ptr<networking::Fabric> fabric; if (useMPIFabric) fabric = make_unique<MPIFabric>(mpicommon::world, 0); else fabric = make_unique<SocketReaderFabric>(mpicommon::world, 0); work::OSPState ospState; uint64_t commandSize = 0; utility::ArrayView<uint8_t> cmdView( reinterpret_cast<uint8_t *>(&commandSize), sizeof(uint64_t)); std::shared_ptr<utility::OwnedArray<uint8_t>> recvBuffer = std::make_shared<utility::OwnedArray<uint8_t>>(); #ifdef ENABLE_PROFILING ProfilingPoint workerStart; #endif while (1) { fabric->recvBcast(cmdView); recvBuffer->resize(commandSize, 0); fabric->recvBcast(*recvBuffer); networking::BufferReader reader(recvBuffer); while (!reader.end()) { work::TAG workTag = work::NONE; reader >> workTag; postStatusMsg(OSP_LOG_DEBUG) << "#osp.mpi.worker: processing work " << workTag << ": " << work::tagName(workTag); #ifdef ENABLE_PROFILING if (workTag == work::FINALIZE) { ProfilingPoint workerEnd; fout << "Worker exiting, /proc/self/status:\n" << getProcStatus() << "\n======\n" << "Avg. CPU % during run: " << cpuUtilization(workerStart, workerEnd) << "%\n" << std::flush; fout.close(); } #endif dispatchWork(workTag, ospState, reader, *fabric); postStatusMsg(OSP_LOG_DEBUG) << "#osp.mpi.worker: completed work " << workTag << ": " << work::tagName(workTag); } } }
function
c++
400
final class ReadAllQueryBuilder extends EclipseLinkAnonymousExpressionVisitor { /** * The query that was created based on the type of select clause. */ ReadAllQuery query; /** * The {@link JPQLQueryContext} is used to query information about the application metadata and * cached information. */ private final JPQLQueryContext queryContext; /** * The {@link Expression} being visited. */ private SelectStatement selectStatement; /** * Creates a new <code>ReadAllQueryBuilder</code>. * * @param queryContext The context used to query information about the application metadata and * cached information */ ReadAllQueryBuilder(JPQLQueryContext queryContext) { super(); this.queryContext = queryContext; } private void initializeReadAllQuery() { ReadAllQuery query = new ReadAllQuery(); query.dontUseDistinct(); this.query = query; } private void initializeReportQuery() { ReportQuery query = new ReportQuery(); query.returnWithoutReportQueryResult(); query.dontUseDistinct(); this.query = query; } /** * {@inheritDoc} */ @Override public void visit(CollectionExpression expression) { // Multiple expressions in the select clause => ReportQuery initializeReportQuery(); } /** * {@inheritDoc} */ @Override protected void visit(Expression expression) { // Does not select an identification variable // (e.g. projection or aggregate function) => ReportQuery initializeReportQuery(); } /** * {@inheritDoc} */ @Override public void visit(IdentificationVariable expression) { // Use ReadAllQuery if the variable of the SELECT clause expression is the base variable // Example: ReadAllQuery = SELECT e FROM Employee e // Example: ReportQuery = SELECT e FROM Department d JOIN d.employees e String variableName = expression.getVariableName(); if (queryContext.isRangeIdentificationVariable(variableName)) { if (selectStatement.hasGroupByClause() || selectStatement.hasHavingClause() || variableName != queryContext.getFirstDeclaration().getVariableName()) { initializeReportQuery(); } else { initializeReadAllQuery(); } } else { initializeReportQuery(); } } /** * {@inheritDoc} */ @Override public void visit(NullExpression expression) { // For from clause only JPQL the full object is always selected, so is ReadAllQuery. initializeReadAllQuery(); } /** * {@inheritDoc} */ @Override public void visit(ObjectExpression expression) { // Visit the identification variable directly expression.getExpression().accept(this); } /** * {@inheritDoc} */ @Override public void visit(ResultVariable expression) { // Make sure to traverse the select expression since // it has a result variable assigned to it expression.getSelectExpression().accept(this); } /** * {@inheritDoc} */ @Override public void visit(SelectClause expression) { expression.getSelectExpression().accept(this); } /** * {@inheritDoc} */ @Override public void visit(SelectStatement expression) { this.selectStatement = expression; expression.getSelectClause().accept(this); } }
class
java
401
public static class TimedLogging { static DateTime _previous = DateTime.UtcNow; public static void Write(string message) { var now = DateTime.UtcNow; var delta = now.Subtract(_previous); Console.WriteLine($"{delta.Milliseconds,4} - {message}"); _previous = now; } }
class
c#
402
public static final void persistDatabaseConnectionData(DatabaseConnectionData data) { try { File f = new File(System.getProperty("user.home")+"/.majortom-server"); if (!f.exists()) { f.mkdir(); } File engineFile = new File(DB_PROP_FILENAME); Properties properties = new Properties(); properties.setProperty(JdbcTopicMapStoreProperty.DATABASE_HOST, data.getHost()); properties.setProperty(JdbcTopicMapStoreProperty.DATABASE_USER, data.getUsername()); properties.setProperty(JdbcTopicMapStoreProperty.DATABASE_PASSWORD, data.getPassword()); properties.setProperty(JdbcTopicMapStoreProperty.DATABASE_NAME, data.getName()); properties.setProperty(JdbcTopicMapStoreProperty.SQL_DIALECT, SqlDialect.POSTGRESQL.name()); properties.store(new FileOutputStream(engineFile), "Database Connections for the server"); } catch (Exception e) { logger.error("Could not persist database connection data", e); } }
function
java
403
public abstract class Metric : DataModelElement { MetricDefinition m_Definition; public override string modelType => m_Definition.modelType; public string sensorId { get; internal set; } public string annotationId { get; internal set; } protected Metric(MetricDefinition definition, string sensorId = default, string annotationId = default) : base(definition.id) { m_Definition = definition; this.sensorId = sensorId; this.annotationId = annotationId; } public abstract T[] GetValues<T>(); public override void ToMessage(IMessageBuilder builder) { base.ToMessage(builder); builder.AddString("sensorId", sensorId); builder.AddString("annotationId", annotationId); builder.AddString("description", m_Definition.description); } }
class
c#
404
func (c *Client) RebootToRecovery(ctx context.Context) error { log.Printf("rebooting to recovery") var wg sync.WaitGroup c.RegisterDisconnectListener(&wg) err := c.Run(ctx, "dm reboot-recovery", os.Stdout, os.Stderr) if err != nil { if _, ok := err.(*ssh.ExitMissingError); !ok { return fmt.Errorf("failed to reboot into recovery: %s", err) } } ch := make(chan struct{}) go func() { defer close(ch) wg.Wait() }() select { case <-ch: case <-ctx.Done(): return fmt.Errorf("device did not disconnect: %s", ctx.Err()) } return nil }
function
go
405
public abstract class SourceItemWithAttributes : SourceItem { protected SourceItemWithAttributes(ISourceLocation sourceLocation) : base(sourceLocation) { } public IEnumerable<ICustomAttribute> Attributes { get { if (this.attributes == null) { List<ICustomAttribute> attrs = this.GetAttributes(); attrs.TrimExcess(); this.attributes = attrs.AsReadOnly(); } return this.attributes; } } IEnumerable<ICustomAttribute> attributes; protected abstract List<ICustomAttribute> GetAttributes(); }
class
c#
406
internal class Rule_5_6_4_InputObjectRequiredFieldsMustBeProvided : DocumentPartValidationRuleStep { public override bool ShouldExecute(DocumentValidationContext context) { return context.ActivePart is IInputValueDocumentPart ivdp && ivdp.Value is QueryComplexInputValue; } public override bool Execute(DocumentValidationContext context) { var ivdp = context.ActivePart as IInputValueDocumentPart; var graphType = ivdp.GraphType as IInputObjectGraphType; var requiredFields = graphType?.Fields.Where(x => x.TypeExpression.IsRequired).ToList(); var complexValue = ivdp.Value as QueryComplexInputValue; if (complexValue == null || requiredFields == null) { this.ValidationError( context, ivdp.Node, $"Input type mismatch. The {ivdp.InputType} '{ivdp.Name}' was used like an {TypeKind.INPUT_OBJECT.ToString()} " + $"but contained no fields to evaluate. Check the schema definition for {ivdp.TypeExpression.TypeName}."); return false; } var allFieldsAccountedFor = true; foreach (var field in requiredFields) { if (!complexValue.Arguments.ContainsKey(field.Name)) { this.ValidationError( context, ivdp.Node, $"The {ivdp.InputType} '{ivdp.Name}' requires a field named '{field.Name}'."); allFieldsAccountedFor = false; } } return allFieldsAccountedFor; } public override string RuleNumber => "5.6.4"; protected override string RuleAnchorTag => "#sec-Input-Object-Required-Fields"; }
class
c#
407
[Serializable] internal class AuthenticationRequest : Request, IAuthenticationRequest { private readonly PositiveAssertionResponse positiveResponse; private readonly NegativeAssertionResponse negativeResponse; internal AuthenticationRequest(OpenIdProvider provider, CheckIdRequest request) : base(request) { ErrorUtilities.VerifyArgumentNotNull(provider, "provider"); this.positiveResponse = new PositiveAssertionResponse(request); this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel); if (this.ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier && Protocol.ClaimedIdentifierForOPIdentifier != null) { this.IsDirectedIdentity = true; this.positiveResponse.ClaimedIdentifier = null; this.positiveResponse.LocalIdentifier = null; } this.IsDelegatedIdentifier = this.ClaimedIdentifier != null && this.ClaimedIdentifier != this.LocalIdentifier; } public override bool IsResponseReady { get { return this.IsAuthenticated.HasValue && (!this.IsAuthenticated.Value || !this.IsDirectedIdentity || (this.LocalIdentifier != null && this.ClaimedIdentifier != null)); } } #region IAuthenticationRequest Properties public ProtocolVersion RelyingPartyVersion { get { return Protocol.Lookup(this.RequestMessage.Version).ProtocolVersion; } } public bool Immediate { get { return this.RequestMessage.Immediate; } } public Realm Realm { get { return this.RequestMessage.Realm; } } public bool IsDirectedIdentity { get; private set; } public bool IsDelegatedIdentifier { get; private set; } public Identifier LocalIdentifier { get { return this.positiveResponse.LocalIdentifier; } set { if (this.IsDirectedIdentity) { if (this.ClaimedIdentifier != null && this.ClaimedIdentifier != value) { throw new InvalidOperationException(OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers); } this.positiveResponse.ClaimedIdentifier = value; } this.positiveResponse.LocalIdentifier = value; } } public Identifier ClaimedIdentifier { get { return this.positiveResponse.ClaimedIdentifier; } set { if (this.IsDirectedIdentity) { ErrorUtilities.VerifyOperation(!(this.LocalIdentifier != null && this.LocalIdentifier != value), OpenIdStrings.IdentifierSelectRequiresMatchingIdentifiers); this.positiveResponse.LocalIdentifier = value; } ErrorUtilities.VerifyOperation(!this.IsDelegatedIdentifier, OpenIdStrings.ClaimedIdentifierCannotBeSetOnDelegatedAuthentication); this.positiveResponse.ClaimedIdentifier = value; } } public bool? IsAuthenticated { get; set; } #endregion protected new CheckIdRequest RequestMessage { get { return (CheckIdRequest)base.RequestMessage; } } protected override IProtocolMessage ResponseMessage { get { if (this.IsAuthenticated.HasValue) { return this.IsAuthenticated.Value ? (IProtocolMessage)this.positiveResponse : this.negativeResponse; } else { return null; } } } #region IAuthenticationRequest Methods public void SetClaimedIdentifierFragment(string fragment) { ErrorUtilities.VerifyOperation(!(this.IsDirectedIdentity && this.ClaimedIdentifier == null), OpenIdStrings.ClaimedIdentifierMustBeSetFirst); ErrorUtilities.VerifyOperation(!(this.ClaimedIdentifier is XriIdentifier), OpenIdStrings.FragmentNotAllowedOnXRIs); UriBuilder builder = new UriBuilder(this.ClaimedIdentifier); builder.Fragment = fragment; this.positiveResponse.ClaimedIdentifier = builder.Uri; } public bool IsReturnUrlDiscoverable(IDirectWebRequestHandler requestHandler) { ErrorUtilities.VerifyArgumentNotNull(requestHandler, "requestHandler"); ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now."); try { foreach (var returnUrl in Realm.Discover(requestHandler, false)) { Realm discoveredReturnToUrl = returnUrl.ReturnToEndpoint; if (discoveredReturnToUrl.DomainWildcard) { Logger.Yadis.WarnFormat("Realm {0} contained return_to URL {1} which contains a wildcard, which is not allowed.", Realm, discoveredReturnToUrl); continue; } if (discoveredReturnToUrl.Contains(this.RequestMessage.ReturnTo)) { return true; } } } catch (ProtocolException ex) { Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed. {1}", Realm, ex); } catch (WebException ex) { Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed. {1}", Realm, ex); } return false; } #endregion }
class
c#
408
ECode View::Animate( IViewPropertyAnimator** res) { VALIDATE_NOT_NULL(res) if (mAnimator == NULL) { CViewPropertyAnimator::New(this, (IViewPropertyAnimator**)&mAnimator); } *res = mAnimator; REFCOUNT_ADD(*res) return NOERROR; }
function
c++
409
private static string ToAlternateServiceUrl(string serviceUrl) { if (string.IsNullOrWhiteSpace(serviceUrl)) { return null; } var url = new Uri(serviceUrl); var parts = url.Host.Split('.'); var organizationName = parts.First(); var tail = parts.Skip(1); var host = organizationName + "--S." + string.Join(".", tail); var alternateUrl = new UriBuilder(serviceUrl) { Host = host }; return alternateUrl.Uri.OriginalString; }
function
c#
410
String name(String enc, String[] parts) { if (this.prefix != null && this.prefix.equals(enc)) { if (parts.length == this.parts.size()) { String[] name = new String[this.parts.size()]; int i = 0; for (Part part : this.parts) { name[i] = part.name(parts[i]); if (name[i] == null) return null; i++; } return Converter.join(name, '.'); } } return null; }
function
java
411
public static IPoint GetCenter(ILineString line) { if (line == null) throw new ArgumentNullException(nameof(line)); double distance = GetLength(line.Points) / 2d; for (int i = 1; i < line.Points.Length; i++) { IPoint a = line.Points[i - 1]; IPoint b = line.Points[i]; double d = DistanceUtils.GetDistance(a, b); if (d > distance) { double heading = ComputeHeading(a, b); return ComputeOffset(a, distance, heading); } distance -= d; } return line.GetBoundingBox().GetCenter(); }
function
c#
412
public class HtmlWidgetVar extends SimpleVar { /** * The name of this variable. */ public static final String NAME = "W"; /** * Constructor. */ public HtmlWidgetVar() { super(NAME); } @Override /* Parameter */ public String resolve(VarResolverSession session, String key) throws Exception { HtmlWidgetMap m = session.getBean(HtmlWidgetMap.class).orElseThrow(RuntimeException::new); HtmlWidget w = m.get(key); if (w == null) return "unknown-widget-"+key; return w.getHtml(session); } @Override public boolean canResolve(VarResolverSession session) { return session.getBean(HtmlWidgetMap.class).isPresent(); } }
class
java
413
public class OrderedSetLinkedList<E> extends LinkedList<E> implements Cloneable, Serializable { public OrderedSetLinkedList() { super(); } @Override public boolean add(E object) { super.remove(object); return super.add(object); } }
class
java
414
public CommandItem toModelType() throws IllegalValueException { if (commandTask == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT)); } if (!CommandTask.isValidTask(commandTask)) { throw new IllegalValueException(CommandTask.MESSAGE_CONSTRAINTS); } final CommandTask modelTask = new CommandTask(commandTask); if (commandWord == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT)); } if (!CommandWord.isValidWord(commandWord)) { throw new IllegalValueException(CommandWord.MESSAGE_CONSTRAINTS); } final CommandWord modelWord = new CommandWord(commandWord); return new CommandItem(modelWord, modelTask); }
function
java
415
static inline enum status_code dma_crc_io_enable( struct dma_crc_config *config) { if (DMAC->CRCSTATUS.reg & DMAC_CRCSTATUS_CRCBUSY) { return STATUS_BUSY; } if (DMAC->CTRL.reg & DMAC_CTRL_CRCENABLE) { return STATUS_BUSY; } DMAC->CRCCTRL.reg = DMAC_CRCCTRL_CRCBEATSIZE(config->size) | DMAC_CRCCTRL_CRCPOLY(config->type) | DMAC_CRCCTRL_CRCSRC_IO; if (config->type == CRC_TYPE_32) { DMAC->CRCCHKSUM.reg = 0xFFFFFFFF; } DMAC->CTRL.reg |= DMAC_CTRL_CRCENABLE; return STATUS_OK; }
function
c
416
private class LoadMessageTask extends AsyncTask<Void, Void, Message> { private long mId; private boolean mOkToFetch; /** * Special constructor to cache some local info */ public LoadMessageTask(long messageId, boolean okToFetch) { mId = messageId; mOkToFetch = okToFetch; } @Override protected Message doInBackground(Void... params) { if (mId == Long.MIN_VALUE) { return null; } return Message.restoreMessageWithId(MessageView.this, mId); } @Override protected void onPostExecute(Message message) { /* doInBackground() may return null result (due to restoreMessageWithId()) * and in that situation we want to Activity.finish(). * * OTOH we don't want to Activity.finish() for isCancelled() because this * would introduce a surprise side-effect to task cancellation: every task * cancelation would also result in finish(). * * Right now LoadMesageTask is cancelled not only from onDestroy(), * and it would be a bug to also finish() the activity in that situation. */ if (isCancelled()) { return; } if (message == null) { if (mId != Long.MIN_VALUE) { finish(); } return; } reloadUiFromMessage(message, mOkToFetch); startPresenceCheck(); } }
class
java
417
public class RemoteAddress implements IOReadableWritable, Serializable { private InetSocketAddress address; private int connectionIndex; public RemoteAddress(InstanceConnectionInfo connectionInfo, int connectionIndex) { this(new InetSocketAddress(connectionInfo.address(), connectionInfo.dataPort()), connectionIndex); } public RemoteAddress(InetSocketAddress address, int connectionIndex) { this.address = checkNotNull(address); checkArgument(connectionIndex >= 0); this.connectionIndex = connectionIndex; } public InetSocketAddress getAddress() { return address; } public int getConnectionIndex() { return connectionIndex; } @Override public int hashCode() { return address.hashCode() + (31 * connectionIndex); } @Override public boolean equals(Object other) { if (other.getClass() != RemoteAddress.class) { return false; } final RemoteAddress ra = (RemoteAddress) other; if (!ra.getAddress().equals(address) || ra.getConnectionIndex() != connectionIndex) { return false; } return true; } @Override public String toString() { return address + " [" + connectionIndex + "]"; } // ------------------------------------------------------------------------ // Serialization // ------------------------------------------------------------------------ public RemoteAddress() { this.address = null; this.connectionIndex = -1; } @Override public void write(final DataOutputView out) throws IOException { final InetAddress ia = address.getAddress(); out.writeInt(ia.getAddress().length); out.write(ia.getAddress()); out.writeInt(address.getPort()); out.writeInt(connectionIndex); } @Override public void read(final DataInputView in) throws IOException { final byte[] addressBytes = new byte[in.readInt()]; in.readFully(addressBytes); final InetAddress ia = InetAddress.getByAddress(addressBytes); int port = in.readInt(); address = new InetSocketAddress(ia, port); connectionIndex = in.readInt(); } }
class
java
418
INKError EventIsActive(char *event_name, bool * is_current) { alarm_t a; if (!event_name || !is_current) return INK_ERR_PARAMS; a = get_event_id(event_name); if (a < 0) return INK_ERR_PARAMS; if (lmgmt->alarm_keeper->isCurrentAlarm(a)) *is_current = true; else *is_current = false; return INK_ERR_OKAY; }
function
c++
419
def plot(self, series, x_axis='x_axis', y_axis='y_axis', **overrides): if not isinstance(series, Series): message = "Series must be of type perrot.plot.Series! -> %s" % type(series) raise TypeError(message) if overrides: series.set_properties(overrides, True) if series.color is UNDEF and self._colors: series.color = self._colors.scale(series.tag) self.add(series) self.map(series, x_axis, scale='x_scale') self.map(series, y_axis, scale='y_scale')
function
python
420
public static IServiceCollection AddVisualStudioSolutionFileOperator(this IServiceCollection services, IServiceAction<IStringlyTypedPathOperator> stringlyTypedPathOperatorAction, IServiceAction<IVisualStudioSolutionFileOperatorCore> visualStudioSolutionFileOperatorCoreAction) { services.AddSingleton<IVisualStudioSolutionFileOperator, VisualStudioSolutionFileOperator>() .Run(stringlyTypedPathOperatorAction) .Run(visualStudioSolutionFileOperatorCoreAction) ; return services; }
function
c#
421
public static boolean isAtomic(String expr) { if (expr.length() == 1 && !"()[]|*+?".contains(expr)) { return true; } char[] data = expr.toCharArray(); int depth = 0; for (int i = 0; i < data.length; i++) { switch (data[i]) { case '(': case '[': depth++; break; case ')': case ']': depth--; break; } if (depth == 0 && i != data.length - 1) { return false; } } return depth == 0; }
function
java
422
public void kWayMergingSortedArray(final List<File> smallFiles, final File outputFile) { Validate.notEmpty(smallFiles); Validate.notNull(outputFile); emptyOrCreateFolder(outputFile.getParentFile()); PriorityQueue<Entry> pq = new PriorityQueue<>((o1, o2) -> o1.word.compareTo(o2.word)); HashMap<Integer, Scanner> scannerMap = new HashMap<>(); populatePriorityQueueAndScannerMap(smallFiles, pq, scannerMap); logger.info("pq = {}", pq); String lastWord = ""; try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) { while (!pq.isEmpty()) { Entry nextEntry = pq.poll(); if (!lastWord.equals(nextEntry.word)) { lastWord = nextEntry.word; try { bw.write(nextEntry.word); bw.newLine(); } catch (IOException e) { logger.error("can't write to finalOutputFile with outputFile: {}; error: {}", outputFile, e); } } if (scannerMap.containsKey(nextEntry.index)) { Scanner scanner = scannerMap.get(nextEntry.index); if (scanner.hasNext()) { pq.add(new Entry(scanner.next(), nextEntry.index)); } else { scannerMap.remove(nextEntry.index); } } } bw.flush(); } catch (IOException e) { logger.error("can't creat or write to finalOutputFile with outputFile: {}; error: {}", outputFile, e); } if (!scannerMap.isEmpty()) { for (Scanner scanner : scannerMap.values()) { if (scanner != null) { scanner.close(); } } } return; }
function
java
423
private void PopulateStructures() { for (int row = 1; row < 10; ++row) { for (int col = 1; col < 10; ++col) { Coordinate c = new Coordinate(row, col); Square s = new Square(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); _squares.Add(c, s); _associations.Add(c, new Associations()); } } }
function
c#
424
public static CompoundStructure GetCompoundStructure (dynaWallType WallType) { revitDB.WallType unwrappedWall = (revitDB.WallType)WallType.InternalElement; revitDoc document = unwrappedWall.Document; revitCS compoundStructure = unwrappedWall.GetCompoundStructure(); if (compoundStructure != null) { return new CompoundStructure(compoundStructure, document); } else { return null; } }
function
c#
425
public class QueueWatcherTask extends TimerTask { // parent object - so we can clean up when finished private IQueueHandler parent; // local timer private Timer timer; /** * start the timer (5 second interval) */ public void init(){ timer = new Timer(); timer.scheduleAtFixedRate(this, 5000L, 5000L); } public QueueWatcherTask(IQueueHandler parentHandler) { parent = parentHandler; init(); } /** * This method looks at the parent queue and sees if it is empty. if it is then it will wait a further * 5 seconds by setting the threadterminationcount to zero and then checking again after 5 seconds * This is just to make sure the queue has been empty for at least 5 seconds before destroying it * and doesn't catch it the split second it happens to be empty */ @Override public void run() { //System.out.println("(" + parent.getQueueIdentifer() + ") tcount="+parent.getThreadTerminationCount()+" queue size="+parent.getQueue().size()); if(parent.getThreadTerminationCount() < 1 && parent.getQueue().isEmpty()){ timer.cancel(); parent.destroy(); this.cancel(); } else{ parent.setThreadTerminationCount(0); } } }
class
java
426
public void configurationChanged(int flags) { if (hasPreviews()) { assert myPreviews != null; beginRenderScheduling(); for (RenderPreview preview : myPreviews) { if (preview.getScale() > 1.2) { preview.configurationChanged(flags); } } for (RenderPreview preview : myPreviews) { if (preview.getScale() <= 1.2) { preview.configurationChanged(flags); } } RenderPreview preview = getStashedPreview(); if (preview != null) { preview.configurationChanged(flags); preview.dispose(); } myNeedLayout = true; myNeedRender = true; redraw(); } }
function
java
427
private void assertCommandSuccess(FindMissingCommand command, String expectedMessage, List<Person> expectedList) { AddressBook expectedAddressBook = new AddressBook(missingAttributesModel.getAddressBook()); CommandResult result = command.execute(); assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedList, missingAttributesModel.getFilteredPersonList()); assertEquals(expectedAddressBook, missingAttributesModel.getAddressBook()); }
function
java
428
@Override public Identifier build() { Identifier identifier = new Identifier(this); if (validating) { validate(identifier); } return identifier; }
function
java
429
public static class TargetPlatformUtility { public static TargetPlatform GetExecutingPlatform() { #if PLATFORM_ANDROID return TargetPlatform.Android; #elif PLATFORM_IOS return TargetPlatform.iOS; #elif PLATFORM_LINUX return TargetPlatform.Linux; #elif PLATFORM_MACOS return TargetPlatform.MacOSX; #elif PLATFORM_OUYA return TargetPlatform.Ouya; #elif PLATFORM_PSMOBILE return TargetPlatform.PlayStationMobile; #elif PLATFORM_WINDOWS return TargetPlatform.Windows; #elif PLATFORM_WINDOWS8 return TargetPlatform.Windows8; #elif PLATFORM_WINDOWSGL return TargetPlatform.WindowsGL; #elif PLATFORM_WINDOWSPHONE return TargetPlatform.WindowsPhone; #elif PLATFORM_WEB return TargetPlatform.Web; #else throw new NotSupportedException(); #endif } }
class
c#
430
def nodeAndOutputFromScenegraphLocationString(string, dag): try: outputNodeUUID = uuidFromScenegraphLocationString(string) outputNode = dag.node(nUUID=outputNodeUUID) outputNodeOutputName = string.split(":")[3] return (outputNode, outputNode.outputNamed(outputNodeOutputName)) except: return(None, None)
function
python
431
function memo(fn) { const cache = {}; return function (...args) { let key; if (args.length === 1) { switch (typeof args[0]) { case "string": case "bigint": case "number": case "boolean": key = args[0]; break; default: key = JSON.stringify(args[0]); break; } } else { key = JSON.stringify(args); } return cache[key] !== undefined ? cache[key] : (cache[key] = fn.apply(null, args)); }; }
function
javascript
432
private void initialize(final List<GeneralParameterDescriptor> elements) { for (final GeneralParameterDescriptor child : elements) { for (int count=child.getMinimumOccurs(); --count>=0;) { addUnchecked(new UninitializedParameter(child)); } } }
function
java
433
def audio_int(num_samples=50): p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) values = [math.sqrt(abs(audioop.avg(stream.read(CHUNK), 4))) for x in range(num_samples)] values = sorted(values, reverse=True) r = sum(values[:int(num_samples * 0.2)]) / int(num_samples * 0.2) stream.close() p.terminate() return r
function
python
434
QUICK_SELECT_DESC::QUICK_SELECT_DESC(QUICK_RANGE_SELECT *q, uint used_key_parts_arg, bool *error) :QUICK_RANGE_SELECT(*q), rev_it(rev_ranges), used_key_parts (used_key_parts_arg) { QUICK_RANGE *r; mrr_buf_desc= NULL; mrr_flags |= HA_MRR_USE_DEFAULT_IMPL; mrr_flags |= HA_MRR_SORTED; mrr_buf_size= 0; Quick_ranges::const_iterator pr= ranges.begin(); Quick_ranges::const_iterator end_range= ranges.end(); for (; pr != end_range; pr++) rev_ranges.push_front(*pr); for (r = rev_it++; r; r = rev_it++) { if ((r->flag & EQ_RANGE) && head->key_info[index].key_length != r->max_length) r->flag&= ~EQ_RANGE; } rev_it.rewind(); q->dont_free=1; }
function
c++
435
def compressive_strength(self, ratios): clay = ratios[1] straw_frac = ratios[2] matrix_c = self.compressive_strength_matrix(ratios) am = 0 ab = -5889.55 bm = 0 bb = 110.46 c = -0.252 compressive = (am*clay + ab) * straw_frac**2 + \ (bm*clay + bb) * straw_frac + \ c + matrix_c return compressive
function
python
436
def Upgrade(self, aff4_class): aff4_class = _ValidateAFF4Type(aff4_class) if self.__class__ == aff4_class: return self if not isinstance(aff4_class, type): raise InstantiationError("aff4_class=%s must be a type" % aff4_class) if not issubclass(aff4_class, AFF4Object): raise InstantiationError( "aff4_class=%s must be a subclass of AFF4Object." % aff4_class) if isinstance(self, aff4_class): return self result = aff4_class(self.urn, mode=self.mode, clone=self, parent=self.parent, token=self.token, age=self.age_policy, object_exists=self.object_exists, follow_symlinks=self.follow_symlinks, aff4_type=self.aff4_type, mutation_pool=self.mutation_pool, transaction=self.transaction) result.symlink_urn = self.urn result.Initialize() return result
function
python
437
@Deprecated public static final String parseExtensionFeedItemFromExtensionFeedItemName( String extensionFeedItemName) { return EXTENSION_FEED_ITEM_PATH_TEMPLATE .parse(extensionFeedItemName) .get("extension_feed_item"); }
function
java
438
public void Invalidate(Aabb aabb) { if (!RegionsContain(InvalidBaseRegions, aabb)) { InvalidBaseRegions.Add(aabb); AreInvalidBaseRegionsClipped = (InvalidBaseRegions.Count == 1); } if (!RegionsContain(InvalidDetailRegions, aabb)) { InvalidDetailRegions.Add(aabb); AreInvalidDetailRegionsClipped = (InvalidDetailRegions.Count == 1); } }
function
c#
439
func pollTimed(t *testing.T, what string, secTimeout float64, pollers ...func() bool) { for i := 0; i < int(secTimeout/0.02); i++ { var ok = true for _, poller := range pollers { if !poller() { ok = false break } } if ok { return } time.Sleep(20 * time.Millisecond) } t.Fatalf("waiting for %s timed out", what) }
function
go
440
def calc_reg_rstval_mask(self, reg): rst_mask = ["0" for x in range(reg.size)] for field in sorted(reg.field, key=lambda a: a.bitOffset): if (field.resets == None): continue; remainder = field.resets.reset.value for j in range(field.bitWidth): if (remainder % 2 == 1): rst_mask[field.bitOffset + j] = "1" remainder = int(remainder / 2) return '"' + ''.join(rst_mask[::-1]) + '"'
function
python
441
function geeChangeGlobe(vs_name) { var url = GEE_BASE_URL; if (geeIsVirtualServer2d(vs_name + '/')) { document.location = url + '/cutter/map_cutter.html?server=' + vs_name; } else { document.location = url + '/cutter/globe_cutter.html?server=' + vs_name; } return false; }
function
javascript
442
public static Map<String,String> extractParameters(String url) throws ParseException { String paramStr = extractParameterString(url); if (paramStr == null) return null; return parseParameterString(paramStr); }
function
java
443
public class SpringBootStarter implements TestRule { private final Class<?> applicationClass; private final List<String> args; private final List<DatabaseState> databaseStates; /** * Constructor. * * @param applicationClass the Spring Boot application class. * @param databaseStates list containing {@link DatabaseState} objects, each describing a database state * in form of one or more SQL scripts. * @param args the command line arguments the application should be started with. */ public SpringBootStarter(Class<?> applicationClass, List<DatabaseState> databaseStates, List<String> args) { this.args = args; this.applicationClass = applicationClass; this.databaseStates = databaseStates; } @Override public Statement apply(Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { List<String> args = new ArrayList<>(); args.addAll(SpringBootStarter.this.args); args.addAll(PactProperties.toCommandLineArguments(SpringBootStarter.this.databaseStates)); ApplicationContext context = SpringApplication.run(SpringBootStarter.this.applicationClass, args.toArray(new String[]{})); base.evaluate(); SpringApplication.exit(context); } }; } /** * Creates a builder that provides a fluent API to create a new {@link SpringBootStarter} instance. */ public static SpringBootStarterBuilder builder() { return new SpringBootStarterBuilder(); } public static class SpringBootStarterBuilder { private Class<?> applicationClass; private List<String> args = new ArrayList<>(); private List<DatabaseState> databaseStates = new ArrayList<>(); public SpringBootStarterBuilder withApplicationClass(Class<?> clazz) { this.applicationClass = clazz; return this; } public SpringBootStarterBuilder withArgument(String argument) { this.args.add(argument); return this; } public SpringBootStarterBuilder withDatabaseState(String stateName, String... sqlScripts) { this.databaseStates.add(new DatabaseState(stateName, sqlScripts)); return this; } public SpringBootStarter build() { return new SpringBootStarter(this.applicationClass, this.databaseStates, args); } } }
class
java
444
func (r *TeapotAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := log.FromContext(ctx) var teapotapp k8sv1alpha1.TeapotApp if err := r.Get(ctx, req.NamespacedName, &teapotapp); err != nil { if !errors.IsNotFound(err) { log.Error(err, "unable to fetch TeapotApp") } return ctrl.Result{}, client.IgnoreNotFound(err) } var deployment appsv1.Deployment err := r.Get(ctx, types.NamespacedName{Namespace: teapotapp.Namespace, Name: teapotapp.Status.DeploymentName}, &deployment) if client.IgnoreNotFound(err) != nil { log.Error(err, "unable to fetch Deployment") return ctrl.Result{}, client.IgnoreNotFound(err) } if errors.IsNotFound(err) { log.Info("Deployment not found, creating a new one") return ctrl.Result{}, r.createNewDeployment(ctx, &teapotapp) } if teapotapp.IsDeploymentOutdated(deployment) { log.Info("Deployment outdated, updating Deployment") return ctrl.Result{}, r.updateDeployment(ctx, &teapotapp, deployment) } var autoscaling autoscalingv2beta2.HorizontalPodAutoscaler err = r.Get(ctx, types.NamespacedName{Namespace: teapotapp.Namespace, Name: teapotapp.Name}, &autoscaling) if client.IgnoreNotFound(err) != nil { log.Error(err, "unable to fetch HorizontalPodAutoscaler") return ctrl.Result{}, client.IgnoreNotFound(err) } if teapotapp.AutoscalingEnabled() && errors.IsNotFound(err) { log.Info("HorizontalPodAutoscaler not found, creating a new one") return ctrl.Result{}, r.createNewAutoscaling(ctx, &teapotapp) } if teapotapp.IsAutoscalingOutdated(autoscaling) && !errors.IsNotFound(err) { log.Info("HorizontalPodAutoscaler outdated, updating HorizontalPodAutoscaler") return ctrl.Result{}, r.updateAutoscaling(ctx, &teapotapp, autoscaling) } var service corev1.Service err = r.Get(ctx, types.NamespacedName{Namespace: teapotapp.Namespace, Name: teapotapp.Name}, &service) if client.IgnoreNotFound(err) != nil { log.Error(err, "unable to fetch Service") return ctrl.Result{}, client.IgnoreNotFound(err) } if errors.IsNotFound(err) { log.Info("Service not found, creating a new one") return ctrl.Result{}, r.createNewService(ctx, &teapotapp) } var ingressRoute traefikv1alpha1.IngressRoute err = r.Get(ctx, types.NamespacedName{Namespace: teapotapp.Namespace, Name: teapotapp.Name}, &ingressRoute) if client.IgnoreNotFound(err) != nil { log.Error(err, "unable to fetch IngressRoute") return ctrl.Result{}, client.IgnoreNotFound(err) } if errors.IsNotFound(err) { log.Info("IngressRoute not found, creating a new one") return ctrl.Result{}, r.createNewIngressRoute(ctx, &teapotapp) } if teapotapp.IsIngressRouteOutdated(ingressRoute) { log.Info("IngressRoute outdated, updating IngressRoute") return ctrl.Result{}, r.updateIngressRoute(ctx, &teapotapp, ingressRoute) } teapotapp.Status.Route = fmt.Sprintf("%s://%s%s", r.Config.Protocol, r.Config.Domain, teapotapp.GetPath()) teapotapp.Status.DeploymentStatus = deployment.Status if err := r.Status().Update(ctx, &teapotapp); err != nil { log.Error(err, "unable to update TeapotApp status") return ctrl.Result{}, err } return ctrl.Result{}, nil }
function
go
445
public Builder mergeParentRequiredBudgetMicros(com.google.protobuf.Int64Value value) { if (parentRequiredBudgetMicrosBuilder_ == null) { if (parentRequiredBudgetMicros_ != null) { parentRequiredBudgetMicros_ = com.google.protobuf.Int64Value.newBuilder(parentRequiredBudgetMicros_).mergeFrom(value).buildPartial(); } else { parentRequiredBudgetMicros_ = value; } onChanged(); } else { parentRequiredBudgetMicrosBuilder_.mergeFrom(value); } return this; }
function
java
446
public String storeToVault(JsonObject dataJson, String vaultId) throws InsightsCustomException { String response = null; Map<String, String> headers = new HashMap<>(); try { headers.put("X-Vault-Token", VAULT_TOKEN); JsonObject requestJson = new JsonObject(); requestJson.add("data", dataJson); log.debug("Request body for vault {} -- ", requestJson); String url = VAULT_URL + vaultId; response = RestApiHandler.doPost(url, requestJson, headers); } catch (Exception e) { log.error("Error while Storing to vault agent {} ", e); throw new InsightsCustomException(e.getMessage()); } return response; }
function
java
447
class ShapeTest : public ::Test { public: using Transform = ::geometria::Transform; using Real3 = ::geometria::Real3; using SurfaceId = ::celeritas::SurfaceId; using SurfaceType = ::celeritas::SurfaceType; using CSGCell = ::celeritas::CSGCell; using VecDbl = std::vector<real_type>; using VecStr = std::vector<std::string>; using surfid_int = SurfaceId::size_type; using logic_int = CSGCell::logic_int; enum LogicToken : CSGCell::logic_int { LOGIC_NOT = CSGCell::LOGIC_NOT, LOGIC_AND = CSGCell::LOGIC_AND, LOGIC_OR = CSGCell::LOGIC_OR, }; static constexpr real_type inf = HUGE_VAL; public: void build(const Shape& shape, Transform t); void build(const Shape& shape) { return this->build(shape, Transform{}); } void print_expected() const; template<class S> S get_surface(surfid_int idx) const { EXPECT_LT(idx, this->surfaces.size()); SurfaceId id(idx); EXPECT_EQ(this->surfaces.get_type(id), S::surface_type()); return this->surfaces.get<S>(id); } VecDbl get_surface_data(SurfaceType type, surfid_int idx) const; SurfaceContainer surfaces; CSGCell cell; BoundingBox bbox; VecStr surface_names; }
class
c++
448
public void render() { if (this.loading) { try { return; } catch (Exception e) { Generals.logger.warning("Loading screen got removed mid-render"); return; } } currentState.render(gameCanvas, uiCanvas); if (toggleScale) { toggleScale=false; } }
function
java
449
def download_leaderboard_table(url): page = requests.get(url) soup = BeautifulSoup(page.text, "html.parser") found = soup.find( "table", {"class": "rgMasterTable", "id": "LeaderBoard1_dg1_ctl00"} ) stats_df = pd.read_html(str(found))[0] stats_df.columns = stats_df.columns.droplevel() return stats_df[:-1]
function
python
450
def shift_cyc_matrix(X, shift=0): K, N = X.shape shift = np.mod(shift, K) X_cyc = np.zeros((K,N)) X_cyc[shift:K, :] = X[0:K-shift, :] X_cyc[0:shift, :] = X[K-shift:K, :] return X_cyc
function
python
451
def fort2xyqscattered(framenumber,outfile=None,components='all'): if isinstance(outfile,str): fout = open(outfile,'w') elif (isinstance(outfile)==file): fout = outfile numstring = str(10000 + framenumber) framenostr = numstring[1:] forttname = 'fort.t'+framenostr fortqname = 'fort.q'+framenostr solutionlist=fort2list(fortqname,forttname) if (components=='all'): qlst = np.arange(solutionlist[0]['meqn']) else: qlst = np.array(components,dtype=int) - 1 levels = solutionlist[0]['AMR_maxlevel'] for grid in solutionlist: if (grid['AMR_level']==levels): x = grid['xlow'] + grid['dx']*(0.5 + (np.arange(grid['mx'],dtype=float))) y = grid['ylow'] + grid['dy']*(0.5 + (np.arange(grid['my'],dtype=float))) Q = grid['data'][:,qlst] (X,Y) = np.meshgrid(x,y) X = np.reshape(X,(grid['mx']*grid['my'],1)) Y = np.reshape(Y,(grid['mx']*grid['my'],1)) try: XYQ = np.vstack((XYQ,np.hstack((X,Y,Q)))) except: XYQ = np.hstack((X,Y,Q)) gridrect = [grid['xlow'],grid['ylow'],grid['xupper'],grid['yupper']] else: gridrect = [grid['xlow'],grid['ylow'],grid['xupper'],grid['yupper']] gridoverlap = False for rectangle in rectangles: if (intersection(gridrect,rectangle)): gridoverlap = True break if (not gridoverlap): x = grid['xlow'] + grid['dx']*(0.5 + (np.arange(grid['mx'],dtype=float))) y = grid['ylow'] + grid['dy']*(0.5 + (np.arange(grid['my'],dtype=float))) Q = grid['data'][:,qlst] (X,Y) = np.meshgrid(x,y) X = np.reshape(X,(grid['mx']*grid['my'],1)) Y = np.reshape(Y,(grid['mx']*grid['my'],1)) XYQ = np.vstack((XYQ,np.hstack((X,Y,Q)))) else: row = 0 for j in xrange(grid['my']): y = grid['ylow'] + grid['dy']*(0.5 + float(j)) for i in xrange(grid['mx']): x = grid['xlow'] + grid['dx']*(0.5 + float(i)) q = grid['data'][row,qlst] gridoverlap = False for rectangle in rectangles: if (intersection([x,y,x,y],rectangle)): gridoverlap = True break if (not gridoverlap): XYQ = np.vstack((XYQ,np.hstack((x,y,q)))) row = row + 1 try: rectangles = np.vstack((rectangles,gridrect)) except: rectangles = gridrect if not outfile: return XYQ else: np.savetxt(fout,XYQ) fout.close()
function
python
452
def stats(args): p = OptionParser(stats.__doc__) p.add_option("--gene", default="mRNA", help="The gene type") p.add_option("--exon", default="CDS", help="The exon type") opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) (gff_file,) = args g = make_index(gff_file) exon_lengths = [] intron_lengths = [] gene_lengths = [] exon_counts = [] for feat in g.features_of_type(opts.gene): exons = [] for c in g.children(feat.id, 1): if c.featuretype != opts.exon: continue exons.append((c.chrom, c.start, c.stop)) introns = range_interleave(exons) feat_exon_lengths = [(stop - start + 1) for (chrom, start, stop) in exons] feat_intron_lengths = [(stop - start + 1) for (chrom, start, stop) in introns] exon_lengths += feat_exon_lengths intron_lengths += feat_intron_lengths gene_lengths.append(sum(feat_exon_lengths)) exon_counts.append(len(feat_exon_lengths)) a = SummaryStats(exon_lengths) b = SummaryStats(intron_lengths) c = SummaryStats(gene_lengths) d = SummaryStats(exon_counts) for x, title in zip((a, b, c, d), metrics): x.title = title print(x, file=sys.stderr) prefix = gff_file.split(".")[0] for x in (a, b, c, d): dirname = x.title mkdir(dirname) txtfile = op.join(dirname, prefix + ".txt") x.tofile(txtfile)
function
python
453
public class AcmeRandomGeneratorAndValidator { private static final Logger logger = LoggerFactory.getLogger(AcmeRandomGeneratorAndValidator.class); private static final Integer NONCE_SIZE = 32; private static final Integer RANDOM_ID_SIZE = 8; private static final Integer RANDOM_CHALLANGE_TOKEN_SIZE = 64; public static String generateNonce(){ SecureRandom secureRandom = new SecureRandom(); byte[] nonceArray = new byte[NONCE_SIZE]; secureRandom.nextBytes(nonceArray); String nonce = Base64URL.encode(nonceArray).toString(); return nonce; } public static String generateRandomId(){ SecureRandom secureRandom = new SecureRandom(); byte[] randomArray = new byte[RANDOM_ID_SIZE]; secureRandom.nextBytes(randomArray); String randomId = Base64URL.encode(randomArray).toString(); return randomId.replace("/", "-"); } public static String generateRandomTokenForValidation(PublicKey publicKey) { SecureRandom secureRandom = new SecureRandom(); byte[] randomArray = new byte[RANDOM_CHALLANGE_TOKEN_SIZE]; secureRandom.nextBytes(randomArray); String randomId = Base64URL.encode(randomArray).toString(); return randomId.replace("/","0"); } }
class
java
454
class FrameView extends ComponentView implements HyperlinkListener { /** * Creates a new FrameView for the specified element. * * @param el the element for the view */ FrameView(Element el) { super(el); } /** * Creates the element that will be embedded in the view. * This will be a JEditorPane with the appropriate content set. * * @return the element that will be embedded in the view */ protected Component createComponent() { Element el = getElement(); AttributeSet atts = el.getAttributes(); JEditorPane html = new JEditorPane(); html.addHyperlinkListener(this); URL base = ((HTMLDocument) el.getDocument()).getBase(); String srcAtt = (String) atts.getAttribute(HTML.Attribute.SRC); if (srcAtt != null && ! srcAtt.equals("")) { try { URL page = new URL(base, srcAtt); html.setPage(page); ((HTMLDocument) html.getDocument()).setFrameDocument(true); } catch (MalformedURLException ex) { // Leave page empty. } catch (IOException ex) { // Leave page empty. } } return html; } /** * Catches hyperlink events on that frame's editor and forwards it to * the outermost editorpane. */ public void hyperlinkUpdate(HyperlinkEvent event) { JEditorPane outer = getTopEditorPane(); if (outer != null) { if (event instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent hfhe = (HTMLFrameHyperlinkEvent) event; if (hfhe.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String target = hfhe.getTarget(); if (event instanceof FormSubmitEvent) { handleFormSubmitEvent(hfhe, outer, target); } else // No FormSubmitEvent. { handleHyperlinkEvent(hfhe, outer, target); } } } else { // Simply forward this event. outer.fireHyperlinkUpdate(event); } } } /** * Handles normal hyperlink events. * * @param event the event * @param outer the top editor * @param target the target */ private void handleHyperlinkEvent(HyperlinkEvent event, JEditorPane outer, String target) { if (target.equals("_top")) { try { outer.setPage(event.getURL()); } catch (IOException ex) { // Well... ex.printStackTrace(); } } if (! outer.isEditable()) { outer.fireHyperlinkUpdate (new HTMLFrameHyperlinkEvent(outer, event.getEventType(), event.getURL(), event.getDescription(), getElement(), target)); } } /** * Handles form submit events. * * @param event the event * @param outer the top editor * @param target the target */ private void handleFormSubmitEvent(HTMLFrameHyperlinkEvent event, JEditorPane outer, String target) { HTMLEditorKit kit = (HTMLEditorKit) outer.getEditorKit(); if (kit != null && kit.isAutoFormSubmission()) { if (target.equals("_top")) { try { outer.setPage(event.getURL()); } catch (IOException ex) { // Well... ex.printStackTrace(); } } else { HTMLDocument doc = (HTMLDocument) outer.getDocument(); doc.processHTMLFrameHyperlinkEvent(event); } } else { outer.fireHyperlinkUpdate(event); } } /** * Determines the topmost editor in a nested frameset. * * @return the topmost editor in a nested frameset */ private JEditorPane getTopEditorPane() { View parent = getParent(); View top = null; while (parent != null) { if (parent instanceof FrameSetView) top = parent; } JEditorPane editor = null; if (top != null) editor = (JEditorPane) top.getContainer(); return editor; } }
class
java
455
public static boolean shouldPushDownJoinCostAware( ConnectorSession session, JoinType joinType, PreparedQuery leftSource, PreparedQuery rightSource, JoinStatistics statistics) { long maxTableSizeBytes = getJoinPushdownAutomaticMaxTableSize(session).map(DataSize::toBytes).orElse(Long.MAX_VALUE); String joinSignature = ""; if (LOG.isDebugEnabled()) { joinSignature = diagnosticsJoinSignature(joinType, leftSource, rightSource); } if (statistics.getLeftStatistics().isEmpty()) { logNoPushdown(joinSignature, "left stats empty"); return false; } double leftDataSize = statistics.getLeftStatistics().get().getDataSize(); if (leftDataSize > maxTableSizeBytes) { logNoPushdown(joinSignature, () -> "left size " + leftDataSize + " > " + maxTableSizeBytes); return false; } if (statistics.getRightStatistics().isEmpty()) { logNoPushdown(joinSignature, "right stats empty"); return false; } double rightDataSize = statistics.getRightStatistics().get().getDataSize(); if (rightDataSize > maxTableSizeBytes) { logNoPushdown(joinSignature, () -> "right size " + rightDataSize + " > " + maxTableSizeBytes); return false; } if (statistics.getJoinStatistics().isEmpty()) { logNoPushdown(joinSignature, "join stats empty"); return false; } double joinDataSize = statistics.getJoinStatistics().get().getDataSize(); if (joinDataSize < getJoinPushdownAutomaticJoinToTablesRatio(session) * (leftDataSize + rightDataSize)) { LOG.debug("triggering join pushdown for %s", joinSignature); return true; } logNoPushdown(joinSignature, () -> "joinDataSize " + joinDataSize + " >= " + getJoinPushdownAutomaticJoinToTablesRatio(session) + " * (leftDataSize " + leftDataSize + " + rightDataSize " + rightDataSize + ") = " + getJoinPushdownAutomaticJoinToTablesRatio(session) * (leftDataSize + rightDataSize)); return false; }
function
java
456
public static EM.Credential_SummaryCache GetSummary( int id ) { EM.Credential_SummaryCache item = new Data.Credential_SummaryCache(); using ( var context = new EntityContext() ) { item = context.Credential_SummaryCache .SingleOrDefault( s => s.CredentialId == id ); if ( item != null && item.CredentialId > 0 ) { } } return item; }
function
c#
457
def _last_volume_delete_initiator_group( self, conn, controllerConfigService, initiatorGroupInstanceName, extraSpecs, host=None): defaultInitiatorGroupName = None initiatorGroupInstance = conn.GetInstance(initiatorGroupInstanceName) initiatorGroupName = initiatorGroupInstance['ElementName'] protocol = self.utils.get_short_protocol_type(self.protocol) if host: defaultInitiatorGroupName = (( "OS-%(shortHostName)s-%(protocol)s-IG" % {'shortHostName': host, 'protocol': protocol})) if initiatorGroupName == defaultInitiatorGroupName: maskingViewInstanceNames = ( self.get_masking_views_by_initiator_group( conn, initiatorGroupInstanceName)) if len(maskingViewInstanceNames) == 0: LOG.debug( "Last volume associated with the initiator group - " "deleting the associated initiator group " "%(initiatorGroupName)s.", {'initiatorGroupName': initiatorGroupName}) self._delete_initiators_from_initiator_group( conn, controllerConfigService, initiatorGroupInstanceName, initiatorGroupName) self._delete_initiator_group(conn, controllerConfigService, initiatorGroupInstanceName, initiatorGroupName, extraSpecs) else: LOG.warning(_LW("Initiator group %(initiatorGroupName)s is " "associated with masking views and can't be " "deleted. Number of associated masking view " "is: %(nmv)d."), {'initiatorGroupName': initiatorGroupName, 'nmv': len(maskingViewInstanceNames)}) else: LOG.warning(_LW("Initiator group %(initiatorGroupName)s was " "not created by the VMAX driver so will " "not be deleted by the VMAX driver."), {'initiatorGroupName': initiatorGroupName})
function
python
458
private void validateVolumesWithSameDiskTiering(ChangedVolumes changedVolumes) throws IOException { if (dnConf.getConf().getBoolean(DFS_DATANODE_ALLOW_SAME_DISK_TIERING, DFS_DATANODE_ALLOW_SAME_DISK_TIERING_DEFAULT) && data.getMountVolumeMap() != null) { for (StorageLocation location : changedVolumes.newLocations) { if (StorageType.allowSameDiskTiering(location.getStorageType())) { File dir = new File(location.getUri()); while (!dir.exists()) { dir = dir.getParentFile(); if (dir == null) { throw new IOException("Invalid path: " + location + ": directory does not exist"); } } DF df = new DF(dir, dnConf.getConf()); String mount = df.getMount(); if (data.getMountVolumeMap().hasMount(mount)) { String errMsg = "Disk mount " + mount + " already has volume, when trying to add " + location + ". Please try removing mounts first" + " or restart datanode."; LOG.error(errMsg); throw new IOException(errMsg); } } } } }
function
java
459
func (u *Util) BlockExtFromBytes(bin []byte) (bx *BlockExt, err error) { bx = &BlockExt{ util: u, } bx.Header, err = u.ExtractBlockHeaderExtFromBlockBytes(bin) if err != nil { return nil, err } i := BlockCborInitialLength + len(bx.Header.Bytes) if i >= len(bin) { return nil, ErrInvalidBytes } if bin[i] != cbg.CborNull[0] { bx.Txs, err = u.TransactionExtSliceFromTransactionsBytes(bin[i:]) if err != nil { return nil, err } } return bx, nil }
function
go
460
async collect(aCount) { let response = await this.kojac.performRequest(this); let result = response.result(); if (!_.isArray(result) || result.length===0) return result; var resource = response.request.ops[0].key; return this.kojac.collectIds(resource,result,null,aCount); }
function
javascript
461
function Ze(t) { switch (t) { case D.OK: return L(); case D.CANCELLED: case D.UNKNOWN: case D.DEADLINE_EXCEEDED: case D.RESOURCE_EXHAUSTED: case D.INTERNAL: case D.UNAVAILABLE: case D.UNAUTHENTICATED: return !1; case D.INVALID_ARGUMENT: case D.NOT_FOUND: case D.ALREADY_EXISTS: case D.PERMISSION_DENIED: case D.FAILED_PRECONDITION: case D.ABORTED: case D.OUT_OF_RANGE: case D.UNIMPLEMENTED: case D.DATA_LOSS: return !0; default: return L(); } }
function
javascript
462
private static boolean overrideDefaultSettings( Log log, RepositoryRegistry repositoryRegistry, String settingsPathOrFile, boolean failIfFileNotFound ) throws MojoExecutionException { File settingsFile = PathUtil.buildSettingsFilePath( settingsPathOrFile ); if ( !settingsFile.exists() ) { if ( failIfFileNotFound ) { throw new MojoExecutionException( "NPANDAY-108-005: Configured settings file does not exist: " + settingsFile ); } else { log.warn( "NPANDAY-108-006: Settings file does not exist: " + settingsFile + "; current Mojo will adhere to configured defaults." ); return false; } } SettingsRepository settingsRepository = findSettingsFromRegistry( repositoryRegistry ); try { settingsRepository.clearAll(); } catch ( OperationNotSupportedException e ) { throw new MojoExecutionException( "NPANDAY-108-006: Error clearing settings repository.", e ); } try { settingsRepository.load( settingsFile.toURI().toURL() ); log.debug( "NPANDAY-108-007: Replaced default npanday-settings with contents from '" + settingsFile + "'." ); return true; } catch ( IOException e ) { throw new MojoExecutionException( "NPANDAY-108-003: Error loading " + settingsFile.getAbsolutePath(), e ); } catch( NPandayRepositoryException e ) { throw new MojoExecutionException( "NPANDAY-108-004: Error loading settings repository.", e ); } }
function
java
463
def _searchTree(f): @wraps(f) def inner(self, *args, **kwargs): name = f.__name__ path = f(self, *args, **kwargs) pattern = re.compile(path) data = DOMProcessor(self._responses, limit=self._max_mixtapes).findRegex( pattern ) if hasattr(self, "_artists"): data = data[: len(self._artists)] dunder = "_" + name setattr(self, dunder, data) return data return inner
function
python
464
func (s *server) FlowCreated(timestamp time.Time, uuid string, id inetdiag.SockID) { s.eventC <- &FlowEvent{ Event: Open, Timestamp: timestamp, ID: &id, UUID: uuid, } }
function
go
465
@SuppressWarnings("unchecked") @Path("/poll/{queue}/{subscriber}") @GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public JResponse<RestOpResponse> poll(@Context final HttpServletRequest req, @PathParam("queue") String queue, @PathParam("subscriber") String subscriber, @QueryParam("timeout") @DefaultValue("-1") long timeout) throws ServiceException { RestOpResponse response = new RestOpResponse(); response.setOperation(EOpType.Receive); response.setStarttime(System.currentTimeMillis()); try { checkState(); long t = q_timeout; if (timeout > 0) { t = timeout; } if (QueueRestServer.context().hasQueue(queue)) { Queue<M> q = (Queue<M>) QueueRestServer.context().queue(queue); Message<M> m = q.poll(subscriber, t); if (m != null) { StringDataResponse d = new StringDataResponse(); d.setResult(handler.serialize(m.data())); response.setData(d); response.setStatus(EServiceResponse.Success); } else { response.setStatus(EServiceResponse.Failed).getStatus() .setError(new DataNotFoundException("No records fetched from queue.")); } } else throw new ServiceException("Invalid Queue name. [name=" + queue + "]"); } catch (ServiceException e) { LogUtils.error(getClass(), e, log); LogUtils.stacktrace(getClass(), e, log); response.setStatus(EServiceResponse.Failed).getStatus().setError(e); } catch (Throwable t) { LogUtils.error(getClass(), t, log); LogUtils.stacktrace(getClass(), t, log); response.setStatus(EServiceResponse.Exception).getStatus().setError(t); } finally { response.setEndtime(System.currentTimeMillis()); } return JResponse.ok(response).build(); }
function
java
466
fn from_str(s: &str) -> Result<Self, Self::Err> { // Strip optional prefix let s = if s.starts_with("0x") { &s[2..] } else { &s }; // Signature has exactly 130 characters (65 as bytes) ensure!( s.len() == 130, "Signature as a string should contain exactly 130 characters" ); // Parse hexadecimal form back to bytes let bytes = hex_str_to_bytes(&s)?; Signature::from_bytes(&bytes) }
function
rust
467
public final class EnvironmentShare { private final EnvironmentAtom atom; private final byte[] share; public EnvironmentAtom getAtom() { return atom; } public byte[] getShare() { return share; } public EnvironmentShare(final EnvironmentAtom atom, final byte[] share) { this.atom = atom; this.share = share; } }
class
java
468
def size_explored_space(self): space_size = 1 for arr in self.parameter_space: space_size = space_size * len(arr) unique_parameters = np.unique(self.history["parameters"], axis=0) percentage_explored_space = len(unique_parameters) / space_size * 100 percentage_static_states = ( (len(self.history["parameters"]) - len(unique_parameters)) / len(self.history["parameters"]) * 100 ) return percentage_explored_space, percentage_static_states
function
python
469
func (w *World) IShouldHavePayments(expected int) error { return DoThen(w.IGetAllPayments(), func() error { return DoThen(w.IShouldHaveStatusCode(200), func() error { return DoThen(w.IShouldHaveAJson(), func() error { return w.ThatJsonShouldHaveItems(expected) }) }) }) }
function
go
470
private class TopWindowListener implements ComponentListener { /** * This method is invoked when top-level window is resized. This method * closes current menu hierarchy. * * @param e The ComponentEvent */ public void componentResized(ComponentEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); manager.clearSelectedPath(); } /** * This method is invoked when top-level window is moved. This method * closes current menu hierarchy. * * @param e The ComponentEvent */ public void componentMoved(ComponentEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); manager.clearSelectedPath(); } /** * This method is invoked when top-level window is shown This method * does nothing by default. * * @param e The ComponentEvent */ public void componentShown(ComponentEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); manager.clearSelectedPath(); } /** * This method is invoked when top-level window is hidden This method * closes current menu hierarchy. * * @param e The ComponentEvent */ public void componentHidden(ComponentEvent e) { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); manager.clearSelectedPath(); } }
class
java
471
public class ImcCALL extends ImcExpr { public final Label label; private final Vector<ImcExpr> args; public ImcCALL(Label label, Vector<ImcExpr> args) { this.label = label; this.args = new Vector<ImcExpr>(args); } public Vector<ImcExpr> args() { return new Vector<ImcExpr>(args); } @Override public <Result, Arg> Result accept(ImcVisitor<Result, Arg> visitor, Arg accArg) { return visitor.visit(this, accArg); } }
class
java
472
@SuppressWarnings({ "unchecked", "rawtypes" }) public List<GcCaseIgnoreHashMap> selectListMap(){ List<Map> list = selectList(Map.class); List<GcCaseIgnoreHashMap> newList = new ArrayList<GcCaseIgnoreHashMap>(); for (Map map : list){ GcCaseIgnoreHashMap mapToReturn= new GcCaseIgnoreHashMap(); mapToReturn.putAll(map); newList.add(mapToReturn); } return newList; }
function
java
473
public class CoverageSuite { public BufferedReader getTestCase(String name) throws IOException { Path root = Paths.get(System.getProperty("user.dir"), ".cldrsuite"); Path path = root.resolve(name + ".txt"); File file = path.toFile(); if (!file.exists()) { throw new RuntimeException("Test suite must be generated using the codegen tool"); } return new BufferedReader(new FileReader(file)); } public static Boolean boolValue(JsonElement e) { return e.isJsonNull() ? null : e.getAsBoolean(); } public static Integer intValue(JsonElement e) { return e.isJsonNull() ? null : e.getAsInt(); } public static Double doubleValue(JsonElement e) { return e.isJsonNull() ? null : e.getAsDouble(); } public static String stringValue(JsonElement e) { return e.isJsonNull() ? null : e.getAsString(); } public static <T> T typeValue(JsonElement e, Function<String, T> f) { return e.isJsonNull() ? null : f.apply(e.getAsString()); } public static <T> List<T> typeArray(JsonElement e, Function<JsonElement, T> f) { List<T> results = new ArrayList<>(); JsonArray arr = e.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { JsonElement elem = arr.get(i); T value = e.isJsonNull() ? null : f.apply(elem.getAsJsonObject()); results.add(value); } return results; } public static String repeat(String s, int count) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < count; i++) { buf.append(s); } return buf.toString(); } public static List<Integer> intArray(JsonElement json) { JsonArray arr = json.getAsJsonArray(); List<Integer> result = new ArrayList<>(); for (int i = 0; i < arr.size(); i++) { Integer value = arr.get(i).getAsInt(); result.add(value); } return result; } public static List<Long> longArray(JsonElement json) { JsonArray arr = json.getAsJsonArray(); List<Long> result = new ArrayList<>(); for (int i = 0; i < arr.size(); i++) { Long value = arr.get(i).getAsLong(); result.add(value); } return result; } public static List<Double> doubleArray(JsonElement json) { JsonArray arr = json.getAsJsonArray(); List<Double> result = new ArrayList<>(); for (int i = 0; i < arr.size(); i++) { Double value = arr.get(i).getAsDouble(); result.add(value); } return result; } public static List<String> stringArray(JsonElement json) { JsonArray arr = json.getAsJsonArray(); List<String> result = new ArrayList<>(); for (int i = 0; i < arr.size(); i++) { String value = arr.get(i).getAsString(); result.add(value); } return result; } public static List<Decimal> decimalArray(JsonElement json) { List<Decimal> result = new ArrayList<>(); JsonArray arr = json.getAsJsonArray(); for (int i = 0; i < arr.size(); i++) { JsonArray raw = arr.get(i).getAsJsonArray(); long[] data = longArray(raw.get(0)).stream().mapToLong(e -> e).toArray(); int sign = raw.get(1).getAsInt(); int exp = raw.get(2).getAsInt(); int flag = raw.get(3).getAsInt(); Decimal n = new Decimal(sign, exp, data, flag); result.add(n); } return result; } }
class
java
474
function isTrueOrStrTrue(strOrBool) { if (typeof strOrBool == 'undefined' || strOrBool == null) return false; if (typeof strOrBool == 'boolean' && strOrBool == true) return true; if (typeof strOrBool == 'string' && strOrBool.toLowerCase() == "true") return true; return false; }
function
javascript
475
private void removeBadMatches(Dependency dependency) { final Set<Identifier> identifiers = dependency.getIdentifiers(); final Iterator<Identifier> itr = identifiers.iterator(); /* TODO - can we utilize the pom's groupid and artifactId to filter??? most of * these are due to low quality data. Other idea would be to say any CPE * found based on LOW confidence evidence should have a different CPE type? (this * might be a better solution then just removing the URL for "best-guess" matches). */ while (itr.hasNext()) { final Identifier i = itr.next(); if ("cpe".equals(i.getType())) { if ((i.getValue().matches(".*c\\+\\+.*") || i.getValue().startsWith("cpe:/a:file:file") || i.getValue().startsWith("cpe:/a:mozilla:mozilla") || i.getValue().startsWith("cpe:/a:cvs:cvs") || i.getValue().startsWith("cpe:/a:ftp:ftp") || i.getValue().startsWith("cpe:/a:tcp:tcp") || i.getValue().startsWith("cpe:/a:ssh:ssh") || i.getValue().startsWith("cpe:/a:lookup:lookup")) && (dependency.getFileName().toLowerCase().endsWith(".jar") || dependency.getFileName().toLowerCase().endsWith("pom.xml") || dependency.getFileName().toLowerCase().endsWith(".dll") || dependency.getFileName().toLowerCase().endsWith(".exe") || dependency.getFileName().toLowerCase().endsWith(".nuspec") || dependency.getFileName().toLowerCase().endsWith(".zip") || dependency.getFileName().toLowerCase().endsWith(".sar") || dependency.getFileName().toLowerCase().endsWith(".apk") || dependency.getFileName().toLowerCase().endsWith(".tar") || dependency.getFileName().toLowerCase().endsWith(".gz") || dependency.getFileName().toLowerCase().endsWith(".tgz") || dependency.getFileName().toLowerCase().endsWith(".ear") || dependency.getFileName().toLowerCase().endsWith(".war"))) { itr.remove(); } else if ((i.getValue().startsWith("cpe:/a:jquery:jquery") || i.getValue().startsWith("cpe:/a:prototypejs:prototype") || i.getValue().startsWith("cpe:/a:yahoo:yui")) && (dependency.getFileName().toLowerCase().endsWith(".jar") || dependency.getFileName().toLowerCase().endsWith("pom.xml") || dependency.getFileName().toLowerCase().endsWith(".dll") || dependency.getFileName().toLowerCase().endsWith(".exe"))) { itr.remove(); } else if ((i.getValue().startsWith("cpe:/a:microsoft:excel") || i.getValue().startsWith("cpe:/a:microsoft:word") || i.getValue().startsWith("cpe:/a:microsoft:visio") || i.getValue().startsWith("cpe:/a:microsoft:powerpoint") || i.getValue().startsWith("cpe:/a:microsoft:office") || i.getValue().startsWith("cpe:/a:core_ftp:core_ftp")) && (dependency.getFileName().toLowerCase().endsWith(".jar") || dependency.getFileName().toLowerCase().endsWith(".ear") || dependency.getFileName().toLowerCase().endsWith(".war") || dependency.getFileName().toLowerCase().endsWith("pom.xml"))) { itr.remove(); } else if (i.getValue().startsWith("cpe:/a:apache:maven") && !dependency.getFileName().toLowerCase().matches("maven-core-[\\d\\.]+\\.jar")) { itr.remove(); } else if (i.getValue().startsWith("cpe:/a:m-core:m-core") && !dependency.getEvidenceUsed().containsUsedString("m-core")) { itr.remove(); } else if (i.getValue().startsWith("cpe:/a:jboss:jboss") && !dependency.getFileName().toLowerCase().matches("jboss-?[\\d\\.-]+(GA)?\\.jar")) { itr.remove(); } } } }
function
java
476
HFONT termMakeFont(const HHTERM hhTerm, const BOOL fUnderline, const BOOL fHigh, const BOOL fWide, const BOOL fSymbol) { LOGFONT lf; HFONT hFont; lf = hhTerm->lf; lf.lfWidth = hhTerm->xChar; if (fSymbol) { StrCharCopy(lf.lfFaceName, "Arial Alternative Symbol"); } if (fUnderline) lf.lfUnderline = 1; if (fHigh) lf.lfHeight *= 2; if (fWide) lf.lfWidth *= 2; if ((hFont = CreateFontIndirect(&lf)) == 0) assert(FALSE); return hFont; }
function
c
477
class Solution { public: bool wordPattern(string pattern, string str) { int index_p[26] = {0}; vector<int> pattern_p(pattern.size()); for(int i = 0; i < pattern.size(); ++i){ if(index_p[pattern[i] - 'a']) pattern_p[i] = index_p[pattern[i] - 'a']; else index_p[pattern[i] - 'a'] = i + 1; } vector<string> strs(process(str)); if(strs.size() != pattern.size()) return false; unordered_map<string,int> index_s; vector<int> pattern_s(pattern.size()); for(int i = 0; i < strs.size(); ++i){ if(index_s[strs[i]]) pattern_s[i] = index_s[strs[i]]; else index_s[strs[i]] = i + 1; } for(int i = 0; i < pattern.size(); ++i){ if(pattern_p[i] != pattern_s[i]) return false; } return true; } private: vector<string> process(string& str){ vector<string> strs; int i = 0; int l = 0; int r = 0; while(i < str.size()){ while(i < str.size() && str[i] != ' ') ++i; r = i++; if(r > l){ strs.emplace_back(str.substr(l,r - l)); } l = r + 1; } return strs; } }
class
c++
478
public class AutoAddInvertedIndex { public enum Strategy { QUERY // Add inverted index based on the query result } public enum Mode { NEW, // Apply only to tables without inverted index REMOVE, // Remove all auto-generated inverted index REFRESH, // Refresh the auto-generated inverted index APPEND // Append to the auto-generated inverted index } public static final long DEFAULT_TABLE_SIZE_THRESHOLD = 10_000_000; public static final long DEFAULT_CARDINALITY_THRESHOLD = 100; public static final int DEFAULT_MAX_NUM_INVERTED_INDEX_ADDED = 2; private static final Logger LOGGER = LoggerFactory.getLogger(AutoAddInvertedIndex.class); private final String _clusterName; private final String _controllerAddress; private final String _brokerAddress; private final ZKHelixAdmin _helixAdmin; private final ZkHelixPropertyStore<ZNRecord> _propertyStore; private final Strategy _strategy; private final Mode _mode; private String _tableNamePattern = null; private long _tableSizeThreshold = DEFAULT_TABLE_SIZE_THRESHOLD; private long _cardinalityThreshold = DEFAULT_CARDINALITY_THRESHOLD; private int _maxNumInvertedIndexAdded = DEFAULT_MAX_NUM_INVERTED_INDEX_ADDED; public AutoAddInvertedIndex(@Nonnull String zkAddress, @Nonnull String clusterName, @Nonnull String controllerAddress, @Nonnull String brokerAddress, @Nonnull Strategy strategy, @Nonnull Mode mode) { _clusterName = clusterName; _controllerAddress = controllerAddress; _brokerAddress = brokerAddress; _helixAdmin = new ZKHelixAdmin(zkAddress); _propertyStore = new ZkHelixPropertyStore<>(zkAddress, new ZNRecordSerializer(), PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, clusterName)); _strategy = strategy; _mode = mode; } public void overrideDefaultSettings(@Nonnull String tableNamePattern, long tableSizeThreshold, long cardinalityThreshold, int maxNumInvertedIndex) { _tableNamePattern = tableNamePattern; _tableSizeThreshold = tableSizeThreshold; _cardinalityThreshold = cardinalityThreshold; _maxNumInvertedIndexAdded = maxNumInvertedIndex; } public void run() throws Exception { if (_strategy == Strategy.QUERY) { runQueryStrategy(); } else { throw new IllegalStateException("Invalid Strategy: " + _strategy); } } private void runQueryStrategy() throws Exception { // Get all resources in cluster List<String> resourcesInCluster = _helixAdmin.getResourcesInCluster(_clusterName); for (String tableNameWithType : resourcesInCluster) { // Skip non-table resources if (!TableNameBuilder.isTableResource(tableNameWithType)) { continue; } // Skip tables that do not match the defined name pattern if (_tableNamePattern != null && !tableNameWithType.matches(_tableNamePattern)) { continue; } LOGGER.info("Table: {} matches the table name pattern: {}", tableNameWithType, _tableNamePattern); // Get the inverted index config TableConfig tableConfig = ZKMetadataProvider.getTableConfig(_propertyStore, tableNameWithType); Preconditions.checkNotNull(tableConfig); IndexingConfig indexingConfig = tableConfig.getIndexingConfig(); List<String> invertedIndexColumns = indexingConfig.getInvertedIndexColumns(); boolean autoGeneratedInvertedIndex = indexingConfig.isAutoGeneratedInvertedIndex(); // Handle auto-generated inverted index if (autoGeneratedInvertedIndex) { Preconditions.checkState(!invertedIndexColumns.isEmpty(), "Auto-generated inverted index list is empty"); // NEW mode, skip if (_mode == Mode.NEW) { LOGGER.info( "Table: {}, skip adding inverted index because it has auto-generated inverted index and under NEW mode", tableNameWithType); continue; } // REMOVE mode, remove the inverted index and update if (_mode == Mode.REMOVE) { invertedIndexColumns.clear(); indexingConfig.setAutoGeneratedInvertedIndex(false); if (updateIndexConfig(tableNameWithType, tableConfig)) { LOGGER.info("Table: {}, removed auto-generated inverted index", tableNameWithType); } else { LOGGER.error("Table: {}, failed to remove auto-generated inverted index", tableNameWithType); } continue; } // REFRESH mode, remove auto-generated inverted index if (_mode == Mode.REFRESH) { invertedIndexColumns.clear(); } } else { // Handle null inverted index columns if (invertedIndexColumns == null) { invertedIndexColumns = new ArrayList<>(); indexingConfig.setInvertedIndexColumns(invertedIndexColumns); } // Remove empty strings int emptyStringIndex; while ((emptyStringIndex = invertedIndexColumns.indexOf("")) != -1) { invertedIndexColumns.remove(emptyStringIndex); } // Skip non-empty non-auto-generated inverted index if (!invertedIndexColumns.isEmpty()) { LOGGER.info("Table: {}, skip adding inverted index because it has non-auto-generated inverted index", tableNameWithType); continue; } } // Skip tables without a schema Schema tableSchema = ZKMetadataProvider.getTableSchema(_propertyStore, tableNameWithType); if (tableSchema == null) { LOGGER.info("Table: {}, skip adding inverted index because it does not have a schema", tableNameWithType); continue; } // Skip tables without dimensions List<String> dimensionNames = tableSchema.getDimensionNames(); if (dimensionNames.size() == 0) { LOGGER.info("Table: {}, skip adding inverted index because it does not have any dimension column", tableNameWithType); continue; } // Skip tables without a proper time column String timeColumnName = tableConfig.getValidationConfig().getTimeColumnName(); if (timeColumnName == null) { LOGGER.info( "Table: {}, skip adding inverted index because it does not have a time column specified in the table config", tableNameWithType); continue; } DateTimeFieldSpec dateTimeSpec = tableSchema.getSpecForTimeColumn(timeColumnName); if (dateTimeSpec == null || dateTimeSpec.getDataType() == FieldSpec.DataType.STRING) { LOGGER.info("Table: {}, skip adding inverted index because it does not have a numeric time column", tableNameWithType); continue; } TimeUnit timeUnit = new DateTimeFormatSpec(dateTimeSpec.getFormat()).getColumnUnit(); if (timeUnit != TimeUnit.DAYS) { LOGGER.warn("Table: {}, time column {] has non-DAYS time unit: {}", timeColumnName, timeUnit); } // Only add inverted index to table larger than a threshold JsonNode queryResponse = sendQuery("SELECT COUNT(*) FROM " + tableNameWithType); long numTotalDocs = queryResponse.get("totalDocs").asLong(); LOGGER.info("Table: {}, number of total documents: {}", tableNameWithType, numTotalDocs); if (numTotalDocs <= _tableSizeThreshold) { LOGGER.info("Table: {}, skip adding inverted index because the table is too small", tableNameWithType); continue; } // Get each dimension's cardinality on one timestamp's data queryResponse = sendQuery("SELECT Max(" + timeColumnName + ") FROM " + tableNameWithType); long maxTimeStamp = queryResponse.get("aggregationResults").get(0).get("value").asLong(); LOGGER.info("Table: {}, max time column {}: {}", tableNameWithType, timeColumnName, maxTimeStamp); // Query DISTINCTCOUNT on all dimensions in one query might cause timeout, so query them separately List<ResultPair> resultPairs = new ArrayList<>(); for (String dimensionName : dimensionNames) { String query = "SELECT DISTINCTCOUNT(" + dimensionName + ") FROM " + tableNameWithType + " WHERE " + timeColumnName + " = " + maxTimeStamp; queryResponse = sendQuery(query); JsonNode result = queryResponse.get("aggregationResults").get(0); resultPairs.add(new ResultPair(result.get("function").asText().substring("distinctCount_".length()), result.get("value").asLong())); } // Sort the dimensions based on their cardinalities Collections.sort(resultPairs); // Add the top dimensions into inverted index columns int numInvertedIndex = Math.min(_maxNumInvertedIndexAdded, resultPairs.size()); for (int i = 0; i < numInvertedIndex; i++) { ResultPair resultPair = resultPairs.get(i); String columnName = resultPair._key; long cardinality = resultPair._value; if (cardinality > _cardinalityThreshold) { // Do not append inverted index if already exists if (!invertedIndexColumns.contains(columnName)) { invertedIndexColumns.add(columnName); } LOGGER.info("Table: {}, add inverted index to column {} with cardinality: {}", tableNameWithType, columnName, cardinality); } else { LOGGER.info("Table: {}, skip adding inverted index to column {} with cardinality: {}", tableNameWithType, columnName, cardinality); break; } } // Update indexing config if (!invertedIndexColumns.isEmpty()) { indexingConfig.setAutoGeneratedInvertedIndex(true); if (updateIndexConfig(tableNameWithType, tableConfig)) { LOGGER.info("Table: {}, added inverted index to columns: {}", tableNameWithType, invertedIndexColumns); } else { LOGGER .error("Table: {}, failed to add inverted index to columns: {}", tableNameWithType, invertedIndexColumns); } } else { if (autoGeneratedInvertedIndex) { Preconditions.checkState(_mode == Mode.REFRESH); // Remove existing auto-generated inverted index because no column matches all the conditions indexingConfig.setAutoGeneratedInvertedIndex(false); if (updateIndexConfig(tableNameWithType, tableConfig)) { LOGGER.info("Table: {}, removed auto-generated inverted index", tableNameWithType); } else { LOGGER.error("Table: {}, failed to remove auto-generated inverted index", tableNameWithType); } } } } } private JsonNode sendQuery(String query) throws Exception { URLConnection urlConnection = new URL("http://" + _brokerAddress + "/query").openConnection(); urlConnection.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); writer.write(JsonUtils.newObjectNode().put("pql", query).toString()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8")); return JsonUtils.stringToJsonNode(reader.readLine()); } private boolean updateIndexConfig(String tableName, TableConfig tableConfig) throws Exception { String request = ControllerRequestURLBuilder.baseUrl("http://" + _controllerAddress).forTableUpdateIndexingConfigs(tableName); HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(request).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8")); writer.write(tableConfig.toJsonString()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); return reader.readLine().equals("done"); } private static class ResultPair implements Comparable<ResultPair> { private final String _key; private final long _value; public ResultPair(String key, long value) { _key = key; _value = value; } @Override public int compareTo(@Nonnull ResultPair o) { return Long.compare(o._value, _value); } @Override public String toString() { return _key + ": " + _value; } } }
class
java
479
def find_node(self, other_name): root = self while root.parent is not None: root = root.parent for node in root.get_children_recursive(): if node.name == other_name: return node return None
function
python
480
public class BiologicalDataItem extends AbstractSecuredEntity { private BiologicalDataItemResourceType type; private String path; private String source; private BiologicalDataItemFormat format; private Date createdDate; private Long bucketId; private Map<String, String> metadata; public BiologicalDataItem() { // no-op } public BiologicalDataItem(Long id) { setId(id); } @Override public AbstractSecuredEntity getParent() { return null; } @Override public AclClass getAclClass() { return null; } public BiologicalDataItemResourceType getType() { return type; } public void setType(BiologicalDataItemResourceType type) { this.type = type; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public BiologicalDataItemFormat getFormat() { return format; } public final void setFormat(BiologicalDataItemFormat format) { this.format = format; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Long getBucketId() { return bucketId; } public void setBucketId(Long bucketId) { this.bucketId = bucketId; } public Map<String, String> getMetadata() { return metadata; } public void setMetadata(final Map<String, String> metadata) { this.metadata = metadata; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } return obj.getClass() == this.getClass() && Objects.equals(getId(), ((BiologicalDataItem) obj).getId()); } @Override public int hashCode() { return (int) BiologicalDataItem.getBioDataItemId(this).longValue(); } /** * Returns biological data item ID of any {@link BiologicalDataItem} ancestor * @param item an {@link BiologicalDataItem} ancestor * @return {@link BiologicalDataItem} ancestor's biological data item ID */ public static Long getBioDataItemId(BiologicalDataItem item) { if (item instanceof FeatureFile) { return ((FeatureFile) item).getBioDataItemId(); } else { if (item instanceof Reference) { return ((Reference) item).getBioDataItemId(); } else { return item.getId(); } } } }
class
java
481
HRESULT CodeRedDownloadCallback(const TCHAR* url, const TCHAR* file_path, void* callback_argument) { ++metric_cr_callback_total; int http_status_code = 0; HRESULT hr = DownloadCodeRedFileAsLoggedOnUser(url, file_path, callback_argument, &http_status_code); if (FAILED(hr) && (http_status_code != HTTP_STATUS_NO_CONTENT)) { hr = DownloadCodeRedFile(url, file_path, callback_argument, &http_status_code); } switch (http_status_code) { case HTTP_STATUS_OK: ++metric_cr_callback_status_200; break; case HTTP_STATUS_NO_CONTENT: ++metric_cr_callback_status_204; break; default: ++metric_cr_callback_status_other; break; } return hr; }
function
c++
482
private boolean promptOpenFilePath() { Stage choosingStage = new Stage(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open Resource File"); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("Text Files", "*.txt")); File selectedFile = fileChooser.showOpenDialog(choosingStage); if (selectedFile != null) { filePath = selectedFile.getPath(); return true; } return false; }
function
java
483
public class RatSamPlotter extends RawDataPlotter { private enum PlotType { VALUES, COUNTS; public static PlotType fromString(String s) { if (s == null) { return null; } else if (s.equals("values")) { return VALUES; } else if (s.equals("cnts")) { return COUNTS; } else { return null; } } } private PlotType plotType; private static Map<Integer, Channel> channelsMap; RSAMData data; /** * Default constructor. */ public RatSamPlotter() { super(); ranks = false; } /** * Initialize internal data from PlotComponent. * * @param comp PlotComponent */ protected void getInputs(PlotComponent comp) throws Valve3Exception { parseCommonParameters(comp); channelLegendsCols = new String[1]; String pt = comp.get("plotType"); if (pt == null) { plotType = PlotType.VALUES; } else { plotType = PlotType.fromString(pt); if (plotType == null) { throw new Valve3Exception("Illegal plot type: " + pt); } } switch (plotType) { case VALUES: leftLines = 0; axisMap = new LinkedHashMap<Integer, String>(); // validateDataManipOpts(component); axisMap.put(0, "L"); leftUnit = "RatSAM"; leftLines++; break; case COUNTS: break; default: break; } } /** * Gets binary data from VDX. * * @param comp PlotComponent */ protected void getData(PlotComponent comp) throws Valve3Exception { // initialize variables boolean exceptionThrown = false; String exceptionMsg = ""; VDXClient client = null; // create a map of all the input parameters Map<String, String> params = new LinkedHashMap<String, String>(); params.put("source", vdxSource); params.put("action", "ratdata"); params.put("ch", ch); params.put("st", Double.toString(startTime)); params.put("et", Double.toString(endTime)); params.put("plotType", plotType.toString()); addDownsamplingInfo(params); // checkout a connection to the database Pool<VDXClient> pool = null; pool = Valve3.getInstance().getDataHandler().getVDXClient(vdxClient); if (pool != null) { client = pool.checkout(); try { data = (RSAMData) client.getBinaryData(params); } catch (UtilException e) { exceptionThrown = true; exceptionMsg = e.getMessage(); } catch (Exception e) { exceptionThrown = true; exceptionMsg = e.getMessage(); } // if data was collected if (data != null && data.rows() > 0) { data.adjustTime(timeOffset); } // check back in our connection to the database pool.checkin(client); } // if a data limit message exists, then throw exception if (exceptionThrown) { throw new Valve3Exception(exceptionMsg); } } /** * Initialize DataRenderer, add it to plot, remove mean from rsam data if needed and render rsam * values to PNG image in local file. * * @param v3p Valve3Plot * @param comp PlotComponent * @param channel1 Channel * @param channel2 Channel * @param rd RSAMData * @param currentComp int * @param compBoxHeight int */ protected void plotValues(Valve3Plot v3p, PlotComponent comp, Channel channel1, Channel channel2, RSAMData rd, int currentComp, int compBoxHeight) throws Valve3Exception { String channelCode1 = channel1.getCode().replace('$', ' ').replace('_', ' ').replace(',', '/'); String channelCode2 = channel2.getCode().replace('$', ' ').replace('_', ' ').replace(',', '/'); channel1.setCode(channelCode1 + "-" + channelCode2); GenericDataMatrix gdm = new GenericDataMatrix(rd.getData()); channelLegendsCols[0] = String.format("%s %s", channel1.getCode(), leftUnit); if (forExport) { // Add column header to csvHdrs String[] hdr = {null, null, channel1.getCode(), leftUnit}; csvHdrs.add(hdr); // Initialize data for export; add to set for CSV ExportData ed = new ExportData(csvIndex, new MatrixExporter(gdm.getData(), ranks, axisMap)); csvData.add(ed); } else { try { MatrixRenderer leftMR = getLeftMatrixRenderer(comp, channel1, gdm, currentComp, compBoxHeight, 0, leftUnit); v3p.getPlot().addRenderer(leftMR); comp.setTranslation(leftMR.getDefaultTranslation(v3p.getPlot().getHeight())); comp.setTranslationType("ty"); v3p.addComponent(comp); } catch (Exception e) { e.printStackTrace(); } } } /** * Loop through the list of channels and create plots. * * @param v3p Valve3Plot * @param comp PlotComponent */ public void plotData(Valve3Plot v3p, PlotComponent comp) throws Valve3Exception { String[] channels = ch.split(","); Channel channel1 = channelsMap.get(Integer.valueOf(channels[0])); Channel channel2 = channelsMap.get(Integer.valueOf(channels[1])); // calculate the number of plot components that will be displayed per channel int channelCompCount = 1; // total components is components per channel * number of channels compCount = channelCompCount; // setting up variables to decide where to plot this component int currentComp = 1; int compBoxHeight = comp.getBoxHeight(); switch (plotType) { case VALUES: plotValues(v3p, comp, channel1, channel2, data, currentComp, compBoxHeight); if (!forExport) { v3p.setCombineable(true); v3p.setTitle(Valve3.getInstance().getMenuHandler().getItem(vdxSource).name + " Values"); } break; case COUNTS: if (!forExport) { v3p.setCombineable(false); } break; default: break; } } /** * Concrete realization of abstract method. Generate PNG images for values or event count * histograms (depends from plot type) to file with random name. * * @param v3p Valve3Plot * @param comp PlotComponent * @see Plotter */ public void plot(Valve3Plot v3p, PlotComponent comp) throws Valve3Exception, PlotException { forExport = (v3p == null); channelsMap = getChannels(vdxSource, vdxClient); comp.setPlotter(this.getClass().getName()); getInputs(comp); // plot configuration if (!forExport) { v3p.setExportable(true); } // this is a legitimate request so lookup the data from the database and plot it getData(comp); plotData(v3p, comp); if (!forExport) { writeFile(v3p); } } }
class
java
484
public static Map<String, Object> makeIngestPipelineDefinition(String grokPattern, String timestampField, List<String> timestampFormats, boolean needClientTimezone) { if (grokPattern == null && timestampField == null) { return null; } Map<String, Object> pipeline = new LinkedHashMap<>(); pipeline.put(Pipeline.DESCRIPTION_KEY, "Ingest pipeline created by file structure finder"); List<Map<String, Object>> processors = new ArrayList<>(); if (grokPattern != null) { Map<String, Object> grokProcessorSettings = new LinkedHashMap<>(); grokProcessorSettings.put("field", "message"); grokProcessorSettings.put("patterns", Collections.singletonList(grokPattern)); processors.add(Collections.singletonMap("grok", grokProcessorSettings)); } if (timestampField != null) { Map<String, Object> dateProcessorSettings = new LinkedHashMap<>(); dateProcessorSettings.put("field", timestampField); if (needClientTimezone) { dateProcessorSettings.put("timezone", "{{ " + BEAT_TIMEZONE_FIELD + " }}"); } dateProcessorSettings.put("formats", timestampFormats); processors.add(Collections.singletonMap("date", dateProcessorSettings)); } if (grokPattern != null && timestampField != null) { processors.add(Collections.singletonMap("remove", Collections.singletonMap("field", timestampField))); } pipeline.put(Pipeline.PROCESSORS_KEY, processors); return pipeline; }
function
java
485
public static Properties kafkaProducerProperties(List<String> serverAddresses, String groupID) { Properties p = new Properties(); p.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, String.join(",", serverAddresses)); p.setProperty(ProducerConfig.CLIENT_ID_CONFIG, groupID + "_producer"); p.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); p.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); p.setProperty(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, "50000000"); return p; }
function
java
486
dom_exception dom_html_input_element_get_default_value( dom_html_input_element *ele, dom_string **default_value) { *default_value = ele->default_value; if (*default_value != NULL) dom_string_ref(*default_value); return DOM_NO_ERR; }
function
c
487
@SuppressWarnings("unchecked") private void initComponents() { jBproduto = new javax.swing.JButton(); jBmtp = new javax.swing.JButton(); jBvoltar = new javax.swing.JButton(); jBfornecedor = new javax.swing.JButton(); jBcliente = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Cadastrar "); jBproduto.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/produtos.png"))); jBproduto.setText("Produto"); jBproduto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBprodutoActionPerformed(evt); } }); jBmtp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/matéria.png"))); jBmtp.setText("Matéria Prima"); jBmtp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBmtpActionPerformed(evt); } }); jBvoltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/voltar.png"))); jBvoltar.setText("Voltar"); jBvoltar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBvoltarActionPerformed(evt); } }); jBfornecedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/fornecedor.png"))); jBfornecedor.setText("Fornecedor"); jBfornecedor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBfornecedorActionPerformed(evt); } }); jBcliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/cliente.png"))); jBcliente.setText("Cliente"); jBcliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBclienteActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBvoltar)) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jBproduto, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE) .addComponent(jBcliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 113, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jBmtp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBfornecedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(73, 73, 73)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(jBproduto) .addGap(39, 39, 39)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jBmtp) .addGap(31, 31, 31))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jBcliente, javax.swing.GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE) .addComponent(jBfornecedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(51, 51, 51) .addComponent(jBvoltar) .addContainerGap(72, Short.MAX_VALUE)) ); pack(); }
function
java
488
def sort_by(self, metric, increasing=True): if metric[-1] != ')': metric += '()' c_values = [list(x) for x in zip(*sorted(eval('self.' + metric + '.items()'), key = lambda(k,v): v))] c_values.insert(1,[self.get_hyperparams(model_id, display=False) for model_id in c_values[0]]) if not increasing: for col in c_values: col.reverse() if metric[-2] == '(': metric = metric[:-2] return h2o.H2OTwoDimTable(col_header=['Model Id', 'Hyperparameters: [' + ', '.join(self.hyper_params.keys())+']', metric], table_header='Grid Search Results for ' + self.model.__class__.__name__, cell_values=zip(*c_values))
function
python
489
pub fn restore(&mut self) { self.canvas_render_context_2_d.restore(); if let Some((config, path_rect)) = self.saved_state.pop() { self.config = config; self.path_rect = path_rect; } }
function
rust
490
public class AdditionsAndRetractions { Model additions; Model retractions; public AdditionsAndRetractions(List<Model>adds, List<Model>retractions){ Model allAdds = ModelFactory.createDefaultModel(); Model allRetractions = ModelFactory.createDefaultModel(); for( Model model : adds ) { allAdds.add( model ); } for( Model model : retractions ){ allRetractions.add( model ); } this.setAdditions(allAdds); this.setRetractions(allRetractions); } public AdditionsAndRetractions(Model add, Model retract){ this.additions = add; this.retractions = retract; } public Model getAdditions() { return additions; } public void setAdditions(Model additions) { this.additions = additions; } public Model getRetractions() { return retractions; } public void setRetractions(Model retractions) { this.retractions = retractions; } @Override public String toString(){ String str = "{"; str += "\nadditions:["; if( getAdditions() != null ) { StringWriter writer = new StringWriter(); getAdditions().write(writer, "N3-PP"); str += "\n" + writer.toString() + "\n"; } str += "],\n"; str += "\nretractions:["; if( getRetractions() != null ) { StringWriter writer = new StringWriter(); getRetractions().write(writer, "N3-PP"); str += "\n" + writer.toString() + "\n"; } str += "],\n"; return str; } }
class
java
491
def elgamal_add(*ciphertexts: ElGamalCiphertext) -> ElGamalCiphertext: assert len(ciphertexts) != 0, "Must have one or more ciphertexts for elgamal_add" result = ciphertexts[0] for c in ciphertexts[1:]: result = ElGamalCiphertext( mult_p(result.pad, c.pad), mult_p(result.data, c.data) ) return result
function
python
492
@Override public Tree transformTree(Tree t) { if (VERBOSE) { log.info("Input to CoordinationTransformer: " + t); } t = tn.transformTree(t); if (VERBOSE) { log.info("After DependencyTreeTransformer: " + t); } if (t == null) { return t; } if (performMWETransformation) { t = MWETransform(t); if (VERBOSE) { log.info("After MWETransform: " + t); } t = prepCCTransform(t); if (VERBOSE) { log.info("After prepCCTransform: " + t); } } t = UCPtransform(t); if (VERBOSE) { log.info("After UCPTransformer: " + t); } t = CCtransform(t); if (VERBOSE) { log.info("After CCTransformer: " + t); } t = qp.transformTree(t); if (VERBOSE) { log.info("After QPTreeTransformer: " + t); } t = SQflatten(t); if (VERBOSE) { log.info("After SQ flattening: " + t); } t = dates.transformTree(t); if (VERBOSE) { log.info("After DateTreeTransformer: " + t); } t = removeXOverX(t); if (VERBOSE) { log.info("After removeXoverX: " + t); } t = combineConjp(t); if (VERBOSE) { log.info("After combineConjp: " + t); } t = moveRB(t); if (VERBOSE) { log.info("After moveRB: " + t); } t = changeSbarToPP(t); if (VERBOSE) { log.info("After changeSbarToPP: " + t); } t = rearrangeNowThat(t); if (VERBOSE) { log.info("After rearrangeNowThat: " + t); } return t; }
function
java
493
public List<Order> GetCartsByCustomerId(Guid customerId) { List<Order> orderList = orders .Include(o => o.Customer) .Include(o => o.Store) .Where(o => o.Customer.CustomerID == customerId && o.isCart == true && o.isOrdered == false) .ToList(); return orderList; }
function
c#
494
def assert_project_folder(project_folder, evaluation=False): import os import glob project_folder = os.path.abspath(project_folder) if not os.path.exists(os.path.join(project_folder, "hparams.yaml")): raise RuntimeError("Folder {} is not a valid DeepSleep project folder." " Must contain a 'hparams.yaml' " "file.".format(project_folder)) if evaluation: model_path = os.path.join(project_folder, "model") if not os.path.exists(model_path): raise RuntimeError("Folder {} is not a valid DeepSleep project " "folder. Must contain a 'model' " "subfolder.".format(project_folder)) models = glob.glob(os.path.join(model_path, "*.h5")) if not models: raise RuntimeError("Did not find any model parameter files in " "model subfolder {}. Model files should have" " extension '.h5' to " "be recognized.".format(project_folder))
function
python
495
public static string GetContents(HealthReport healthReport, string originalHealthTestEndpoint, List<HealthTestPageLink>? testingLinks = null) { string healthPage = Pages.Html.health; healthPage = healthPage .Replace("{HealthEndpoint}", originalHealthTestEndpoint) .Replace("<div id=\"hc\"></div>", PrepareHealthReport(healthReport)); if (testingLinks != null && testingLinks.Count > 0) { var links = new StringBuilder(); foreach (var link in testingLinks) { links.Append($"<li><a href='{link.TestEndpoint}'>{link.Name}</a> - {link.Description}</li>"); } healthPage = healthPage.Replace("<div id=\"links\"></div>", $"<h2>Testing links</h2><ul>{links}</ul>"); } return healthPage; }
function
c#
496
def find_longest_common_ngram(self, sequences: [str], max_ngram: int = 30, min_ngram: int = 3): seqs_ngrams = map(partial(self._allngram, min_ngram=min_ngram, max_ngram=max_ngram), sequences) intersection = reduce(set.intersection, seqs_ngrams) try: longest = max(intersection, key=len) except ValueError: longest = "" return longest if longest.strip() else None
function
python
497
def _adapter_connect(self): while True: try: addresses = self._getaddrinfo(self.params.host, self.params.port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP) break except _SOCKET_ERROR as error: if error.errno == errno.EINTR: continue LOGGER.critical('Could not get addresses to use: %s (%s)', error, self.params.host) return error error = "No socket addresses available" for sock_addr in addresses: error = self._create_and_connect_to_socket(sock_addr) if not error: self.socket.setblocking(0) return None self._cleanup_socket() return error
function
python
498
def _parameter_attribute_to_title(parameter: Parameter) -> str: attribute_symbols = { "epsilon": r"\varepsilon", "sigma": r"\sigma", "rmin_half": r"\dfrac{r_{min}}{2}", "charge_increment": "q", } indexless_attribute = re.sub(r"\d", "", parameter.attribute_name) if indexless_attribute not in attribute_symbols: return parameter.attribute_name if parameter.attribute_name in attribute_symbols: return f"${attribute_symbols[parameter.attribute_name]}$" symbol = attribute_symbols[indexless_attribute] title = re.sub(r"(\d+)", r"_{\1}", parameter.attribute_name) title = title.replace(indexless_attribute, symbol) return f"${title}$"
function
python
499