language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private ImmutableList<CharacterRegion> offsetsOfSubstringByContentCodepointOffsets( final OffsetRange<CharOffset> substringContentCodePointsRange) { checkArgument(substringContentCodePointsRange.startInclusive().asInt() >= 0); checkArgument( substringContentCodePointsRange.endInclusive().asInt() <...
java
@Override @Transactional public String getResource(String id) { final TemplateCall call = templater.template("resource_template"); final ResourceTemplateEntity entity = resourceProvisionService.getOrCreateTemplate(id); if (entity == null) throw new RestException(404, "No such resource with id: " + id); ...
java
@Column(header = "V1 (%(v1))", order = 40) public String getV1() { return CmsValueCompareBean.formatContentValueForDiffTable(m_cms, m_elemComp, m_elemComp.getVersion1()); }
python
def anneal(self, mode, matches, orig_matches): """ Perform post-processing. Return True when any changes were applied. """ changed = False def dupes_in_matches(): """Generator for index of matches that are dupes.""" items_by_path = config.engine.grou...
python
def get_jsonfacet_counts_as_dict(self, field, data=None): ''' EXPERIMENTAL Takes facets and returns then as a dictionary that is easier to work with, for example, if you are getting something this:: {'facets': {'count': 50, 'test': {'buckets': [{'count': 10, ...
java
public I_CmsTemplateContextProvider getTemplateContextProvider(String providerName) { providerName = providerName.trim(); providerName = removePropertyPrefix(providerName); String providerClassName = providerName; String providerConfig = ""; // get provider configuration...
java
public ParameterBinding getBindingFor(String name) { Assert.hasText(name, PARAMETER_NAME_MISSING); for (ParameterBinding binding : bindings) { if (binding.hasName(name)) { return binding; } } throw new IllegalArgumentException(String.f...
python
def format(self, fmt, locale=None): """ Formats the instance using the given format. :param fmt: The format to use :type fmt: str :param locale: The locale to use :type locale: str or None :rtype: str """ return self._formatter.format(self, fmt,...
java
@NotNull public static <T> Stream<T> iterate( @Nullable final T seed, @NotNull final Predicate<? super T> predicate, @NotNull final UnaryOperator<T> op) { Objects.requireNonNull(predicate); return iterate(seed, op).takeWhile(predicate); }
python
def get_generation_code(self): """Return python code that generates all drawn gates.""" if len(self.gates) < 1: code = '' else: import_list = set([gate._gencode_gate_class for gate in self.gates]) import_list = 'from FlowCytometryTools import ' + ', '.join(imp...
java
public static void loadOutputFormBean(ServletRequest request, Object bean) { if(bean != null) request.setAttribute(OUTPUT_FORM_BEAN_OBJECT_KEY, bean); }
python
def replicate_attributes(source, target, cache=None): '''Replicates common SQLAlchemy attributes from the `source` object to the `target` object.''' target_manager = manager_of_class(type(target)) column_attrs = set() relationship_attrs = set() relationship_columns = set() for attr in manage...
java
public static <T> Set<T> newUnmodifiableSet(T...contents) { Set<T> set; if(contents == null || contents.length==0) return Collections.emptySet(); if(contents.length == 1) return Collections.singleton(contents[0]); set = newSet(contents.length); Collections.addAll(set, contents); return Collections.u...
java
protected void registerAmfProxies(ConversionService conversionService, boolean useDirectFieldAccess) { Set<Class<?>> typesToRegister = findTypesToRegister(); if (log.isInfoEnabled()) { log.info("Types detected for AMF serialization support: "+typesToRegister.toString()); } fo...
python
def remove_duplicates(seq, idfun=None): """ removes duplicates from a list, order preserving, as found in http://www.peterbe.com/plog/uniqifiers-benchmark """ # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: ...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.MPG__RG: getRG().clear(); return; } super.eUnset(featureID); }
java
public Observable<Page<SpatialAnchorsAccountInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<SpatialAnchorsAccountInner>>, Page<SpatialAnchorsAccountInner>>() { @Override public Page<SpatialAnchorsAccountInner> call(Servi...
java
@Override public synchronized BeanContext stop() { if (terminating.compareAndSet(false, true)) { if (LOG.isDebugEnabled()) { LOG.debug("Stopping BeanContext"); } publishEvent(new ShutdownEvent(this)); // need to sort registered singletons so t...
python
def load_config(self, config_source, parameters_source): """For JSON, the source it the file path""" with open(config_source) as config_source: config_raw = config_source.read() """Replace the parameters""" pattern = "(%[a-zA-Z_0-9]*%)" self.parameters = ...
java
public static String encode(String unencoded) { byte[] bytes = null; try { bytes = unencoded.getBytes("UTF-8"); } catch (UnsupportedEncodingException ignored) {} if (null == bytes) { return null; } return encode(bytes); }
java
static LogoutUrlBuilder newInstance(HttpUrl baseUrl, String clientId, String returnToUrl, boolean setClientId) { return new LogoutUrlBuilder(baseUrl, setClientId ? clientId : null, returnToUrl); }
java
public JobDetail retrieveJob(JobKey jobKey, T jedis) throws JobPersistenceException, ClassNotFoundException{ final String jobHashKey = redisSchema.jobHashKey(jobKey); final String jobDataMapHashKey = redisSchema.jobDataMapHashKey(jobKey); final Map<String, String> jobDetailMap = jedis.hgetAll(j...
python
def write_networking_file(version, pairs): """ Write the VMware networking file. """ vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0])) try: with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f: f.write(version) for key, value in vmnets.items():...
python
def plot_ts(ax, agemin, agemax, timescale='gts12', ylabel="Age (Ma)"): """ Make a time scale plot between specified ages. Parameters: ------------ ax : figure object agemin : Minimum age for timescale agemax : Maximum age for timescale timescale : Time Scale [ default is Gradstein et al...
java
@Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { @Override public void onMiss...
java
public Record remove(String... columns) { if (columns != null) for (String c : columns) this.getColumns().remove(c); return this; }
python
def rationalize_until(until=None): """ Rationalizes the `until` argument used by other functions. This function accepts datetime and timedelta instances as well as integers representing epoch values. """ if until is None: until = "+inf" elif isinstance(until, datetime): until...
python
def _parse_args(func, variables, annotations=None): """Return a list of arguments with the variable it reads. NOTE: Multiple arguments may read the same variable. """ arg_read_var = [] for arg_name, anno in (annotations or func.__annotations__).items(): if arg_name == 'return': ...
python
def fieldvalue_pairs(self, exclude_cache=False): '''Generator of fields,values pairs. Fields correspond to the ones which have been loaded (usually all of them) or not loaded but modified. Check the :ref:`load_only <performance-loadonly>` query function for more details. If *exclude_cache* evaluates to ``True`...
java
public static <PS, SEG, S> UndoManager defaultUndoManager(GenericStyledArea<PS, SEG, S> area) { return area.isPreserveStyle() ? richTextUndoManager(area) : plainTextUndoManager(area); }
python
def rmultivariate_hypergeometric(n, m, size=None): """ Random multivariate hypergeometric variates. Parameters: - `n` : Number of draws. - `m` : Number of items in each categoy. """ N = len(m) urn = np.repeat(np.arange(N), m) if size: draw = np.array([[urn[i] for i in ...
python
def _add_freq_options(config, opts, var2vcf_opts): """ Setting -f option for vardict and var2vcf_valid Prioritizing settings in resources/vardict/options, then algorithm/min_allele_fraction: min_allele_fraction "-f" in opts var2vcfopts -> vardict -f var2vcf -f yes ...
java
@Override public NrqlAlertCondition deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = element.getAsJsonObject(); JsonElement condition = obj.get("nrql_condition"); if(condition != null && condition.isJsonO...
python
def clean_data(freqs, data, chunk, avg_bin): """ Extract time-varying (wandering) lines from strain data. Parameters ---------- freqs: list List containing the frequencies of the wandering lines. data: pycbc.types.TimeSeries Strain data to extract the wandering lines from. chunk...
python
def post_process(self, settings): """ Perform post processing methods on settings according to their definition in manifest. Post process methods are implemented in their own method that have the same signature: * Get arguments: Current settings, item name and item valu...
java
@Override @SuppressWarnings("unchecked") public void register(String extensionClassName, String blockName) throws MojoExecutionException { Class<? extends Processor> clazz; try { clazz = (Class<Processor>) Class.forName(extensionClassName); } catch (ClassCastException...
python
def addVote(self, commit: Commit, voter: str) -> None: """ Add the specified COMMIT to this replica's list of received COMMITs. :param commit: the COMMIT to add to the list :param voter: the name of the replica who sent the COMMIT """ super()._add_msg(commit, vot...
python
def nn_y(self, y, dims=None, k = 1, radius=np.inf, eps=0.0, p=2): """Find the k nearest neighbors of y in the observed output data @see Databag.nn() for argument description @return distance and indexes of found nearest neighbors. """ if dims is None: assert len(y) =...
java
public static void read(InputStream stream, byte[] buffer) throws IOException { int read = 0; while(read < buffer.length) { int newlyRead = stream.read(buffer, read, buffer.length - read); if(newlyRead == -1) throw new EOFException("Attempt to read " + buffer.leng...
java
void updateDeletedDocs(CommittableIndexReader reader) { int maxDoc = reader.maxDoc(); for (int i = 0; i < maxDoc; i++) { if (reader.isDeleted(i)) { deleted.set(i); } } deletedDocsVersion = reader.getModificationCount(); }
python
def asizeof(self, *objs, **opts): '''Return the combined size of the given objects (with modified options, see method **set**). ''' if opts: self.set(**opts) s, _ = self._sizes(objs, None) return s
java
public static SingleTaskDataPublisher getInstance(Class<? extends DataPublisher> dataPublisherClass, State state) throws ReflectiveOperationException { Preconditions.checkArgument(SingleTaskDataPublisher.class.isAssignableFrom(dataPublisherClass), String.format("Cannot instantiate %s since it does not...
java
@SuppressWarnings("unchecked") public final <T> GetsResponse<T> gets(final String key, final Transcoder transcoder) throws TimeoutException, InterruptedException, MemcachedException { return this.gets(key, this.opTimeout, transcoder); }
java
protected void broadcastServicesChanged(boolean local) { Tree message = new Tree(); message.put("localService", true); eventbus.broadcast("$services.changed", message, null, true); }
python
def config_get(config, *path, default=None): """Get a configuration option following a path through the config Example usage: >>> config_get(config, 'problem', 'problem_type_details', 'scorer', default='accuracy') Args: config (dict): config d...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case TypesPackage.JVM_COMPONENT_TYPE__ARRAY_TYPE: return arrayType != null; } return super.eIsSet(featureID); }
python
def shift_dateint(dateint, day_shift): """Shifts the given dateint by the given amount of days. Arguments --------- dateint : int An integer object decipting a specific calendaric day; e.g. 20161225. days : int The number of days to shift the given dateint by. A negative number ...
python
def records( self ): """ Returns the record list that ist linked with this combo box. :return [<orb.Table>, ..] """ records = [] for i in range(self.count()): record = self.recordAt(i) if record: records.appen...
python
def longest(args): """ %prog longest bedfile fastafile Select longest feature within overlapping piles. """ from jcvi.formats.sizes import Sizes p = OptionParser(longest.__doc__) p.add_option("--maxsize", default=20000, type="int", help="Limit max size") p.add_option("...
java
public Node appendNode(Object name, Map attributes, Object value) { return new Node(this, name, attributes, value); }
python
def users_update(self, user_id, **kwargs): """Update an existing user.""" return self.__call_api_post('users.update', userId=user_id, data=kwargs)
python
def get_element_by_id(self, ident): """Get a TocElement element identified by index number from the container.""" for group in list(self.toc.keys()): for name in list(self.toc[group].keys()): if self.toc[group][name].ident == ident: return self.toc...
python
async def get_data(self): """Get Tautulli data.""" try: await self.get_session_data() await self.get_home_data() await self.get_users() await self.get_user_data() except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): msg ...
python
def print_code_table(self, out=sys.stdout): """ Print code table overview """ out.write(u'bits code (value) symbol\n') for symbol, (bitsize, value) in sorted(self._table.items()): out.write(u'{b:4d} {c:10} ({v:5d}) {s!r}\n'.format( b=bitsize,...
python
def build(self, update=True): """ Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page number is part of the query string and not the URL path """ query_str = "?page={}".format(self.page) if s...
java
public static void main(String[] args) { int i = 0; int classifierToUse = WORDSHAPECHRIS1; if (args.length == 0) { System.out.println("edu.stanford.nlp.process.WordShapeClassifier [-wordShape name] string+"); } else if (args[0].charAt(0) == '-') { if (args[0].equals("-wordShape") && ar...
java
protected <T extends VelocityTemplate> T configTemplate(T template) { // FIXME: this would be cool if it worked, but it doesn't, because VelocityEngine // props are currently set during template instantiation... // See VelocityTemplate#initVelocity. template.setLoggingEnabled(true); ...
java
@Override public T merge(Archive<?> source, Filter<ArchivePath> filter) throws IllegalArgumentException { return merge(source, new BasicPath(), filter); }
java
public ParsedOptions parse(Options options, String[] args, Properties properties, boolean skipParsingAtNonOption) throws OptionParserException { this.options = options; this.skipParsingAtNonOption = skipParsingAtNonOption; this.currentOption = null; this.expectedOpts = new Ar...
java
@Override public List<WSJobExecution> getJobExecutionsFromInstance(long instanceId) throws NoSuchJobInstanceException, JobSecurityException { return new ArrayList<WSJobExecution>(persistenceManagerService.getJobExecutionsFromJobInstanceId(authorizedInstanceRead(instanceId))); }
java
@Override public void addMaxCardinalityRestriction(Class<? extends D> domain, int max) { if (multipleCardinality) { this.maxCardinalities.put(domain, max); } else { if (max == 1) { if (log.isInfoEnabled()) { log.info("unnecessary use of cardinality restriction. " + "Maybe yo...
python
def _make_postfixes_1( analysis ): ''' Provides some post-fixes. ''' assert FORM in analysis, '(!) The input analysis does not contain "'+FORM+'" key.' if 'neg' in analysis[FORM]: analysis[FORM] = re.sub( '^\s*neg ([^,]*)$', '\\1 Neg', analysis[FORM] ) analysis[FORM] = re.sub( ' Neg Neg$', ' ...
python
def truncateletters(value, arg): """ Truncates a string after a certain number of letters Argument: Number of letters to truncate after """ warnings.warn( "`django_extensions.templatetags.truncate_letters` is deprecated. " "You should use `django.template.defaultfilters.truncatechars...
python
def upload(self, cmd: str, meta: dict): """Push the current state of the registry to Git.""" index = os.path.join(self.cached_repo, self.INDEX_FILE) if os.path.exists(index): os.remove(index) self._log.info("Writing the new index.json ...") with open(index, "w") as _o...
java
public ServiceFuture<List<TypeFieldInner>> listFieldsByModuleAndTypeAsync(String resourceGroupName, String automationAccountName, String moduleName, String typeName, final ServiceCallback<List<TypeFieldInner>> serviceCallback) { return ServiceFuture.fromResponse(listFieldsByModuleAndTypeWithServiceResponseAsync...
python
def match(self, feature, gps_precision=None, profile='mapbox.driving'): """Match features to OpenStreetMap data.""" profile = self._validate_profile(profile) feature = self._validate_feature(feature) geojson_line_feature = json.dumps(feature) uri = URITemplate(self.baseuri + '/...
python
def update_kwargs(kwargs, *updates): """ Utility function for merging multiple keyword arguments, depending on their type: * Non-existent keys are added. * Existing lists or tuples are extended, but not duplicating entries. The keywords ``command`` and ``entrypoint`` are however simply overwritte...
python
def find_notes(freqTable, maxNote=100): """Convert the (frequencies, amplitude) list to a (Note, amplitude) list.""" res = [0] * 129 n = Note() for (freq, ampl) in freqTable: if freq > 0 and ampl > 0: f = _find_log_index(freq) if f < maxNote: res[f] += amp...
java
private void processSyncMessageChunk(CommsByteBuffer buffer, Conversation conversation, boolean connectionMessage) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processSyncMessageChunk", ...
python
def make_default(self, user, group_membership): """ Set the passed GroupMembership as default for the specified user. :param user: User object or id :param group_membership: GroupMembership object or id """ return self._put(self._build_url(self.endpoint.make_default(user...
python
def infer_list_subtype(items): """Infer a list subtype from a collection of items.""" subtype = End for item in items: item_type = type(item) if not issubclass(item_type, Base): continue if subtype is End: subtype = ...
python
def _chunks(l, n): """ Yield successive n-sized chunks from l. http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python """ for i in xrange(0, len(l), n): yield l[i:i+n]
python
def manager(self, obj): """Returns the :class:`AttachmentsManager` instance for this object.""" manager = getattr(obj, _MANAGER_ATTR, None) if manager is None: manager = AttachmentsManager() setattr(obj.__class__, _MANAGER_ATTR, manager) return manager
java
public static boolean containsIgnoreCase(String input, String substring) { return contains(input.toUpperCase(), substring.toUpperCase()); }
python
def allocate(self, handles, initial=False, params={}): """Call from main thread. Initiate a request for more environments""" assert all(re.search('^\d+$', h) for h in handles), "All handles must be numbers: {}".format(handles) self.requests.put(('allocate', (handles, initial, params)))
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "unfileObjects", scope = DeleteTree.class) public JAXBElement<EnumUnfileObject> createDeleteTreeUnfileObjects( EnumUnfileObject value) { return new JAXBElement<EnumUnfileObject>( _DeleteTreeUnfileObjects_QNAME, Enum...
python
def get_multiple(self, fields=list(), limit=None, order_by=list(), offset=None): """Wrapper method that takes whatever was returned by the _all_inner() generators and chains it in one result The response can be sorted by passing a list of fields to order_by. Example: get_multiple(order...
python
def filter_metadata(metadata, user_filter, default_filter): """Filter the cell or notebook metadata, according to the user preference""" actual_keys = set(metadata.keys()) keep_keys = apply_metadata_filters(user_filter, default_filter, actual_keys) for key in actual_keys: if key not in keep_key...
java
@SuppressWarnings({ "null", "unused" }) @NotNull Media processRequest(@NotNull final MediaRequest mediaRequest) { // detect media source MediaSource mediaSource = null; List<Class<? extends MediaSource>> mediaSources = mediaHandlerConfig.getSources(); if (mediaSources == null || mediaSources.isEmpt...
java
protected ClassMapping mapClass (short code, String cname) throws IOException, ClassNotFoundException { // create a class mapping record, and cache it ClassMapping cmap = createClassMapping(code, cname); _classmap.add(code, cmap); return cmap; }
java
@Override protected void _fit(Dataframe trainingData) { ModelParameters modelParameters = knowledgeBase.getModelParameters(); Map<Object, Object> referenceLevels = modelParameters.getReferenceLevels(); Set<TypeInference.DataType> supportedXDataTypes = getSupportedXDataTypes(); Map<O...
java
public void addPoint(final double x, final double y, final double z) { minX = Math.min(minX, x); minY = Math.min(minY, y); minZ = Math.min(minZ, z); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); maxZ = Math.max(maxZ, z); }
java
public JvmAnnotationReference annotationRef(/* @Nullable */ Class<?> annotationType, /* @Nullable */ String... values) { if(annotationType == null) return null; return annotationRef(annotationType.getCanonicalName(), values); }
java
public static InputStream createBundle( final InputStream jarInputStream, final Properties instructions, final String jarInfo, final OverwriteMode overwriteMode ) throws IOExceptio...
java
public Observable<String> vpnDeviceConfigurationScriptAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VpnDeviceScriptParameters parameters) { return vpnDeviceConfigurationScriptWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).map(new Func1<...
java
private String getIntegerString(Number value) { return (value == null ? null : Integer.toString(value.intValue())); }
python
def _Comparator(self, operator): """Generate lambdas for uid and gid comparison.""" if operator == "=": return lambda x, y: x == y elif operator == ">=": return lambda x, y: x >= y elif operator == ">": return lambda x, y: x > y elif operator == "<=": return lambda x, y: x <=...
java
public static synchronized void shutdown() { logger.info(Messages.get("info.service.shutdown")); if (container != null) try { container.shutdown(); } catch (Exception e) { logger.error(Messages.get("info.service.error.shutdown"), e); } ...
python
def register(linter): """Required method to auto register this checker.""" linter.register_checker(NewDbFieldWithDefaultChecker(linter)) if not compat.LOAD_CONFIGURATION_SUPPORTED: load_configuration(linter)
python
def _write_cron_lines(user, lines): ''' Takes a list of lines to be committed to a user's crontab and writes it ''' lines = [salt.utils.stringutils.to_str(_l) for _l in lines] path = salt.utils.files.mkstemp() if _check_instance_uid_match(user) or __grains__.get('os_family') in ('Solaris', 'AIX'...
java
public static Date parseDate(String strdate) { /* Return in case the string date is not set */ if (strdate == null || strdate.length() == 0) return null; Date result = null; strdate = strdate.trim(); if (strdate.length() > 10) { /* Open: deal with +4:00 (no zero be...
python
def post_message(self): """Send templated message to **#deployments-{env}**. Primarily for production deployments. """ message = get_template(template_file='slack/pipeline-prepare-ran.j2', info=self.info) channel = '#deployments-prod' post_slack_message(message=message, ...
java
public Set<SyntacticCategory> getSubcategories(Set<String> featureValues) { Set<Integer> featureVariables = Sets.newHashSet(); getAllFeatureVariables(featureVariables); Preconditions.checkState(featureVariables.size() <= 2); if (featureVariables.size() == 0) { return Sets.newHashSet(this); } ...
python
def statsumToken(self, *args, **kwargs): """ Get Token for Statsum Project Get temporary `token` and `baseUrl` for sending metrics to statsum. The token is valid for 24 hours, clients should refresh after expiration. This method gives output: ``v1/statsum-token-response.json#`...
java
public ServiceFuture<IPAddressAvailabilityResultInner> checkIPAddressAvailabilityAsync(String resourceGroupName, String virtualNetworkName, final ServiceCallback<IPAddressAvailabilityResultInner> serviceCallback) { return ServiceFuture.fromResponse(checkIPAddressAvailabilityWithServiceResponseAsync(resourceGrou...
java
public void invalidate(Envelope envelope) { List<String> keys = index.getOverlappingKeys(envelope); if (CacheIndexService.ALL_KEYS == keys) { log.debug("clear all keys from cache"); clear(); } else { log.debug("invalidate keys {}", keys); for (String key : keys) { remove(key); } } }
python
def build(pattern=None, path='.'): """Generates a static copy of the sources """ path = abspath(path) c = Clay(path) c.build(pattern)
java
@Nonnull public Imports copyAndAdd(final Imports imports) { Check.notNull(imports, "imports"); return copyAndAdd(imports.asList()); }
python
def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def invoke_(self, arg): # pylint: disable=unused-argument try: ...
python
async def set_upstream_dns( cls, addresses: typing.Optional[typing.Sequence[str]]): """See `get_upstream_dns`.""" await cls.set_config("upstream_dns", ( "" if addresses is None else",".join(addresses)))