language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static Diagram load(String ref) throws SlickException { return load(ResourceLoader.getResourceAsStream(ref), false); }
java
private void write(TargetType theTarget, ValueSetTm theValueSetTm, File theOutputDirectory, String thePackageBase) throws IOException { if (!theOutputDirectory.exists()) { theOutputDirectory.mkdirs(); } if (!theOutputDirectory.isDirectory()) { throw new IOException(theOutputDirectory + " is not a directory"...
java
public static String mangleClass(Class cl, boolean isFull) { String name = cl.getName(); if (name.equals("boolean") || name.equals("java.lang.Boolean")) return "boolean"; else if (name.equals("int") || name.equals("java.lang.Integer") || name.equals("short") || name....
python
def _normalize_interval(start, end, value): """Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date a...
java
public static ExpressionInfo expressionInfo(String code, JShell state) { if (code == null || code.isEmpty()) { return null; } try { OuterWrap codeWrap = state.outerMap.wrapInTrialClass(Wrap.methodReturnWrap(code)); AnalyzeTask at = state.taskFactory.new Analyz...
java
public final static boolean isEjbQlIdentifier(String s) { if (s == null || s.length() == 0) { return false; } for (int i = 0; i < ejbQlIdentifiers.length; i++) { if (ejbQlIdentifiers[i].equalsIgnoreCase(s)) { return true; } } ...
java
public T get(V value) { T found = find(value); if (found != null) { return found; } synchronized (runtimeDefined) { for (T obj : runtimeDefined) { if (matches(obj, value)) { return obj; } } T created = create(value); runtimeDefined.add(created); return created; } }
java
private static void fillInMissing(Data result) { // Initially we assume that previous divisor is 1 with no prefix or suffix. long lastDivisor = 1L; for (int i = 0; i < result.divisors.length; i++) { if (result.units.get(OTHER)[i] == null) { result.divisors[i] = lastDi...
python
def play_media(self, url, content_type, title=None, thumb=None, current_time=0, autoplay=True, stream_type=STREAM_TYPE_BUFFERED, metadata=None, subtitles=None, subtitles_lang='en-US', subtitles_mime='text/vtt', subtitle_id=1): """ ...
python
def poly2poly(line): """ Parse a string of text containing a DS9 description of a polygon. This function works but is not very robust due to the constraints of healpy. Parameters ---------- line : str A string containing a DS9 region command for a polygon. Returns ------- ...
python
def numRegisteredForRole(self, role, includeTemporaryRegs=False): ''' Accepts a DanceRole object and returns the number of registrations of that role. ''' count = self.eventregistration_set.filter(cancelled=False,dropIn=False,role=role).count() if includeTemporaryRegs: ...
java
void setLoadedAscanrules(List<AbstractPlugin> ascanrules) { if (ascanrules == null) { throw new IllegalArgumentException("Parameter ascanrules must not be null."); } if (ascanrules.isEmpty()) { loadedAscanrules = Collections.emptyList(); return; } for (AbstractPlugin ascanrule : ascanrule...
java
public com.google.api.ads.admanager.axis.v201811.UserConsentEligibility getUserConsentEligibility() { return userConsentEligibility; }
java
public static String getVMStatus(String hostIpPort, String id) throws TargetException { if(id.startsWith("urn:uuid:")) id = id.substring(9); String status = null; URL url = null; try { CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); url = new URL("http://" + hostIpPort + "/com...
python
def words(ctx, input, output): """Read input document, and output words.""" log.info('chemdataextractor.read.elements') log.info('Reading %s' % input.name) doc = Document.from_file(input) for element in doc.elements: if isinstance(element, Text): for sentence in element.sentences...
java
public Socket getSocket(String host, int port, boolean useSecureSocket, SecurityDomain securityDomain) throws Exception { return getSocket(host,port,useSecureSocket,securityDomain,null); }
java
public static long parseDuration(CharSequence duration) { // Match the duration against the regular expression. Matcher matcher = DURATION_PATTERN.matcher(duration); // Check that the argument is of the right format accepted by this method. if (!matcher.matches()) { ...
python
def IntGreaterThanZero(n): """If *n* is an integer > 0, returns it, otherwise an error.""" try: n = int(n) except: raise ValueError("%s is not an integer" % n) if n <= 0: raise ValueError("%d is not > 0" % n) else: return n
java
public static RunOptions parseRunCommand(String[] args) throws CliArgsException { try { DefaultParser parser = new DefaultParser(); CommandLine line = parser.parse(RUN_OPTIONS, args, true); return new RunOptions(line); } catch (ParseException e) { throw new CliArgsException(e.getMessage()); } }
python
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: potential...
python
def profile_create(self): """Create a profile.""" if self.args.profile_name in self.profiles: self.handle_error('Profile "{}" already exists.'.format(self.args.profile_name)) # load the install.json file defined as a arg (default: install.json) ij = self.load_install_json(se...
java
public static void checkJobProperties(final int projectId, final Props props, final Map<String, Props> jobPropsMap, final Set<String> errors) { // if project is in the memory check whitelist, then we don't need to check // its memory settings if (ProjectWhitelist.isProjectWhitelisted(projectId, ...
python
def make_registryitem_text(text, condition='contains', negate=False, preserve_case=False): """ Create a node for RegistryItem/Text :return: A IndicatorItem represented as an Element node """ document = 'RegistryItem' search = 'RegistryItem/Text' content_type = 'string' content = tex...
java
public static void extractFilesUsingFilter(File archive, File destination, FilenameFilter filter) throws ExtractionException { if (archive == null || destination == null) { return; } try (FileInputStream fis = new FileInputStream(archive)) { extractArchive(new ZipArchive...
java
@JsIgnore public static void onReady(Runnable callback) { if (isReady) { callback.run(); return; } onReadyCallbacks.push(callback); }
python
def is_inside_any(dir_list, fname): """True if fname is inside any of given dirs.""" for dirname in dir_list: if is_inside(dirname, fname): return True return False
java
private static long lcm(long x, long y) { // binary gcd algorithm from Knuth, "The Art of Computer Programming," // vol. 2, 1st ed., pp. 298-299 long x1 = x; long y1 = y; int p2 = 0; while ((x1 & 1) == 0 && (y1 & 1) == 0) { ++p2; x1 >>= 1; ...
python
def _create_action( self, icon_name: Optional[str], title: str, slot_function: Callable[[None], None], tool_tip: Optional[str]=None)-> QAction: """ QAction factory. All items created belong to the calling instance, i.e. created QAction parent i...
java
static String findNonProgressingOp(Resource resource, boolean forServer, long timeout) throws OperationFailedException { Resource.ResourceEntry nonProgressing = null; for (Resource.ResourceEntry child : resource.getChildren(ACTIVE_OPERATION)) { ModelNode model = child.getModel(); ...
python
def CopyFromDict(self, attributes): """Copies the attribute container from a dictionary. Args: attributes (dict[str, object]): attribute values per name. """ for attribute_name, attribute_value in attributes.items(): # Not using startswith to improve performance. if attribute_name[0] ...
python
def send_button_message(self, recipient_id, text, buttons, notification_type=NotificationType.regular): """Send text messages to the specified recipient. https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template Input: recipient_id: recipient id to se...
java
@Override public void onEvent(EventIterator events) { try { // this resolver should be the only one (for this handling thread) ResourceResolver resolver = getResolver(); if (resolver != null) { try { Session session = resolver.adaptTo(S...
java
public boolean nextKey() throws IOException,InterruptedException { while (hasMore && nextKeyIsSame) { nextKeyValue(); } if (hasMore) { if (inputKeyCounter != null) { inputKeyCounter.increment(1); } return nextKeyValue(); } else { return false; } }
java
public static long start(String key) { if (key.isEmpty()) { throw new InvalidKeyForTimeStampException(); } // current timestamp long timestamp = QuickUtils.date.getCurrentTimeInMiliseconds(); // save the timestamp QuickUtils.prefs.save(TIMER_PREFIX + key, t...
python
def cumcount(self, ascending=True): """ Number each item in each group from 0 to the length of that group - 1. Essentially this is equivalent to >>> self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- ascending : bool, default True...
python
def set_unit_spike_features(self, unit_id, feature_name, value): '''This function adds a unit features data set under the given features name to the given unit. Parameters ---------- unit_id: int The unit id for which the features will be set feature_name: st...
python
def _ohlc_dict(df_or_figure,open='',high='',low='',close='',volume='', validate='',**kwargs): """ Returns a dictionary with the actual column names that correspond to each of the OHLCV values. df_or_figure : DataFrame or Figure open : string Column name to be used for OPEN values high : string Column...
python
def commajoin_as_strings(iterable): """ Join the given iterable with ',' """ return _(u',').join((six.text_type(i) for i in iterable))
java
public void setListeners(StatsStorageRouter statsStorage, Collection<? extends TrainingListener> listeners) { //Check if we have any RoutingIterationListener instances that need a StatsStorage implementation... if (listeners != null) { for (TrainingListener l : listeners) { i...
java
public VariableRef[] getVariableRefs() { Collection<VariableRef> allRefs = new ArrayList<VariableRef>(); fillVariableRefs(allRefs, this); return allRefs.toArray(new VariableRef[allRefs.size()]); }
java
private URI _getSpecURI(String spec) { URI specURI = URI.create(spec); if (_scheme.indexOf(':') == -1) { return specURI; } String schemeSpecificPart = specURI.getSchemeSpecificPart(); return URI.create(schemeSpecificPart); }
java
public int getArgmaxConfigId() { int argmax = -1; double max = s.minValue(); for (int c = 0; c < this.size(); c++) { double val = getValue(c); if (s.gte(val, max)) { max = val; argmax = c; } } return argmax; ...
java
private void readZookeeperConfig() { try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) { curator.start(); accumuloInstance = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME), StandardCharsets.UTF_8); accumuloInstanceID = ...
java
public static void initializeInternalProject(CommandExecutor executor) { final long creationTimeMillis = System.currentTimeMillis(); try { executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ)) .get(); } catch (Throwable cause) { ...
python
def update(self, other=None, **kwargs): """D.update([other, ]**kwargs) -> None. Update D From dict/iterable ``other`` and ``kwargs``. If ``other`` present and has a .keys() method, does: for k in other: D[k] = other[k] If ``other`` present and lacks .keys() method, does: ...
python
def get_relationship_family_assignment_session(self, proxy=None): """Gets the ``OsidSession`` associated with assigning relationships to families. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipFamilyAssignmentSession) - a ``RelationshipFamilyAs...
python
def store(self, correlation_id, key, credential): """ Stores credential parameters into the store. :param correlation_id: (optional) transaction id to trace execution through call chain. :param key: a key to uniquely identify the credential parameters. :param credential: a cre...
java
public Observable<List<IntentsSuggestionExample>> getIntentSuggestionsAsync(UUID appId, String versionId, UUID intentId, GetIntentSuggestionsOptionalParameter getIntentSuggestionsOptionalParameter) { return getIntentSuggestionsWithServiceResponseAsync(appId, versionId, intentId, getIntentSuggestionsOptionalPara...
java
private static String convertToPropertiesKey(String environmentVariableKey, String environmentContext) { return environmentVariableKey.substring(environmentContext.length()).replace(ENV_DELIMITER, PROPERTIES_DELIMITER); }
python
def dbStore(self, typ, py_value): """ Prepares to store this column for the a particular backend database. :param backend: <orb.Database> :param py_value: <variant> :param context: <orb.Context> :return: <variant> """ # convert base types to work in the ...
python
def timeseries(self, data: ['SASdata', str] = None, by: str = None, corr: str = None, crosscorr: str = None, crossvar: str = None, decomp: str = None, id: str = None, out: [str, 'SASdata'...
java
@Override public java.util.Iterator findEntitiesForGroup(IEntityGroup group) throws GroupsException { if (log.isDebugEnabled()) log.debug( DEBUG_CLASS_NAME + ".findEntitiesForGroup(): retrieving entities for group " + gr...
python
def get_pkg_names(pkgs): """Get PyPI package names from a list of imports. Args: pkgs (List[str]): List of import names. Returns: List[str]: The corresponding PyPI package names. """ result = set() with open(join("mapping"), "r") as f: data = dict(x.strip().split(":") ...
java
public static Object newInstance(Class target, Class type, Object arg) throws InstantiationException, IllegalAccessException, IllegalArgumentException, ...
python
def _trim(self): """ Removes oldest backups that exceed the limit configured in backup_count option. Does not write back to file system, make sure to call self._write() afterwards. """ index = self._get_index() backup_limit = config().backup_count() - 1 ...
python
def _timestamp_to_json_row(value): """Coerce 'value' to an JSON-compatible representation. This version returns floating-point seconds value used in row data. """ if isinstance(value, datetime.datetime): value = _microseconds_from_datetime(value) * 1e-6 return value
java
public static String des(String code) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { return JavaEncrypt.decryptDES(code, "DES"); }
python
def getenvar(self, envar): from os import getenv """Retrieves the value of an environment variable if it exists.""" if getenv(envar) is not None: self._vardict[envar] = getenv(envar)
java
public static <T extends ImageGray<T>> TrackerObjectQuad<T> circulant( ConfigCirculantTracker config , Class<T> imageType ) { CirculantTracker<T> alg = FactoryTrackerObjectAlgs.circulant(config,imageType); return new Circulant_to_TrackerObjectQuad<>(alg, ImageType.single(imageType)); }
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case GUID: return isSetGuid(); case SECRET: return isSetSecret(); } throw new IllegalStateException(); }
java
@Override public String execute(Connection<?> connection) { String localUserId = UUID.randomUUID().toString(); logger.debug("Local User ID is: {}", localUserId); return localUserId; }
python
def execute(source, optimize=True, output=sys.stdout, input=sys.stdin, steps=-1): """Compiles and runs program, returning the machine used to execute the code. Args: optimize: Whether to optimize the code after parsing it. output: Stream which program can write output to. input: Str...
java
Index addExprIndex(int[] col, Expression[] indexExprs, HsqlName name, boolean unique, boolean migrating, Expression predicate) { Index newindex; if (table.isEmpty(session) || table.isIndexingMutable()) { newindex = table.createAndAddExprIndexStructure(name, col, indexExprs, unique, migrati...
python
def min_pos(self): '''Returns minimal positive value or None.''' if self.__len__() == 0: return ArgumentError('empty set has no minimum positive value.') if self.contains(0): return None positive = [interval for interval in self.intervals if in...
java
public static String base64String(INDArray arr) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); Nd4j.write(arr, dos); String base64 = Base64.encodeBase64String(bos.toByteArray()); return base64; }
python
def _escaped_token_to_subtoken_strings(self, escaped_token): """Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings. """ # NOTE: This algorithm is greedy; it won't nece...
python
def create_existing_folder(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None): # type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str """ Create a new folder parameter :param help_string: :param default: :param suffixes: :return: ""...
java
@Override public final void setItem(final ServiceToSale pItem) { this.item = pItem; if (getItsId() == null) { setItsId(new ServiceCatalogId()); } getItsId().setItem(this.item); }
java
public Material addVideo(InputStream inputStream, String fileName, String title, String description) { String url = WxEndpoint.get("url.material.binary.upload"); String desc = "{\"title\":\"%s\",\"introduction\":\"%s\"}"; Map<String, String> form = new HashMap<>(); form.put("descript...
java
public static RandomVariableInterface blackScholesOptionDelta( RandomVariableInterface initialStockValue, RandomVariableInterface riskFreeRate, RandomVariableInterface volatility, double optionMaturity, RandomVariableInterface optionStrike) { if(optionMaturity < 0) { return initialStockValue.mult(0...
python
def nl_complete_msg(sk, msg): """Finalize Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450 This function finalizes a Netlink message by completing the message with desirable flags and values depending on the socket configuration. - If not yet filled out, the source...
python
def kem(request): """ due to the base directory settings of django, the model_path needs to be different when testing with this section. """ keyword = request.GET['keyword'] lang = request.GET['lang'] ontology = 'ontology' if 'ontology' in request.GET and bool(json.loads(request.GET['ontology'].lower())) else 'o...
java
public static <K extends Comparable<? super K>, V> Comparator<Entry<K, V>> mapEntryComparator(boolean sortByKey, boolean ascending ...
python
def do_training(num_epoch, optimizer, kvstore, learning_rate, model_prefix, decay): """Perform CapsNet training""" summary_writer = SummaryWriter(args.tblog_dir) lr_scheduler = SimpleLRScheduler(learning_rate) optimizer_params = {'lr_scheduler': lr_scheduler} module.init_params() module.init_opt...
java
private File writeCleanupFile(int platformType) throws IOException { String fileSuffix = ".sh"; if (platformType == SelfExtractUtils.PlatformType_WINDOWS) { fileSuffix = ".bat"; } File file = File.createTempFile("wlpDelete", fileSuffix); if (!file.exists()) { ...
python
def fnmatch( name, pat ): """Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Bot...
python
def show_lb(kwargs=None, call=None): ''' Show the details of an existing load-balancer. CLI Example: .. code-block:: bash salt-cloud -f show_lb gce name=lb ''' if call != 'function': raise SaltCloudSystemExit( 'The show_lb function must be called with -f or --funct...
java
public DTMIterator iter() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!"); return null; }
java
private void addNewKeyToComponent(String key, Component component) throws ProviderConflictException { Component root = getRootComponent(); if (componentLocator.keySet().contains(key)) { String msg = String.format("Type %s has already been registered " + "in this componen...
python
def until_cmd(listcmd, end_expects=None, save2logfile=None, coding = encoding): ''' 执行系统命令,并等待执行完 @param listcmd: 执行的命令,列表格式 @param end_expects: 命令执行结束,在输出的最后一行,正则搜素期望值,并设置 结果标志 @param save2logfile: 设置执行过程,保存的日志 @param coding: 设置输出编码 ''' ...
python
def tags(self, tags=None): """Filter by tags. :param tags: Tags to filter. :type tags: ``list`` :return: A list of Node objects. :rtype: ``list`` of :class:`Node` """ if tags is None or not tags: return self nodes = [] for node in...
python
def solve_apply(expr, vars): """Returns the result of applying function (lhs) to its arguments (rest). We use IApplicative to apply the function, because that gives the host application an opportunity to compare the function being called against a whitelist. EFILTER will never directly call a function ...
python
def registry_key(self, key_name, value_name, value_type, **kwargs): """Add Registry Key data to Batch object. Args: key_name (str): The key_name value for this Indicator. value_name (str): The value_name value for this Indicator. value_type (str): The value_type valu...
java
public String convertRenderingIntentGOCARIToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public void addJMDict(InputStream stream) throws IOException, SAXException { new JMDictParser().parse(stream, new DictionaryJMDictReader(trie, errors), threeLetterlanguageCode); }
java
@SuppressWarnings("unchecked") public static <T extends Iterable<E>, R extends Collection<E>, E> Collector<T, ?, R> flat(Supplier<R> supplier) { return (Collector<T, ?, R>) Collector.of(supplier, R::addAll, (left, right) -> { left.addAll(right); return left; }); }
java
public void cache(String key, Object obj, int expiration) { H.Session session = this.session; if (null != session) { session.cache(key, obj, expiration); } else { app().cache().put(key, obj, expiration); } }
java
protected List<InetSocketAddress> getAddresses(final String s) { if (s == null) { throw new NullPointerException("Null host list"); } if (s.trim().isEmpty()) { throw new IllegalArgumentException("No hosts in list: '" + s + "'"); } List<InetSocketAddress> ...
python
def radec2azel(ra_deg: float, dec_deg: float, lat_deg: float, lon_deg: float, time: datetime) -> Tuple[float, float]: """ converts right ascension, declination to azimuth, elevation Parameters ---------- ra_deg : float or numpy.ndarray of float right ascension...
python
def publish(self, topic, obj, reference_message=None): """ Sends an object out over the pubsub connection, properly formatted, and conforming to the protocol. Handles pickling for the wire, etc. This method should *not* be subclassed. """ logging.debug("Publishing topic ...
python
def do_check(self, params): """ \x1b[1mNAME\x1b[0m check - Checks that a path is at a given version (only works within a transaction) \x1b[1mSYNOPSIS\x1b[0m check <path> <version> \x1b[1mEXAMPLES\x1b[0m > txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1' ""...
python
def put_file(self): """SCP copy the file from the local system to the remote device.""" destination = "{}/{}".format(self.file_system, self.dest_file) self.scp_conn.scp_transfer_file(self.source_file, destination) # Must close the SCP connection to get the file written (flush) se...
python
def get_value(self, addr, size, offset, **kwargs): '''Reading a value of any arbitrary size (max. unsigned int 64) and offset from a register Parameters ---------- addr : int The register address. size : int Bit size/length of the value. ...
python
def _init_metadata(self, **kwargs): """Initialize metadata for form""" self._mdata.update(default_mdata.get_osid_object_mdata()) OsidForm._init_metadata(self) if 'default_display_name' in kwargs: self._mdata['display_name']['default_string_values'][0]['text'] = kwargs['defaul...
python
def _list(self, path, collected): """ Lists all the files/dirs in directory that match the pattern. :param path: the directory to search :type path: str :param collected: the files/dirs collected so far (full path) :type collected: list :return: None if successfu...
python
def execute(self, state, successors=None, arguments=None, ret_to=None): """ Call this method with a SimState and a SimSuccessors to execute the procedure. Alternately, successors may be none if this is an inline call. In that case, you should provide arguments to the function. "...
python
def _parse_eval_args(self,*args,**kwargs): """ NAME: _parse_eval_args PURPOSE: Internal function to parse the arguments given for an action/frequency/angle evaluation INPUT: OUTPUT: HISTORY: 2010-07-11 - Written - Bovy (NYU) """ ...
java
public void setSyncStatus(com.google.api.ads.admanager.axis.v201811.SetTopBoxSyncStatus syncStatus) { this.syncStatus = syncStatus; }
python
def _get_triplet_value(self, graph, identity, rdf_type): """ Get a value from an RDF triple """ value = graph.value(subject=identity, predicate=rdf_type) return value.toPython() if value is not None else value
python
def plot_spectrum(self, spectrum_id, table='spectra', column='spectrum', overplot=False, color='b', norm=False): """ Plots a spectrum from the given column and table Parameters ---------- spectrum_id: int The id from the table of the spectrum to plot. overplo...