language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_nn_info(self, structure, n): """ Get all near-neighbor sites and weights (orders) of bonds for a given atom. :param molecule: input Molecule. :param n: index of site for which to determine near neighbors. :return: [dict] representing a neighboring site and the ty...
python
def keyring_auth(self, username=None): """ Uses the keyring module to retrieve the user's password or api_key. """ if not keyring: # Module not installed raise exc.KeyringModuleNotInstalled("The 'keyring' Python module " "is not installed on th...
python
def find_tendril(cls, proto, addr): """ Finds the tendril corresponding to the protocol and address tuple. Returns the Tendril object, or raises KeyError if the tendril is not tracked. The address tuple is the tuple of the local address and the remote address for the te...
python
def upload(server, session, base_file, charset='UTF-8'): """Push a layer to a Geonode instance. :param server: The Geonode server URL. :type server: basestring :param base_file: The base file layer to upload such as a shp, geojson, ... :type base_file: basestring :param charset: The encoding ...
java
public synchronized String makeEscapedCompactString() { StringBuffer buffer = new StringBuffer(); for(Group group: this){ buffer.append(group.makeEscapedCompactString()); } return buffer.toString(); }
python
def _split_raw_signature(sig): """ Split raw signature into components :param sig: The signature :return: A 2-tuple """ c_length = len(sig) // 2 r = int_from_bytes(sig[:c_length], byteorder='big') s = int_from_bytes(sig[c_length:], byteorder='big') ...
python
def plotline(plt, alpha, taus, style,label=""): """ plot a line with the slope alpha """ y = [pow(tt, alpha) for tt in taus] plt.loglog(taus, y, style,label=label)
python
def AddFiles(self, hash_id_metadatas): """Adds multiple files to the file store. Args: hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple of hash client path and blob references). """ for hash_id, metadata in iteritems(hash_id_metadatas): self.AddFile(hash_id...
java
public java.lang.String getFooterClass() { return (java.lang.String) getStateHelper().eval(PropertyKeys.footerClass); }
python
def frequency_model( self ): """ build a letter frequency model for Tamil letters from a corpus """ # use a generator in corpus for next_letter in self.corpus.next_tamil_letter(): # update frequency from corpus self.letter[next_letter] = self.letter[next_letter] + 1
java
public Matrix4d rotationTowards(Vector3dc dir, Vector3dc up) { return rotationTowards(dir.x(), dir.y(), dir.z(), up.x(), up.y(), up.z()); }
python
def run(configobj=None): """ TEAL interface for the `acs2d` function. """ acs2d(configobj['input'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], quiet=configobj['quiet'] )
java
public InputMapTemplate<S, E> ifIgnored(BiConsumer<? super S, ? super E> postIgnore) { return postResult(Result.IGNORE, postIgnore); }
java
@SuppressWarnings({"WeakerAccess", "unused"}) public Picture renderViewToPicture(String viewId, int widthInPixels, int heightInPixels) { RenderOptions renderOptions = new RenderOptions(); renderOptions.view(viewId) .viewPort(0f, 0f, (float) widthInPixels, (float) heightInPixe...
python
def C_Reader_Harris_Gallagher_wet_venturi_tube(mg, ml, rhog, rhol, D, Do, H=1): r'''Calculates the coefficient of discharge of the wet gas venturi tube based on the geometry of the tube, mass flow rates of liquid and vapor through the tube, the density of the liquid and gas phases, and an adjustable ...
java
public void saveWithTrainingConfig(OutputStream outputStream) throws IOException { if(this.trainingConfig == null) { throw new IllegalStateException("No training configuration found!"); } saveWithTrainingConfig(this.trainingConfig,outputStream); }
python
def filter_service_by_servicegroup_name(group): """Filter for service Filter on group :param group: group to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if group in service.servicegroups""" servic...
java
public String getPath() { StringBuilder result = new StringBuilder().append('$'); for (int i = 0, size = stackSize; i < size; i++) { switch (stack[i]) { case JsonScope.EMPTY_ARRAY: case JsonScope.NONEMPTY_ARRAY: result.append('[').append(pathIndices[i]).append(']'); bre...
java
public ServiceFuture<List<AppServiceCertificateResourceInner>> listCertificatesNextAsync(final String nextPageLink, final ServiceFuture<List<AppServiceCertificateResourceInner>> serviceFuture, final ListOperationCallback<AppServiceCertificateResourceInner> serviceCallback) { return AzureServiceFuture.fromPageRe...
java
public static base_response update(nitro_service client, clusternode resource) throws Exception { clusternode updateresource = new clusternode(); updateresource.nodeid = resource.nodeid; updateresource.state = resource.state; updateresource.backplane = resource.backplane; updateresource.priority = resource.pr...
python
def server_mechanisms(self): """List of available :class:`ServerMechanism` objects.""" return [mech for mech in self.mechs.values() if isinstance(mech, ServerMechanism)]
python
def set_data_points(self, points): """ Input `points` must be in data coordinates, will be converted to the coordinate space of the object and stored. """ self.points = np.asarray(self.crdmap.data_to(points))
java
public void clearFields() { this.requiredFields = NO_FIELDS; this.optionalFields = NO_FIELDS; this.textFields = Collections.emptyMap(); removeAll(); validate(); }
python
def name(self): """str: name of the file entry, which does not include the full path. Raises: BackEndError: if pytsk3 returns a non UTF-8 formatted name. """ if self._name is None: # If pytsk3.FS_Info.open() was used file.info has an attribute name # (pytsk3.TSK_FS_FILE) that contains...
java
@Override protected String createDialogHtml(String dialog) { StringBuffer result = new StringBuffer(512); result.append(createWidgetTableStart()); // show error header once if there were validation errors result.append(createWidgetErrorHeader()); if (dialog.equals(PAGES[0]...
python
def prebuild_arch(self, arch): """Make the build and target directories""" path = self.get_build_dir(arch.arch) if not exists(path): info("creating {}".format(path)) shprint(sh.mkdir, '-p', path)
python
def list(self, platformIdentifier, configuration, libOverrides = {}): """ Returns the list of supported UE4-bundled third-party libraries """ modules = self._getThirdPartyLibs(platformIdentifier, configuration) return sorted([m['Name'] for m in modules] + [key for key in libOverrides])
python
def eval_master_func(opts): ''' Evaluate master function if master type is 'func' and save it result in opts['master'] ''' if '__master_func_evaluated' not in opts: # split module and function and try loading the module mod_fun = opts['master'] mod, fun = mod_fun.split('.') ...
java
public boolean isCurrentIgnoreSpace(char c) { if (!hasNext()) return false; int start = getPos(); removeSpace(); boolean is = isCurrent(c); setPos(start); return is; }
java
public synchronized AcceleratedScreen getAcceleratedScreen(int[] attributes) throws GLException, UnsatisfiedLinkError { if (accScreen == null) { accScreen = new AcceleratedScreen(attributes); } return accScreen; }
java
public void setProfileTaskRange(boolean isMap, String newValue) { // parse the value to make sure it is legal new Configuration.IntegerRanges(newValue); set((isMap ? "mapred.task.profile.maps" : "mapred.task.profile.reduces"), newValue); }
java
public static ApnsSigningKey loadFromPkcs8File(final File pkcs8File, final String teamId, final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException { try (final FileInputStream fileInputStream = new FileInputStream(pkcs8File)) { return ApnsSigningKey.loadFromInputStream(f...
java
private List<BaseInvoker> getInvokersForPointcut(Pointcut thePointcut) { List<BaseInvoker> invokers; synchronized (myRegistryMutex) { List<BaseInvoker> globalInvokers = myGlobalInvokers.get(thePointcut); List<BaseInvoker> anonymousInvokers = myAnonymousInvokers.get(thePointcut); List<BaseInvoker> threadLo...
java
public synchronized void gc() { if (!configuration.isUseGc()) { LOG.trace("GC deactivated, no beans will be removed!"); return; } LOG.trace("Garbage collection started! GC will remove {} beans!", removeOnGC.size()); onRemoveCallback.onReject(removeOnGC.keySet())...
java
@Override public java.util.concurrent.Future<ListQueueTagsResult> listQueueTagsAsync(String queueUrl) { return listQueueTagsAsync(new ListQueueTagsRequest().withQueueUrl(queueUrl)); }
java
@SuppressWarnings("unchecked") private static LogAdapterFactory createAdapterFactory() { List<LogAdapterFactory> factories = Iterators.asList(ServiceLoader.load(LogAdapterFactory.class)); if (factories.isEmpty()) { /* * Always fall back to the JDK, even if our service loading ...
python
def move_application(self, app_id, queue): """Move an application to a different queue. Parameters ---------- app_id : str The id of the application to move. queue : str The queue to move the application to. """ self._call('moveApplication...
python
def _sign_input(cls, input_, message, key_pairs): """Signs a single Input. Note: This method works only for the following Cryptoconditions currently: - Ed25519Fulfillment - ThresholdSha256. Args: in...
python
def get_order_specification_visitor(name, registry=None): """ Returns the class registered as the order specification visitor utility under the given name (one of the :const:`everest.querying.base.EXPRESSION_KINDS` constants). :returns: class implementing :class:`everest.interfaces.IOrderSp...
python
def create_from_xml(root, extdir=None): """Create a Source object from an XML node. Parameters ---------- root : `~xml.etree.ElementTree.Element` XML node containing the source. extdir : str Path to the extended source archive. """ src_t...
python
def ggsave(name, plot, data=None, *args, **kwargs): """Save a GGStatements object to destination name @param name output file name. if None, don't run R command @param kwargs keyword args to pass to ggsave. The following are special keywords for the python save method data: a python da...
java
public static String readStringFromFile(String path, SparkContext sc) throws IOException { return readStringFromFile(path, sc.hadoopConfiguration()); }
python
def herp_derp_interp(place): """simple interpolation of GFS forecast""" lat, lon = place #begin=2014-02-14T00%3A00%3A00&end=2018-02-22T00%3A00%3A00 fmt = '%Y-%m-%dT00:00:00' fmt = '%Y-%m-%dT%H:%M:00' begin = (datetime.datetime.now()-datetime.timedelta(hours=12)).strftime(fmt) #end=(datetime....
java
public ExecutionContext transform(Consumer<ExecutionContextBuilder> builderConsumer) { ExecutionContextBuilder builder = ExecutionContextBuilder.newExecutionContextBuilder(this); builderConsumer.accept(builder); return builder.build(); }
python
def main(args): """ Main function - launches the program """ if args: if not args.outputRepository: HOME_DIR = os.path.expanduser('~') # Utility's base directory BASE_DIR = os.path.abspath(os.path.dirname(__file__)) DOWNLOAD_DIR = HOME_DI...
java
public static String elasticSearchTimeFormatToISO8601(String time) { try { DateTime dt = DateTime.parse(time, ES_DATE_FORMAT_FORMATTER); return getISO8601String(dt); } catch (IllegalArgumentException e) { return time; } }
python
def forward(self, speed=1): """ Drive the motor forwards. :param float speed: The speed at which the motor should turn. Can be any value between 0 (stopped) and the default 1 (maximum speed). """ if isinstance(self.enable_device, DigitalOutputDevice): ...
python
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
python
def _get_command(classes): """Associates each command class with command depending on setup.cfg """ commands = {} setup_file = os.path.join( os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')), 'setup.cfg') for line in open(setup_file, 'r'): for cl in classes: ...
python
def kill(name, signal): ''' sends a kill signal to process 1 of ths container <name> :param signal: numeric signal ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-kill', '--name=%s' % name, signal] subprocess.check_ca...
python
def log_create(self, instance, **kwargs): """ Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given. :param instance: The model instance to log a change for. :type instance: Model :param kwargs: Field ove...
java
static String convertURLToString(URL url) { if (URISchemeType.FILE.isURL(url)) { final StringBuilder externalForm = new StringBuilder(); externalForm.append(url.getPath()); final String ref = url.getRef(); if (!Strings.isEmpty(ref)) { externalForm.append("#").append(ref); //$NON-NLS-1$ } return ...
python
def form_uri(item_content, item_class): """Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.Mus...
java
private Object getComponentProperty(_PropertyDescriptorHolder propertyDescriptor) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null) { throw new IllegalArgumentException("Component property " + propertyDescriptor.getName() ...
java
public static IntegerBinding getExponent(final ObservableFloatValue f) { return createIntegerBinding(() -> Math.getExponent(f.get()), f); }
java
public static DataSource createDataSource(final Map<String, DataSource> dataSourceMap, final File yamlFile) throws SQLException, IOException { YamlRootShardingConfiguration config = YamlEngine.unmarshal(yamlFile, YamlRootShardingConfiguration.class); return ShardingDataSourceFactory.createDataSource(dat...
python
def _cellmagic(cls, options, obj, strict=False): "Deprecated, not expected to be used by any current code" options, failure = cls._process_magic(options, strict) if failure: return obj if not isinstance(obj, Dimensioned): return obj else: return StoreOptio...
python
def find_transport_reactions(model): """ Return a list of all transport reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- A transport reaction is defined as follows: 1. It contains metabolites from at least 2 compartme...
python
def param_extract(args, short_form, long_form, default=None): """ Quick extraction of a parameter from the command line argument list. In some cases we need to parse a few arguments before the official arg-parser starts. Returns parameter value, or None if not present. """ val = default ...
java
private void readMetadata() throws SQLException { if (valid) { return; } String[] metaInfos = queryMetaInfos(isFunction); String paramList = metaInfos[0]; String functionReturn = metaInfos[1]; parseParamList(isFunction, paramList); // parse type of the return value (for functions) ...
java
public int read() throws IOException { if (_peek >= 0) { int peek = _peek; _peek = -1; return peek; } InputStream is = _is; int ch1 = is.read(); if (ch1 < 0x80) { return ch1; } else if ((ch1 & 0xe0) == 0xc0) { int ch2 = is.read(); i...
python
def __store_config(self, args, kwargs): """ Assign args to kwargs and store configuration. """ signature = ( 'schema', 'ignore_none_values', 'allow_unknown', 'require_all', 'purge_unknown', 'purge_readonly', ) for i,...
java
public void configInterceptor(Interceptors me) { // add excetion interceptor me.add(new ExceptionInterceptor()); if (this.getHttpPostMethod()) { me.add(new POST()); } // config others configMoreInterceptors(me); }
python
def _write_docstring_parameters(self, routine): """ Writes the parameters part of the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine. """ if routine['pydoc']['parameters']: self._write_line('') ...
python
def batch_run_many(player, positions, batch_size=100): """Used to avoid a memory oveflow issue when running the network on too many positions. TODO: This should be a member function of player.network?""" prob_list = [] value_list = [] for idx in range(0, len(positions), batch_size): prob...
python
def set_collections_acl(self): """ Calculate and set ACL valid for requested collections. DENY_ALL is added to ACL to make sure no access rules are inherited. """ acl = [(Allow, 'g:admin', ALL_PERMISSIONS)] collections = self.get_collections() resources = self.ge...
python
def load(self, context): """Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A InteractiveInferencePlugin instance or None if it couldn't be loaded. """ try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow except Import...
java
public static Filter toTimestampRangeFilter(long bigtableStartTimestamp, long bigtableEndTimestamp) { return FILTERS.timestamp().range().of(bigtableStartTimestamp, bigtableEndTimestamp); }
python
def generate_sample_cdk_tsc_module(env_root, module_dir=None): """Generate skeleton CDK TS sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.cdk') generate_sample_module(module_dir) for i in ['.npmignore', 'cdk.json', 'package.json', 'runway.module.yml', ...
java
public static void convertBaseClasses (ImportSet imports) { // replace primitive types with OOO types (required for unboxing) imports.replace("byte", "com.threerings.util.Byte"); imports.replace("boolean", "com.threerings.util.langBoolean"); imports.replace("[B", "flash.utils.ByteArr...
java
public ClientContact instantiateForInsert() { ClientContact entity = new ClientContact(); entity.setCategory(new Category(512973)); entity.setClientCorporation(new ClientCorporation(1)); entity.setEmail("unknown"); entity.setNumEmployees(1); entity.setIsDeleted(Boolean.FALSE); entity.setPreferredContact("...
java
public boolean equalAny(final TokenType... tokenTypes) { for (TokenType each : tokenTypes) { if (each == lexer.getCurrentToken().getType()) { return true; } } return false; }
java
private static boolean isKnownLeafClassLoader(final ClassLoader classLoader) { if (classLoader == null) { return false; } if (!isKnownClassLoaderAccessibleFrom(classClassLoader, classLoader)) { // We cannot access the class class loader from the specified class loader, ...
python
def setLoggingFromOptions(options): """Sets the logging from a dictionary of name/value options. """ #We can now set up the logging info. if options.logLevel is not None: setLogLevel(options.logLevel) #Use log level, unless flags are set.. if options.logOff: setLogLevel("OFF") e...
python
def _to_roman(num): """Convert integer to roman numerals.""" roman_numeral_map = ( ('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ...
python
def ListChildPathInfos(self, client_id, path_type, components, timestamp=None): """Lists path info records that correspond to children of given path. Args: client_id: An identifier string for a client. path_type: A type of a path to retrieve path information for. comp...
python
def finalize_oauth(self, access_token, access_token_secret): """ Called internally once auth process is complete. """ self.access_token = access_token self.access_token_secret = access_token_secret # Final OAuth object self.oauth = OAuth1( self.consumer_key, ...
python
def clear(self): """Clear ErrorMessage. """ self.problems = [] self.details = [] self.suggestions = [] self.tracebacks = []
java
public Schemata getSchemataForSession( JcrSession session ) { assert session != null; // If the session does not override any namespace mappings used in this schemata ... if (!overridesNamespaceMappings(session)) { // Then we can just use this schemata instance ... return...
java
Stream<String> writeMeter(Meter m) { List<Field> fields = new ArrayList<>(); for (Measurement measurement : m.measure()) { double value = measurement.getValue(); if (!Double.isFinite(value)) { continue; } String fieldKey = measurement.getSt...
java
public static void logDiffException(final Logger logger, final DiffException e) { logger.logException(Level.ERROR, "DiffException", e); }
java
@SuppressWarnings("unchecked") // safe covariant cast public static ImmutableSet<OpenOption> getOptionsForInputStream(OpenOption... options) { boolean nofollowLinks = false; for (OpenOption option : options) { if (checkNotNull(option) != READ) { if (option == LinkOption.NOFOLLOW_LINKS) { ...
java
private static void parseChildShapes(ArrayList<Shape> shapes, JSONObject modelJSON, Shape current) throws JSONException { if (modelJSON.has("childShapes")) { ArrayList<Shape> childShapes = new ArrayList<Shape>(); ...
java
public static ResourceList<Message> list(final BandwidthClient client, final int page, final int size) throws Exception { final String messageUri = client.getUserResourceUri(BandwidthConstants.MESSAGES_URI_PATH); final ResourceList<Message> messages = new ResourceList<Message>(page, s...
java
public static ApruveResponse<Payment> get(String paymentRequestId, String paymentId) { return ApruveClient.getInstance().get( getPaymentsPath(paymentRequestId) + paymentId, Payment.class); }
java
public String getObjectType(int groupID, int objectID) { if (groupID >= 0 && groupID < objectGroups.size()) { ObjectGroup grp = (ObjectGroup) objectGroups.get(groupID); if (objectID >= 0 && objectID < grp.objects.size()) { GroupObject object = (GroupObject) grp.objects.get(objectID); return object....
python
def in_list(list_to_search, string_to_search): """ Verify if the list contains the item. :param list_to_search: The list. :type list_to_search: str :param string_to_search: The value of item. :type string_to_search: str :return: True if the list contains the item...
python
def deploy(project_name): """Assemble the middleware pipeline""" request_log = requestlog.RequestLog header_addon = HeaderControl fault_wrapper = FaultWrapper application = handler.SdkHandler() # currently we have 3 middleware for middleware in (header_addon, fault_wr...
java
public boolean containsFunction(String ns, String name) { for (int i = 0; i < this.libraries.length; i++) { if (this.libraries[i].containsFunction(ns, name)) { return true; } } return false; }
python
def fingerprint_relaxation(T, p0, obs, tau=1, k=None, ncv=None): r"""Dynamical fingerprint for relaxation experiment. The dynamical fingerprint is given by the implied time-scale spectrum together with the corresponding amplitudes. Parameters ---------- T : (M, M) ndarray or scipy.sparse matri...
python
def align_unaligned_seqs(seqs_fp, moltype=DNA, params=None, accurate=False): """Aligns unaligned sequences Parameters ---------- seqs_fp : string file path of the input fasta file moltype : {skbio.DNA, skbio.RNA, skbio.Protein} params : dict-like type It pass the additional para...
java
public int activeGroupCount() { int ngroupsSnapshot; ThreadGroup[] groupsSnapshot; synchronized (this) { if (destroyed) { return 0; } ngroupsSnapshot = ngroups; if (groups != null) { groupsSnapshot = Arrays.copyOf(gr...
python
def servertoken(self,serverURL,referer): """ returns the server token for the server """ if self._server_token is None or self._server_token_expires_on is None or \ datetime.datetime.now() >= self._server_token_expires_on or \ self._server_url != serverURL: self._server...
python
def apply_motion_tracks(self, tracks, accuracy=0.004): """ Similar to click but press the screen for the given time interval and then release Args: tracks (:py:obj:`list`): list of :py:class:`poco.utils.track.MotionTrack` object accuracy (:py:obj:`float`): motion accuracy ...
python
def inverse_transform(self, maps): """This function transforms from luminosity distance to chirp distance, given the chirp mass. Parameters ---------- maps : a mapping object Examples -------- Convert a dict of numpy.array: >>> import numpy as n...
java
public int getInt() { int v = 0; v |= ((getByte() & 0xFF) << 24); v |= ((getByte() & 0xFF) << 16); v |= ((getByte() & 0xFF) << 8); v |= (getByte() & 0xFF); return v; }
java
@Deprecated public static SqlRunner newSqlRunner(DataSource ds, Dialect dialect) { return SqlRunner.create(ds, dialect); }
python
def ed(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """ Compute the Euclidean distance between predicted and observed values in vector space. .. image:: /pictures/ED.png **Range** 0 ≤ ED < inf, smaller is better. **Notes** Also s...
java
@Nonnull public T create( @Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) { return performCreate(documentReference, fields); }
python
def load_mnist(size: int = None, border: int = _MNIST_BORDER, blank_corners: bool = False, nums: List[int] = None) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Download and rescale the MNIST database of handwritten digits MNIST is a dataset...