language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def resolve_dependencies(nodes): """ Figure out which order the nodes in the graph can be executed in to satisfy all requirements. """ done = set() while True: if len(done) == len(nodes): break for node in nodes: if node.name not in done: match = d...
java
public void refresh() { QueryCache.instance().purgeTableCache(metaModelLocal); Model fresh = ModelDelegate.findById(this.getClass(), getId()); if (fresh == null) { throw new StaleModelException("Failed to refresh self because probably record with " + "this ID does...
java
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromTaskHeaders>> listFromTaskNextSinglePageAsync(final String nextPageLink, final FileListFromTaskNextOptions fileListFromTaskNextOptions) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is...
java
protected ChildData getData(String path) { try { return new ChildData(path, EMPTY_STAT, client.getData().forPath(path)); } catch (Exception e) { throw new NiubiException(e); } }
java
public void typeInvalid(final String type) { this.addStatusMessage( ProtocolConstants.StatusCodes.Create.TYPE_INVALID, "\"" + type + "\" is not a valid create request type. Use \"" + CreateRequestType.USER.getIdentifier() + "\" to create a user, \"" + CreateRequestType.FOLLOW.getIdentifier()...
java
public void setDeviceManufacturerTargeting(com.google.api.ads.admanager.axis.v201811.DeviceManufacturerTargeting deviceManufacturerTargeting) { this.deviceManufacturerTargeting = deviceManufacturerTargeting; }
java
public static void free(TempCharBuffer buf) { buf._next = null; if (buf._buf.length == SIZE) _freeList.free(buf); }
java
public static int getEditDistance(String source, String target, boolean caseSensitive) { // Levenshtein distance algorithm int sourceLength = isEmptyOrWhitespace(source) ? 0 : source.length(); int targetLength = isEmptyOrWhitespace(target) ? 0 : target.length(); if (sourceLength == 0) { return ...
java
public static SecretKey createSecretKey(String algorithm) { // 声明KeyGenerator对象 KeyGenerator keygen; // 声明 密钥对象 SecretKey deskey = null; try { // 返回生成指定算法的秘密密钥的 KeyGenerator 对象 keygen = KeyGenerator.getInstance(algorithm); // 生成一个密钥 deskey = keygen.generateKey(); } catch (NoSuchAlgorithmExceptio...
java
synchronized TransactionQueueEvent nextTransactionEvent() throws InterruptedException { if (mQueue.isEmpty()) { if (mIdleTimeout != 0) { if (mIdleTimeout < 0) { wait(); } else { wait(mIdleTimeout); ...
java
public byte[] read(final String _resourceName) { byte[] ret = null; EFapsClassLoader.LOG.debug("read ''", _resourceName); try { final QueryBuilder queryBuilder = new QueryBuilder(this.classType); queryBuilder.addWhereAttrEqValue("Name", _resourceName); fin...
python
def dirsplit(path): r""" Args: path (str): Returns: list: components of the path CommandLine: python -m utool.util_path --exec-dirsplit Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> paths = [] >>> paths.append(...
python
def __get_is_revertible(self): """Return a boolean representing whether this Action is revertible or not""" # If it was already reverted if self.reverted: return False errors = [] inst = self.timemachine if inst.fields != inst.presently.fiel...
python
def negate(self, topv=None): """ Given a CNF formula :math:`\mathcal{F}`, this method creates a CNF formula :math:`\\neg{\mathcal{F}}`. The negation of the formula is encoded to CNF with the use of *auxiliary* Tseitin variables [1]_. A new CNF formula is returned ...
python
def gotResolverError(self, failure, protocol, message, address): ''' Copied from twisted.names. Removes logging the whole failure traceback. ''' if failure.check(dns.DomainError, dns.AuthoritativeDomainError): message.rCode = dns.ENAME else: messag...
java
private synchronized TableBucket getNextBucketFromExistingBatch() { if (this.currentBatch != null) { TableBucket next = this.currentBatch.next(); if (!this.currentBatch.hasNext()) { this.currentBatch = null; } return next; } retur...
python
def CheckSchema(self, database): """Checks the schema of a database with that defined in the plugin. Args: database (SQLiteDatabase): database. Returns: bool: True if the schema of the database matches that defined by the plugin, or False if the schemas do not match or no schema ...
java
public boolean setIfSignificantToUser(final int newValue) { while (true) { final int currentValue = _value.get(); if (newValue > currentValue) { final long currentTimestamp; if (_significantUpdateIntervalMillis > 0) { currentTimestamp ...
python
def _pad(expr, width, side='left', fillchar=' '): """ Pad strings in the sequence or scalar with an additional character to specified side. :param expr: :param width: Minimum width of resulting string; additional characters will be filled with spaces :param side: {‘left’, ‘right’, ‘both’}, default ...
python
def same(*values): """ Check if all values in a sequence are equal. Returns True on empty sequences. Examples -------- >>> same(1, 1, 1, 1) True >>> same(1, 2, 1) False >>> same() True """ if not values: return True first, rest = values[0], values[1:] ...
java
public void setResultValue(String actionId, Object resultValue) { if (actionId == null || !actionId.contains(ActivityContext.ID_SEPARATOR)) { this.actionId = actionId; this.resultValue = resultValue; } else { String[] ids = StringUtils.tokenize(actionId, ActivityConte...
java
private List<FilterChangeListener> getAllListeners() { @SuppressWarnings("deprecation") final List<FilterChangeListener> globalChangeListeners = getAnalysisJobBuilder().getFilterChangeListeners(); final List<FilterChangeListener> list = new ArrayList<>(globalChangeListene...
python
def schunk(string, size): """Splits string into n sized chunks.""" return [string[i:i+size] for i in range(0, len(string), size)]
java
@Override public void init(RestoreManagerConfig config, SnapshotJobManager jobManager) { this.config = config; this.jobManager = jobManager; }
java
private static MimeType getParentMimeType(Resource resource) { MimeType result = null; if (resource != null && (resource = resource.getParent()) != null) { ResourceHandle handle = ResourceHandle.use(resource); result = getMimeType(handle.getProperty(ResourceUtil.PROP_MIME_TYPE, "...
python
def get_collections(self, unit, names=None, merge=False, sampling_rate=None, **entities): ''' Retrieve variable data for a specified level in the Dataset. Args: unit (str): The unit of analysis to return variables for. Must be one of 'run', 'session',...
java
protected void beforeInsertDummies(int index, int length) { if (index > size || index < 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); if (length > 0) { ensureCapacity(size + length); System.arraycopy(elements, index, elements, index + length, size-index); size += length; ...
python
def _replace_fields(self, json_dict): """ Delete this object's attributes, and replace with those in json_dict. """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = json_dict self._set_...
python
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isi...
java
public void delete() { URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE); request.send(); }
java
public @Nonnull Optional<URL> getResource(@Nonnull String path) { ArgumentUtils.requireNonNull("path", path); Optional<ResourceLoader> resourceLoader = getSupportingLoader(path); if (resourceLoader.isPresent()) { return resourceLoader.get().getResource(path); } return...
java
@Override public Structure getDomain(String pdpDomainName, AtomCache cache) throws IOException, StructureException { return cache.getStructure(getPDPDomain(pdpDomainName)); }
python
def gumbel_softmax(x, z_size, mode, softmax_k=0, temperature_warmup_steps=150000, summary=True, name=None): """Gumbel softmax discretization bottleneck. Args: x: Input to the discretization bottlen...
python
def parse(self): """Parse our .PLT file and return :class:`Plot` object or raise :exc:`ParseException`.""" plt = Plot(name_from_filename(self.pltfilename)) with open(self.pltfilename, 'rb') as pltfile: segment = None for line in pltfile: if not line: ...
java
private BitMatrix extractDataRegion(BitMatrix bitMatrix) { int symbolSizeRows = version.getSymbolSizeRows(); int symbolSizeColumns = version.getSymbolSizeColumns(); if (bitMatrix.getHeight() != symbolSizeRows) { throw new IllegalArgumentException("Dimension of bitMatrix must match the version size");...
java
public Tag create(String name) { String url = WxEndpoint.get("url.tag.create"); TagWrapper tag = new TagWrapper(name); String json = JsonMapper.nonEmptyMapper().toJson(tag); logger.debug("create tag: {}", json); String response = wxClient.post(url, json); TagWrapper...
python
def findFirstHref(link_attrs_list, target_rel): """Return the value of the href attribute for the first link tag in the list that has target_rel as a relationship.""" # XXX: TESTME matches = findLinksRel(link_attrs_list, target_rel) if not matches: return None first = matches[0] retu...
java
static ObjectGraph createWith(Loader loader, Object... modules) { return DaggerObjectGraph.makeGraph(null, loader, modules); }
python
def validate_min_items(value, minimum, **kwargs): """ Validator for ARRAY types to enforce a minimum number of items allowed for the ARRAY to be valid. """ if len(value) < minimum: raise ValidationError( MESSAGES['min_items']['invalid'].format( minimum, len(value)...
python
def get_instance(self, payload): """ Build an instance of IpAccessControlListInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListInstance :rtype: twilio.rest.api.v2010.account.sip.ip_a...
java
public static boolean isValid( String variant, int yearOfEra, int month, int dayOfMonth ) { EraYearMonthDaySystem<HijriCalendar> calsys = CALSYS.get(variant); return ((calsys != null) && calsys.isValid(HijriEra.ANNO_HEGIRAE, yearOfEra, month, dayOfMonth)); }
python
def load(self, env=None): """ Load a section values of given environment. If nothing to specified, use environmental variable. If unknown environment was specified, warn it on logger. :param env: environment key to load in a coercive manner :type env: string :rtype: dict...
java
public StartApplicationRequest withInputConfigurations(InputConfiguration... inputConfigurations) { if (this.inputConfigurations == null) { setInputConfigurations(new java.util.ArrayList<InputConfiguration>(inputConfigurations.length)); } for (InputConfiguration ele : inputConfigurat...
java
public static PropertyMap getAnnotationMap(ControlBeanContext cbc, AnnotatedElement annotElem) { if ( cbc == null ) return new AnnotatedElementMap(annotElem); return cbc.getAnnotationMap(annotElem); }
java
public boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || ((o instanceof String) && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || ((o instanceof String) && ((String)o).equalsIgnore...
python
def sample_vMF(mu, kappa, num_samples): """Generate num_samples N-dimensional samples from von Mises Fisher distribution around center mu \in R^N with concentration kappa. """ dim = len(mu) result = np.zeros((num_samples, dim)) for nn in range(num_samples): # sample offset from center (o...
java
void removeFromIndexes(TransactionContext transactionContext, Object key) { Stream<IndexedTypeIdentifier> typeIdentifiers = getKnownClasses().stream() .filter(searchFactoryHandler::hasIndex) .map(PojoIndexedTypeIdentifier::new); Set<Work> deleteWorks = typeIdentifiers .ma...
java
protected void addDependenciesRecursively(Namespace namespace, List<Namespace> namespaceList, String dependencyId, List<String> extendedDependencies) throws XmlException { if(extendedDependencies.contains(dependencyId)) { return; } if(namespace.getId().equals(dependencyId)) { ...
python
def weekday(cls, year, month, day): """Returns the weekday of the date. 0 = aaitabar""" return NepDate.from_bs_date(year, month, day).weekday()
java
@NotNull public DoubleStream peek(@NotNull final DoubleConsumer action) { return new DoubleStream(params, new DoublePeek(iterator, action)); }
python
def get_longest_non_repeat_v2(string): """ Find the length of the longest substring without repeating characters. Uses alternative algorithm. Return max_len and the substring as a tuple """ if string is None: return 0, '' sub_string = '' start, max_len = 0, 0 used_char = ...
java
public boolean renew(String value, String state, long time) { Nonce nonce = _map.get(state + ':' + value); if (nonce != null && !nonce.hasExpired()) { nonce.renew(time > 0 ? time : TTL); return true; } else { return false; } }
python
def export(outfile): """Export image anchore data to a JSON file.""" if not nav: sys.exit(1) ecode = 0 savelist = list() for imageId in imagelist: try: record = {} record['image'] = {} record['image']['imageId'] = imageId record['ima...
java
@Pure @SuppressWarnings("checkstyle:magicnumber") public static String parseHTML(String html) { if (html == null) { return null; } final Map<String, Integer> transTbl = getHtmlToJavaTranslationTable(); assert transTbl != null; if (transTbl.isEmpty()) { return html; } final Pattern pattern = Patter...
java
protected synchronized Class loadClass(final String name, boolean resolve) throws ClassNotFoundException { Class c = this.findLoadedClass(name); if (c != null) return c; c = (Class) customClasses.get(name); if (c != null) return c; try { c = oldFindClass(name); ...
java
public ServiceFuture<OperationStatusResponseInner> restartAsync(String resourceGroupName, String vmName, final ServiceCallback<OperationStatusResponseInner> serviceCallback) { return ServiceFuture.fromResponse(restartWithServiceResponseAsync(resourceGroupName, vmName), serviceCallback); }
python
def _extract_country_code(number): """Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code. """ ...
java
public void setImageURI(@Nullable String uriString, @Nullable Object callerContext) { Uri uri = (uriString != null) ? Uri.parse(uriString) : null; setImageURI(uri, callerContext); }
python
def _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway): ''' Ensure that the configuration passed is formatted correctly and contains valid IP addresses, etc. ''' errors = [] # Validate DNS configuration if dns_proto == 'dhcp': if dns_servers is not None: error...
java
public static User getUserByBasicAuthentication(Request applicationRequest, HttpServletRequest request, HttpServletResponse response, String realmDescription) throws IOException, ServletRequestAlreadyRedirectedException { // Request applicationRequest = application.getCurrentRequest(); // String realmId = applica...
python
def translate(self): """Run CheckTranslator.""" visitor = CheckTranslator(self.document, contents=self.contents, filename=self.filename, ignore=self.ignore) self.document.walkabout(visitor) ...
python
def run(self, node, client): """ Upload the file, retaining permissions See also L{Deployment.run} """ perms = os.stat(self.source).st_mode client.put(path=self.target, chmod=perms, contents=open(self.source, 'rb').read()) return node
python
def has_coverage(self): """ Returns a boolean for is a parseable .coverage file can be found in the repository :return: bool """ if os.path.exists(self.git_dir + os.sep + '.coverage'): try: with open(self.git_dir + os.sep + '.coverage', 'r') as f: ...
java
public static String toAlpha(long i, boolean uppercase) { final int A = (uppercase ? 'A' : 'a') - 1; if (i < 0) throw new IllegalArgumentException( "Argument must be non-negative, was " + i); if (i == Long.MAX_VALUE) throw new IllegalArgumentException(...
java
public int divide(int x, int y) { assert(x >= 0 && x < getFieldSize() && y > 0 && y < getFieldSize()); return divTable[x][y]; }
python
def set_ttl(self, key, ttl): """ Sets time to live for @key to @ttl seconds -> #bool True if the timeout was set """ return self._client.expire(self.get_key(key), ttl)
python
def collectstatic(force=False): """ collect static files for production httpd If run with ``settings.DEBUG==True``, this is a no-op unless ``force`` is set to ``True`` """ # noise reduction: only collectstatic if not in debug mode from django.conf import settings if force or not setting...
python
async def disconnect(self, conn_id): """Asynchronously disconnect from a connected device Args: conn_id (int): A unique identifier that will refer to this connection callback (callback): A callback that will be called as callback(conn_id, adapter_id, success, fai...
java
public long nextLong() { Delta d = ranges.get(); if (d.start <= d.stop) { mutex.lock(); value = d.update(value); mutex.unlock(); } return d.start++; }
java
public String beginReplaceContent(String resourceGroupName, String automationAccountName, String runbookName, String runbookContent) { return beginReplaceContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, runbookContent).toBlocking().single().body(); }
python
def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600, used_flightmodes=[], mav_type=None): '''create path and mission as an image file''' mt = mp_tile.MPTile(service=options.service) map_img = mt.area_to_image(latlon[0], latlon[1], ...
python
def venn3_unweighted(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1, 1, 1, 1, 1), ax=None, subset_label_formatter=None): ''' The version of venn3 without area-weighting. It is implemented as a wrapper around venn3. Namely, venn3 is invoked...
java
@Override public CPDefinitionSpecificationOptionValue findByCPDefinitionId_First( long CPDefinitionId, OrderByComparator<CPDefinitionSpecificationOptionValue> orderByComparator) throws NoSuchCPDefinitionSpecificationOptionValueException { CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValu...
java
private String toPath(String name, IconSize size) { return CmsStringUtil.joinPaths(CmsWorkplace.getSkinUri(), ICON_FOLDER, "" + name.hashCode()) + size.getSuffix(); }
python
def getVATAmount(self): """ Compute AnalysisProfileVATAmount """ price, vat = self.getAnalysisProfilePrice(), self.getAnalysisProfileVAT() return float(price) * float(vat) / 100
python
def run_in_transaction(self, func, *args, **kw): """Perform a unit of work in a transaction, retrying on abort. :type func: callable :param func: takes a required positional argument, the transaction, and additional positional / keyword arguments as supplied ...
java
public static DataNode createFromEncoded(String encodedData, String baseUri) { String data = Entities.unescape(encodedData); return new DataNode(data); }
python
def location_path(self): """ Return the Location-Path of the response. :rtype : String :return: the Location-Path option """ value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_PATH.number: value....
python
def get_profile_names_and_default() -> ( typing.Tuple[typing.Sequence[str], typing.Optional[Profile]]): """Return the list of profile names and the default profile object. The list of names is sorted. """ with ProfileStore.open() as config: return sorted(config), config.default
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.GCPARC__XCENT: return getXCENT(); case AfplibPackage.GCPARC__YCENT: return getYCENT(); case AfplibPackage.GCPARC__MH: return getMH(); case AfplibPackage.GCPARC__MFR: re...
python
def single_device(cl_device_type='GPU', platform=None, fallback_to_any_device_type=False): """Get a list containing a single device environment, for a device of the given type on the given platform. This will only fetch devices that support double (possibly only double with a pragma defined, bu...
python
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str: """ Handles the requirements in the target repository, returns a path to a executable of the virtualenv. """ return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python")
python
def _parse_line_section(self, line): """ Parse a line containing a group definition. Returns a tuple: (group_type, group_name), where group_type is in the set ('hosts', 'children', 'vars'). For example: [prod] Returns: ('hosts', 'prod') F...
java
private boolean setDefine(CompilerOptions options, String key, Object value) { boolean success = false; if (value instanceof String) { final boolean isTrue = "true".equals(value); final boolean isFalse = "false".equals(value); if (isTrue || isFalse) { options.setDefineToBoolean...
java
public CreateTrustRequest withConditionalForwarderIpAddrs(String... conditionalForwarderIpAddrs) { if (this.conditionalForwarderIpAddrs == null) { setConditionalForwarderIpAddrs(new com.amazonaws.internal.SdkInternalList<String>(conditionalForwarderIpAddrs.length)); } for (String ele...
python
def get_link_name (self, tag, attrs, attr): """Parse attrs for link name. Return name of link.""" if tag == 'a' and attr == 'href': # Look for name only up to MAX_NAMELEN characters data = self.parser.peek(MAX_NAMELEN) data = data.decode(self.parser.encoding, "ignore"...
python
def get_containing(self, name, depth = 0): """Return the n-th (n = ``depth``) context containing attribute named ``name``.""" ctx_dict = object.__getattribute__(self, '__dict__') if name in ctx_dict: if depth <= 0: return self depth -= 1 parent = c...
python
def register (self, cmd): """Register a new command with the tool. 'cmd' is expected to be an instance of `Command`, although here only the `cmd.name` attribute is investigated. Multiple commands with the same name are not allowed to be registered. Returns 'self'. """ if...
java
@Override public List<CommerceVirtualOrderItem> findAll(int start, int end) { return findAll(start, end, null); }
python
def bunzip2(filename): """Uncompress `filename` in place""" log.debug("Uncompressing %s", filename) tmpfile = "%s.tmp" % filename os.rename(filename, tmpfile) b = bz2.BZ2File(tmpfile) f = open(filename, "wb") while True: block = b.read(512 * 1024) if not block: br...
java
private void configure(RaftMember.Type type, CompletableFuture<Void> future) { // Set a timer to retry the attempt to leave the cluster. configureTimeout = cluster.getContext().getThreadContext().schedule(cluster.getContext().getElectionTimeout(), () -> { configure(type, future); }); // Attempt t...
python
def from_arrow_schema(arrow_schema): """ Convert schema from Arrow to Spark. """ return StructType( [StructField(field.name, from_arrow_type(field.type), nullable=field.nullable) for field in arrow_schema])
python
def _filtered_list(self, selector): """Iterate over `self.obj` list, extracting `selector` from each element. The `selector` can be a simple integer index, or any valid key (hashable object). """ res = [] for elem in self.obj: self._append(elem, selector, res)...
java
protected Integer processInt(String name, String expression, int value, boolean immediateOnly) { Integer result = null; boolean immediate = false; /* * The expression language value takes precedence over the direct setting. */ if (expression.isEmpty()) { /*...
java
public void initializationPhase() { population = new ArrayList<>(populationSize) ; while (population.size() < populationSize) { S newSolution = diversificationGeneration() ; S improvedSolution = improvement(newSolution) ; population.add(improvedSolution) ; } }
python
def removeLogger(self, logger): """ Removes the inputed logger from the set for this widget. :param logger | <str> || <logging.Logger> """ if isinstance(logger, logging.Logger): logger = logger.name if logger in self._loggers: ...
python
def snapshot_peek_sigb64( fd, off, bytelen ): """ Read the last :bytelen bytes of fd and interpret it as a base64-encoded string """ fd.seek( off - bytelen, os.SEEK_SET ) sigb64 = fd.read(bytelen) if len(sigb64) != bytelen: return None try: base64.b64decode(sigb64) ...
java
protected ProcessOutput executeProcess(String command,FaxActionType faxActionType) { //execute process ProcessOutput processOutput=ProcessExecutorHelper.executeProcess(this,command); //validate process output this.processOutputValidator.validateProcessOutput(this,processOutput,faxAc...
python
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) result = client.get(key) return result.value
python
def clean(self): """Return a copy of this Text instance with invalid characters removed.""" return Text(self.__text_cleaner.clean(self[TEXT]), **self.__kwargs)