language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static List<String> queryStringToNamesAndValues(String encodedQuery) { List<String> result = new ArrayList<>(); for (int pos = 0; pos <= encodedQuery.length(); ) { int ampersandOffset = encodedQuery.indexOf('&', pos); if (ampersandOffset == -1) ampersandOffset = encodedQuery.leng...
java
protected ClusterClient<ApplicationId> deployInternal( ClusterSpecification clusterSpecification, String applicationName, String yarnClusterEntrypoint, @Nullable JobGraph jobGraph, boolean detached) throws Exception { // ------------------ Check if configuration is valid -------------------- validat...
java
@SuppressWarnings("nullness") private static <T> T castNonNull(@javax.annotation.Nullable T arg) { return arg; }
java
public static <T> String getCustomDeleteSQL(T t, List<Object> values, String setSql) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); Table table = DOInfoReader.getTable(t.getClass()); List<Field> fields = DOInfoReader.getColumns(t.getClass()); List<Field> keyFields = DOInfoReader.getKeyColu...
python
def zscan(self, key, cursor=0, match=None, count=None): """Incrementally iterate sorted sets elements and associated scores.""" args = [] if match is not None: args += [b'MATCH', match] if count is not None: args += [b'COUNT', count] fut = self.execute(b'Z...
python
def parents(self): # type: () -> List[CommitDetails] """ Parents of the this commit. """ if self._parents is None: self._parents = [CommitDetails.get(x) for x in self.parents_sha1] return self._parents
java
@Override public void injectServices(ServiceRegistryImplementor serviceRegistry) { if ( gridDialect instanceof ServiceRegistryAwareService ) { ( (ServiceRegistryAwareService) gridDialect ).injectServices( serviceRegistry ); } }
python
def set_link_status(link_id, status, **kwargs): """ Set the status of a link """ user_id = kwargs.get('user_id') #check_perm(user_id, 'edit_topology') try: link_i = db.DBSession.query(Link).filter(Link.id == link_id).one() except NoResultFound: raise ResourceNotFoundError...
python
def get_power_status() -> SystemPowerStatus: """Retrieves the power status of the system. The status indicates whether the system is running on AC or DC power, whether the battery is currently charging, how much battery life remains, and if battery saver is on or off. :raises OSError: if the call ...
java
private void updateDecorationPainterClippedBounds(JLayeredPane layeredPane, Point relativeLocationToOwner) { if (layeredPane == null) { decorationPainter.setClipBounds(null); } else { JComponent clippingComponent = getEffectiveClippingAncestor(); if (clippingComponent...
java
@Override void doSetValueAsQueryToken(FhirContext theContext, String theParamName, String theQualifier, String theParameter) { setValue(ParameterUtil.unescape(theParameter)); }
python
def _do_batched_write_command( namespace, operation, command, docs, check_keys, opts, ctx): """Batched write commands entry point.""" if ctx.sock_info.compression_context: return _batched_write_command_compressed( namespace, operation, command, docs, check_keys, opts, ctx) return...
python
def bootstrap_methods(self) -> BootstrapMethod: """ Returns the bootstrap methods table from the BootstrapMethods attribute, if one exists. If it does not, one will be created. :returns: Table of `BootstrapMethod` objects. """ bootstrap = self.attributes.find_one(name='B...
java
boolean scanIsEmpty() { // This 'slow' implementation is still faster than any external one // could be // (e.g.: (bitSet.length() == 0 || bitSet.nextSetBit(0) == -1)) // especially for small BitSets // Depends on the ghost bits being clear! final int count = numWords; for (int i = 0; i < count; ...
java
public static void generateWhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method, Pair<String, List<Pair<String, TypeName>>> where) { boolean nullable; // methodBuilder.addStatement("$T<String> // _sqlWhereParams=getWhereParamsArray()", ArrayList.class); for (Pair<String, TypeName> item : ...
java
private Path find(String namespace, String name) { Path expectedPath = pathForMetadata(namespace, name); if (DEFAULT_NAMESPACE.equals(namespace)) { // when using the default namespace, the namespace may not be in the path try { checkExists(rootFileSystem, expectedPath); return expect...
java
static void lockCloud() { if( _cloudLocked ) return; // Fast-path cutout synchronized(Paxos.class) { while( !_commonKnowledge ) try { Paxos.class.wait(); } catch( InterruptedException ie ) { } _cloudLocked = true; } }
python
def _AddForwardedIps(self, forwarded_ips, interface): """Configure the forwarded IP address on the network interface. Args: forwarded_ips: list, the forwarded IP address strings to configure. interface: string, the output device to use. """ for address in forwarded_ips: self.ip_forwar...
java
@SuppressWarnings("unchecked") public <T> List<T> getContextualInstances(final Class<T> type) { List<T> result = new ArrayList<T>(); for (Bean<?> bean : manager.getBeans(type)) { CreationalContext<T> context = (CreationalContext<T>) manager.createCreationalContext(bean); if (...
python
def to_capitalized_camel_case(snake_case_string): """ Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var" would become "SomeVar". :param snake_case_string: Snake-cased string to convert to camel case. :returns: Camel-cased version of snake_case_...
java
@Override public EClass getIfcSurfaceStyleRendering() { if (ifcSurfaceStyleRenderingEClass == null) { ifcSurfaceStyleRenderingEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(681); } return ifcSurfaceStyleRenderingEClass; }
python
def write_to(fpath, to_write, aslines=False, verbose=None, onlyifdiff=False, mode='w', n=None): """ Writes text to a file. Automatically encodes text as utf8. Args: fpath (str): file path to_write (str): text to write (must be unicode text) aslines (bool): if True to_write ...
java
public ServerList filterOutObservers() { Iterable<ServerSpec> filtered = Iterables.filter ( specs, new Predicate<ServerSpec>() { @Override public boolean apply(ServerSpec spec) { return spec.getSe...
python
def stddev_samples(data, xcol, ycollist, delta=1.0): """Create a sample list that contains the mean and standard deviation of the original list. Each element in the returned list contains following values: [MEAN, STDDEV, MEAN - STDDEV*delta, MEAN + STDDEV*delta]. >>> chart_data.stddev_samples([ [1, 10, 15, 12, 15]...
java
@Override public JspConfigDescriptor getJspConfigDescriptor() { if (withinContextInitOfProgAddListener) { throw new UnsupportedOperationException(MessageFormat.format( nls.getString("Unsupported.op.from.servlet.context.listener"), new Object[] {"getJspConf...
java
public ProcessDefinitionCacheEntry resolveProcessDefinition(ProcessDefinition processDefinition) { String processDefinitionId = processDefinition.getId(); String deploymentId = processDefinition.getDeploymentId(); ProcessDefinitionCacheEntry cachedProcessDefinition = processDefinitionCache.get(processDefin...
python
def organization(self): """ | Comment: The ID of the organization associated with this user, in this membership """ if self.api and self.organization_id: return self.api._get_organization(self.organization_id)
java
@Deprecated public static SSRC createSsrc(String url, KeyManager[] kms, TrustManager[] tms) throws InitializationException { return new SsrcImpl(url, kms, tms, 120 * 1000); }
java
public static void removeSharedFlow( String sharedFlowClassName, HttpServletRequest request, ServletContext servletContext ) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = unwrapMultipart( reque...
java
public synchronized PacketBuilder withShort(final short s) { checkBuilt(); try { dataOutputStream.writeShort(s); } catch (final IOException e) { logger.error("Unable to add short: {} : {}", e.getClass(), e.getMessage()); } retur...
java
protected URLConnection openConnection(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setDoOutput(true); if (_basicAuth != null) conn.setRequestProperty("Authorization", _basicAuth); else if (_user != null && _password != null) { ...
python
def dump(self, path): """Saves the pushdb as a properties file to the given path.""" with open(path, 'w') as props: Properties.dump(self._props, props)
java
public static String escapeJavaScript(final String text, final JavaScriptEscapeType type, final JavaScriptEscapeLevel level) { if (type == null) { throw new IllegalArgumentException("The 'type' argument cannot be null"); } if (level == null...
python
def gen_typedefs(self) -> str: """ Generate python type declarations for all defined types """ rval = [] for typ in self.schema.types.values(): typname = self.python_name_for(typ.name) parent = self.python_name_for(typ.typeof) rval.append(f'class {typname}({pa...
java
public List<ActivitySpreadType.Period> getPeriod() { if (period == null) { period = new ArrayList<ActivitySpreadType.Period>(); } return this.period; }
python
def get_files_to_check(self): """Generate files and error codes to check on each one. Walk dir trees under `self._arguments` and yield file names that `match` under each directory that `match_dir`. The method locates the configuration for each file name and yields a tuple of (fi...
java
@Override public DeleteResourcePolicyResult deleteResourcePolicy(DeleteResourcePolicyRequest request) { request = beforeClientExecution(request); return executeDeleteResourcePolicy(request); }
python
def exception(self, timeout=None): """Return the exception raised by the call, if any. This blocks until the message has successfully been published, and returns the exception. If the call succeeded, return None. Args: timeout (Union[int, float]): The number of seconds befo...
python
def _recv_timeout_loop(self): """ A loop to check timeout of receiving remote BFD packet. """ while self._detect_time: last_wait = time.time() self._lock = hub.Event() self._lock.wait(timeout=self._detect_time) if self._lock.is_set(): ...
java
public boolean isTextPresentInDropDown(final By by, final String text) { WebElement element = driver.findElement(by); List<WebElement> options = element.findElements(By .xpath(".//option[normalize-space(.) = " + escapeQuotes(text) + "]")); return options != null && !options.isEmpty(); }
java
private void waitForCompletion() { for (ListenableFuture<?> future : pendingTasks.values()) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOG.error("[" + this + "] Error waiting for writes to complete: " + e.getMessage()); ...
java
@Override public boolean isTabu(Move<? super SolutionType> move, SolutionType currentSolution) { // apply move move.apply(currentSolution); // check: contained in tabu memory? boolean tabu = memory.contains(currentSolution); // undo move move.undo(currentSolution); ...
java
@Nullable public static String extractFullServiceName(String fullMethodName) { int index = checkNotNull(fullMethodName, "fullMethodName").lastIndexOf('/'); if (index == -1) { return null; } return fullMethodName.substring(0, index); }
java
private void start(boolean isResume) { long startTime = 0; long lastPauseTime = 0; if (taskInfo != null && taskInfo.getStatus() == HttpDownStatus.WAIT) { startTime = taskInfo.getStartTime(); lastPauseTime = System.currentTimeMillis(); } taskInfo = new TaskInfo(); taskInfo.setStartTim...
python
def rand(self, count=1): """ Gets @count random members from the set @count: #int number of members to return -> @count set members """ result = self._client.srandmember(self.key_prefix, count) return set(map(self._loads, result))
java
public static Object[] copyArray(Object[] array, int from, int to) { Object[] result = new Object[to - from]; System.arraycopy(array, from, result, 0, to - from); return result; }
python
def vhost_exists(name, runas=None): ''' Return whether the vhost exists based on rabbitmqctl list_vhosts. CLI Example: .. code-block:: bash salt '*' rabbitmq.vhost_exists rabbit_host ''' if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_use...
java
public CertificateInner createOrUpdate(String resourceGroupName, String name, CertificateInner certificateEnvelope) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, name, certificateEnvelope).toBlocking().single().body(); }
java
static Finding createFinding(SourceName sourceName, String findingId) { try (SecurityCenterClient client = SecurityCenterClient.create()) { // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ // "423432321"); // String findingId = "samplefindingid"; // Use the ...
python
def later(timeout, f, *args, **kwargs): ''' Sets a timer that will call the *f* function past *timeout* seconds. See example in :ref:`sample_inter` :return: :class:`Timer` ''' t = Timer(timeout, f, args, kwargs) t.start() return t
java
public void widthTable(XWPFTable table, float widthCM, int rows, int cols) { TableTools.widthTable(table, widthCM, cols); TableTools.borderTable(table, 4); }
python
def date_convert(string, match, ymd=None, mdy=None, dmy=None, d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None): '''Convert the incoming string containing some date / time info into a datetime instance. ''' groups = match.groups() time_only = False if mm and dd: y=datetim...
java
public static DynamicMessage getDefaultInstance(final Descriptor type) { return wrap(com.google.protobuf.DynamicMessage.getDefaultInstance(type)); }
python
def get_acgt_geno_marker(self, marker): """Gets the genotypes for a given marker (ACGT format). Args: marker (str): The name of the marker. Returns: numpy.ndarray: The genotypes of the marker (ACGT format). """ # Getting the marker's genotypes g...
java
@Override public CommerceCountry findByPrimaryKey(Serializable primaryKey) throws NoSuchCountryException { CommerceCountry commerceCountry = fetchByPrimaryKey(primaryKey); if (commerceCountry == null) { if (_log.isDebugEnabled()) { _log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); } throw...
python
def as_iso8601(self): """ example: 2016-08-13T00:38:05.210+00:00 """ if self.__date is None or self.__time is None: return None return "20%s-%s-%sT%s:%s:%s0Z" % \ (self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], s...
java
public double sum() { double sum = 0; for (WeightedDirectedTypedEdge<T> e : inEdges.values()) sum += e.weight(); for (WeightedDirectedTypedEdge<T> e : outEdges.values()) sum += e.weight(); return sum; }
python
def get_project(self, owner, id, **kwargs): """ Retrieve a project Return details on a project. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. ...
java
protected List<AcademicTermDetail> getAcademicTermsAfter(DateTime start) { final List<AcademicTermDetail> terms = this.eventAggregationManagementDao.getAcademicTermDetails(); final int index = Collections.binarySearch( terms, ...
python
def find_import_star(node): """Finds import stars""" return ( isinstance(node, ast.ImportFrom) and '*' in h.importfrom_names(node.names) )
java
@Deprecated @Override public SQLTransaction beginTransaction(IsolationLevel isolationLevel, boolean forUpdateOnly) { return super.beginTransaction(isolationLevel, forUpdateOnly); }
python
def _compute_fluxes(self): ''' All fluxes are band by band''' self.emission = self._compute_emission() self.emission_sfc = self._compute_emission_sfc() fromspace = self._from_space() self.flux_down = self.trans.flux_down(fromspace, self.emission) self.flux_reflected_up = ...
java
public StructuredQueryDefinition valueConstraint(String constraintName, double weight, String... values) { return new ValueConstraintQuery(constraintName, weight, values); }
python
def column_to_bq_schema(self): """Convert a column to a bigquery schema object. """ kwargs = {} if len(self.fields) > 0: fields = [field.column_to_bq_schema() for field in self.fields] kwargs = {"fields": fields} return google.cloud.bigquery.SchemaField(s...
java
@Override public Request<DescribeSpotPriceHistoryRequest> getDryRunRequest() { Request<DescribeSpotPriceHistoryRequest> request = new DescribeSpotPriceHistoryRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public ArrayList<String> getDataRows() { ArrayList<String> rows = new ArrayList<String>(); for (String row : rowLookup.keySet()) { if (this.isMetaDataRow(row)) { continue; } HeaderInfo hi = rowLookup.get(row); if (!hi.isHide()) { rows.add(row); } } return rows; }
python
def _parse_api_options(self, options, query_string=False): """Select API options out of the provided options object. Selects API string options out of the provided options object and formats for either request body (default) or query string. """ api_options = self._select_optio...
java
public final void mT__144() throws RecognitionException { try { int _type = T__144; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalSARL.g:130:8: ( 'true' ) // InternalSARL.g:130:10: 'true' { match("true"); } st...
python
def _parse_record(self, record_type): """Parse a record.""" if self._next_token() in ['{', '(']: key = self._next_token() self.records[key] = { u'id': key, u'type': record_type.lower() } if self._next_token() == ',': ...
python
def append(self, offset, timestamp, key, value, headers=None): """ Append message to batch. """ assert not headers, "Headers not supported in v0/v1" # Check types if type(offset) != int: raise TypeError(offset) if self._magic == 0: timestamp = self...
python
def set_state(self, state, speed=None): """ :param state: bool :param speed: a string one of ["lowest", "low", "medium", "high", "auto"] defaults to last speed :return: nothing """ desired_state = {"powered": state} if state: brightness = s...
python
def shutdown_abort(): ''' Abort a shutdown. Only available while the dialog box is being displayed to the user. Once the shutdown has initiated, it cannot be aborted. Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion...
python
def aggr(self, group, **named_attributes): """ Aggregation of the type U('attr1','attr2').aggr(group, computation="QueryExpression") has the primary key ('attr1','attr2') and performs aggregation computations for all matching elements of `group`. :param group: The query expression to be...
java
public static DMatrixSparseCSC diag(double... values ) { int N = values.length; return diag(new DMatrixSparseCSC(N,N,N),values,0,N); }
python
def set_coordinates(self, x, y, z=None): """Set all coordinate dimensions at once.""" self.x = x self.y = y self.z = z
python
def visibleColumns(self): """ Returns a list of the visible column names for this widget. :return [<str>, ..] """ return [self.columnOf(c) for c in range(self.columnCount()) \ if not self.isColumnHidden(c)]
java
public void rotation(TextureRotationMode mode){ float[][] tmp = corner.clone(); switch (mode) { case HALF: corner[0] = tmp[2]; corner[1] = tmp[3]; corner[2] = tmp[0]; corner[3] = tmp[1]; break; case CLOCKWIZE: corner[0] = tmp[3]; corner[1] = tmp[0]; corner[2] = tmp[1]; corner[3] = tmp...
python
def rel_paths(self, *args, **kwargs): """ Fix the paths in the given dictionary to get relative paths Parameters ---------- %(ExperimentsConfig.rel_paths.parameters)s Returns ------- %(ExperimentsConfig.rel_paths.returns)s Notes ----- ...
python
def accuracy(current, predicted): """ Computes the accuracy of the TM at time-step t based on the prediction at time-step t-1 and the current active columns at time-step t. @param current (array) binary vector containing current active columns @param predicted (array) binary vector containing predicted act...
python
def alarm( cls, template, default_params={}, stack_depth=0, log_context=None, **more_params ): """ :param template: *string* human readable string with placeholders for parameters :param default_params: *dict* parameters to fill in template ...
python
def dependentItems(store, tableClass, comparisonFactory): """ Collect all the items that should be deleted when an item or items of a particular item type are deleted. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and returning an L{iaxi...
python
def static_partial_tile_sizes(width, height, tilesize, scale_factors): """Generator for partial tile sizes for zoomed in views. Positional arguments: width -- width of full size image height -- height of full size image tilesize -- width and height of tiles scale_factors -- iterable of scale fa...
python
def set_dict_none_default(dict_item, default_value): """ 对字典中为None的值,重新设置默认值 :param dict_item: :param default_value: :return: """ for (k, v) in iteritems(dict_item): if v is None: dict_item[k] = default_value
java
public synchronized int chooseGetCursorIndex(int previous) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "chooseGetCursorIndex", new Object[] {Integer.valueOf(previous)}); // The zeroth index represents the default cursor for non-classified messages. int cla...
python
def filterAcceptsRow(self, source_row, source_parent): """The filter method .. note:: This filter hides top-level items of unsupported branches and also leaf items containing xml files. Enabled root items: QgsDirectoryItem, QgsFavouritesItem, QgsPGRootItem. ...
python
def deprecated_conditional(predicate, removal_version, entity_description, hint_message=None, stacklevel=4): """Marks a certain configuration as deprecated. The predicate is used to determine if that configu...
python
def _parse_heading(self): """Parse a section heading at the head of the wikicode string.""" self._global |= contexts.GL_HEADING reset = self._head self._head += 1 best = 1 while self._read() == "=": best += 1 self._head += 1 context = conte...
python
def send_at_point(self, what, row, col): """Ask the server to perform an operation at a given point.""" pos = self.get_position(row, col) self.send_request( {"typehint": what + "AtPointReq", "file": self._file_info(), "point": pos})
python
def empty_mets(): """ Create an empty METS file from bundled template. """ tpl = METS_XML_EMPTY.decode('utf-8') tpl = tpl.replace('{{ VERSION }}', VERSION) tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now()) return OcrdMets(content=tpl.encode('utf-8'))
python
def surface2image(surface): """ Convert a cairo surface into a PIL image """ # TODO(Jflesch): Python 3 problem # cairo.ImageSurface.get_data() raises NotImplementedYet ... # import PIL.ImageDraw # # if surface is None: # return None # dimension = (surface.get_width(), surfac...
java
private void mainLoop() { for (@AutoreleasePool int i = 0;;) { try { TimerTask task; boolean taskFired; synchronized(queue) { // Wait for queue to become non-empty while (queue.isEmpty() && newTasksMayBeScheduled...
python
def faces_unique_edges(self): """ For each face return which indexes in mesh.unique_edges constructs that face. Returns --------- faces_unique_edges : (len(self.faces), 3) int Indexes of self.edges_unique that construct self.faces Examples ...
python
def update_generic_password(client, path): """Will update a single key in a generic secret backend as thought it were a password""" vault_path, key = path_pieces(path) mount = mount_for_path(vault_path, client) if not mount: client.revoke_self_token() raise aomi.exceptions.VaultConst...
python
def get_R_mod(options, rho0): """Compute synthetic measurements over a homogeneous half-space """ tomodir = tdManager.tdMan( elem_file=options.elem_file, elec_file=options.elec_file, config_file=options.config_file, ) # set model tomodir.add_homogeneous_model(magnitude=r...
java
public CompletableFuture<T> except(Consumer<Throwable> consumer) { return whenComplete((result, error) -> { if (error != null) { consumer.accept(error); } }); }
java
public static FieldMapping parseFieldMapping(String source, JsonNode mappingNode) { ValidationException.check(mappingNode.isObject(), "A column mapping must be a JSON record"); ValidationException.check(mappingNode.has(TYPE), "Column mappings must have a %s.", TYPE); String type = mappingNo...
java
@FFDCIgnore(ArithmeticException.class) public static long asClampedNanos(Duration duration) { try { return duration.toNanos(); } catch (ArithmeticException e) { // Treat long overflow as an exceptional case if (duration.isNegative()) { return Long....
java
public alluxio.proto.dataserver.Protocol.OpenUfsBlockOptions getOpenUfsBlockOptions() { return openUfsBlockOptions_ == null ? alluxio.proto.dataserver.Protocol.OpenUfsBlockOptions.getDefaultInstance() : openUfsBlockOptions_; }
python
def GetMostRecentClient(client_list, token=None): """Return most recent client from list of clients.""" last = rdfvalue.RDFDatetime(0) client_urn = None for client in aff4.FACTORY.MultiOpen(client_list, token=token): client_last = client.Get(client.Schema.LAST) if client_last > last: last = client...
java
public void loadTileSets (InputStream source, Map<String, TileSet> tilesets) throws IOException { // stick an array list on the top of the stack for collecting // parsed tilesets List<TileSet> setlist = Lists.newArrayList(); _digester.push(setlist); // now fire up th...