language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def pip_report(self): """ Show editable pip-requirements line necessary to clone this repository Yields: str: pip-requirements line necessary to clone this repository """ comment = '#' if not self.remote_url else '' if os.path.exists(os.path.join(self.fpath, ...
java
public static LogMetadata of(String key, Object value) { Map<String, Object> map = new HashMap<>(); map.put(key, value); return new LogMetadata(map); }
java
public static String toHexStringPadded(byte[] src, int offset, int length) { return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString(); }
python
def dispatch(self, event, *args): """ Dispatch an event where `args` is a tuple of the arguments to send to any callbacks. If any callback throws an exception, the subsequent callbacks will be aborted. """ for callback in self.listeners.get(event, []): if l...
java
public Object getValue(Object object) throws IllegalAccessException, InvocationTargetException { Object result = null; if (getter != null) { result = getter.invoke(object); } else if (field != null) { if(!field.isAccessible()){ field.setAccessible(true); ...
python
def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}): """ Method decorator to mark allowed transitions. Set target to None if current state needs to be validated and has not changed after the function call. """ def inner_transition(func): ...
java
private X509Certificate loadX509FromPEMFile(String filename) { try { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(FileReader.openStreamToFileFromClassPathOrPath(filename)); } catch (Exception e) { throw new RuntimeException("Exception readi...
python
def others2db(file_path, file_type, is_copy, step_id, db_conn): """Extract some meta-data from files (actually mostly from their paths) and stores it in a DB. Arguments: :param file_path: File path. :param file_type: File type. :param is_copy: Indicate if this file is a copy. :param step_id: St...
java
@Override public final String[] addAttribute(String name, String value) { signature = null; encryptedBytes = null; return userData.addAttribute(name, value); }
java
public static List<CommercePriceEntry> findByCPInstanceUuid( String CPInstanceUuid, int start, int end) { return getPersistence().findByCPInstanceUuid(CPInstanceUuid, start, end); }
python
def register_from_data(cls, key, format, data): """Register a image data using key""" if key in cls._stock: logger.info('Warning, replacing resource ' + str(key)) cls._stock[key] = {'type': 'data', 'data': data, 'format': format } logger.info('%s registered as %s' % ('data',...
python
def check_weather(self): ''' Check the weather using the configured backend ''' self.output['full_text'] = \ self.refresh_icon + self.output.get('full_text', '') self.backend.check_weather() self.refresh_display()
java
public static SQLTable get(final long _id) throws CacheReloadException { final Cache<Long, SQLTable> cache = InfinispanCache.get().<Long, SQLTable>getCache(SQLTable.IDCACHE); if (!cache.containsKey(_id)) { SQLTable.getSQLTableFromDB(SQLTable.SQL_ID, _id); } return...
python
def _retry(n, f, *args, **kwargs): '''Try to call f(*args, **kwargs) "n" times before giving up. Wait 2**n seconds before retries.''' for i in range(n): try: return f(*args, **kwargs) except Exception as exc: if i == n - 1: log.error( ...
java
public Observable<ServiceResponse<ProtectionContainerResourceInner>> registerWithServiceResponseAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, ProtectionContainerResourceInner parameters) { if (vaultName == null) { throw new IllegalArgumentException("Param...
python
def balancer_detach_member(balancer_id, member_id, profile, **libcloud_kwargs): ''' Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port f...
java
public static Date parse(String timeString) throws ParseException { // Return null if no time provided if (timeString == null || timeString.isEmpty()) return null; // Parse time according to format DateFormat timeFormat = new SimpleDateFormat(TimeField.FORMAT); ...
python
def filter_data_values(data): """Remove special values that log function can take There are some special values, like "request" that the `log()` function can take, but they're not meant to be passed to the celery task neither for the event handlers. This function filter these keys and return anothe...
python
def check_call_arguments(lineno, id_, args): """ Check arguments against function signature. Checks every argument in a function call against a function. Returns True on success. """ if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'): return False if not glo...
python
def size(self): """ The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar """ (halfw, halfh) = self._halfdim if self.orientation in ["top",...
python
def check_platform_variables(self, ds): ''' The value of platform attribute should be set to another variable which contains the details of the platform. There can be multiple platforms involved depending on if all the instances of the featureType in the collection share the same...
python
def _check(self, file): """ Run apropriate check based on `file`'s extension and return it, otherwise raise an Error """ if not os.path.exists(file): raise Error("file \"{}\" not found".format(file)) _, extension = os.path.splitext(file) try: ...
python
def get_password_data(self, instance_id): """ Get encrypted administrator password for a Windows instance. :type instance_id: string :param instance_id: The identifier of the instance to retrieve the password for. """ params = {'InstanceId' :...
python
def venn2_unweighted(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, subset_areas=(1, 1, 1), ax=None, subset_label_formatter=None): ''' The version of venn2 without area-weighting. It is implemented as a wrapper around venn2. Namely, venn2 is invoked as usual, but with al...
java
public AttributeType getTagAttribute() { if (tagAttributeType == null) { synchronized (this) { if (tagAttributeType == null) { String attribute = Config.get(typeName, name(), "tag").asString(); if (StringUtils.isNullOrBlank(attribute) && !AnnotationType.ROOT.equa...
java
public void document_id_PUT(String id, OvhDocument body) throws IOException { String qPath = "/me/document/{id}"; StringBuilder sb = path(qPath, id); exec(qPath, "PUT", sb.toString(), body); }
python
def p_expression_cond(self, p): 'expression : expression COND expression COLON expression' p[0] = Cond(p[1], p[3], p[5], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
python
def start_logger(self): """ Enables the root logger and configures extra loggers. """ level = self.real_level(self.level) logging.basicConfig(level=level) self.set_logger(self.name, self.level) config.dictConfig(self.config) self.logger = logging.getLogger...
java
public int read(long pos, byte[] b, int off, int len) { // since max is len (an int), result is guaranteed to be an int int bytesToRead = (int) bytesToRead(pos, len); if (bytesToRead > 0) { int remaining = bytesToRead; int blockIndex = blockIndex(pos); byte[] block = blocks[blockIndex]; ...
python
def __check_table_rules(configuration): """ Do some basic checks on the configuration """ for table_name in configuration['tables']: table = configuration['tables'][table_name] # Check that increase/decrease units is OK valid_units = ['percent', 'units'] if table['increase_reads_...
python
def get_user_by_action_token(action, token): """ Get the user by action token :param action: str :param token: str :return: AuthUser """ data = utils.unsign_url_safe(token, secret_key=get_jwt_secret(), salt=action) if data...
java
public static void decod_ACELP( int sign, /* input : signs of 4 pulses */ int index, /* input : positions of 4 pulses */ float cod[] /* output: innovative codevector */ ) { int pos[] = new int[4]; int i, j; /* decode the positions of 4 pulses */ i = inde...
java
public void marshall(RevisionLocation revisionLocation, ProtocolMarshaller protocolMarshaller) { if (revisionLocation == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(revisionLocation.getRevisionTyp...
java
@Override public Collection<Certificate> engineGetCertificates (CertSelector selector) throws CertStoreException { if (coll == null) { throw new CertStoreException("Collection is null"); } // Tolerate a few ConcurrentModificationExceptions for (int c = 0; c < ...
java
public void close() throws IOException { if (raf != null) { // gibt Lock auf datei frei try { if (this.fileLock != null) { if( !fileLock.release()) { LOG.error("Filelock not release properly"); } } ...
java
private double doubleValueLeftColor( double color, double right ) { return rgba( doubleValue( red( color ), right ), // doubleValue( green( color ), right ), // doubleValue( blue( color ), right ), 1 ); }
python
def transform(self, path): """ Transform a path into an actual Python object. The path can be arbitrary long. You can pass the path to a package, a module, a class, a function or a global variable, as deep as you want, as long as the deepest module is importable through ...
python
def from_json_format(conf): '''Convert fields of parsed json dictionary to python format''' if 'fmode' in conf: conf['fmode'] = int(conf['fmode'], 8) if 'dmode' in conf: conf['dmode'] = int(conf['dmode'], 8)
java
protected OrcKey convertOrcStructToOrcKey(OrcStruct struct) { OrcKey orcKey = new OrcKey(); orcKey.key = struct; return orcKey; }
python
def run(self, app_input, *args, **kwargs): """ Creates a new job that executes the function "main" of this app with the given input *app_input*. See :meth:`dxpy.bindings.dxapplet.DXExecutable.run` for the available args. """ # Rename app_input to preserve API com...
python
def send(self, request, pk=None): """ Sends all the subscriptions for the specified schedule """ schedule = self.get_object() queue_subscription_send.delay(str(schedule.id)) return Response({}, status=status.HTTP_202_ACCEPTED)
java
synchronized void dispose() { if (!isDisposed()) { // First wait for all data from the connection to be read. Then unregister the handle. // Otherwise, unregistering might cause the server to be stopped and all child connections // to be closed. if (connection != null) { try { ...
java
private void processFunctions(FileData coverageData, StringBuilder lcov) { int total = 0; int hit = 0; for (int functionNumber = 0; functionNumber < coverageData.getFunctions().size(); functionNumber++) { total++; Integer functionHits = coverageData.getFunctions().ge...
python
def _IAC_parser(self, buf, network_reader, network_writer, connection): """ Processes and removes any Telnet commands from the buffer. :param buf: buffer :returns: buffer minus Telnet commands """ skip_to = 0 while True: # Locate an IAC to process ...
python
def query(self, dataset, label=None, k=5, radius=None, verbose=True, batch_size=64): """ For each image, retrieve the nearest neighbors from the model's stored data. In general, the query dataset does not need to be the same as the reference data stored in the model. Parameters ...
python
def add_string(self, string): """Add to the working string and its length and reset eos.""" self.string += string self.length += len(string) self.eos = 0
python
def setMaxSpeedLat(self, vehID, speed): """setMaxSpeedLat(string, double) -> None Sets the maximum lateral speed in m/s for this vehicle. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_MAXSPEED_LAT, vehID, speed)
python
def set_vcard(self, vcard): """ Store the vCard `vcard` for the connected entity. :param vcard: the vCard to store. .. note:: `vcard` should always be derived from the result of `get_vcard` to preserve the elements of the vcard the client does not modi...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case SimpleExpressionsPackage.BOOLEAN_LITERAL__VALUE: return value != VALUE_EDEFAULT; } return super.eIsSet(featureID); }
java
protected void updateLastScanFile() { final String methodName = "updateLastScanFile()"; final File f = new File(lastScanFileName); final CacheOnDisk cod = this; traceDebug(methodName, "cacheName=" + this.cacheName); AccessController.doPrivileged(new PrivilegedAction() { ...
python
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ ...
java
public static CharMatcher inRange(final char startInclusive, final char endInclusive) { checkArgument(endInclusive >= startInclusive); return new FastMatcher() { @Override public boolean matches(char c) { return startInclusive <= c && c <= endInclusive; } @GwtIncompatible("java.util.B...
python
def _parse_general_counters(self, init_config): """ Return a dictionary for each job counter { counter_group_name: [ counter_name ] } } """ job_counter = {} if init_config.get('general_counters'): # Parse...
python
def _eval_target_jumptable(state, ip, limit): """ A *very* fast method to evaluate symbolic jump targets if they are a) concrete targets, or b) targets coming from jump tables. :param state: A SimState instance. :param ip: The AST of the instruction pointer to evaluate. ...
python
def command(func_or_args=None): """Decorator to tell Skal that the method/function is a command. """ def decorator(f): f.__args__ = args return f if type(func_or_args) == type(decorator): args = {} return decorator(func_or_args) args = func_or_args return decorat...
python
def find_connectable_ip(host, port=None): """Resolve a hostname to an IP, preferring IPv4 addresses. We prefer IPv4 so that we don't change behavior from previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections. If the optional port number ...
java
public static <E> OptionalFunction<Selection<Element>, E> getValue() { return OptionalFunction.of(selection -> selection.result().getValue()); }
python
def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = ctypes.c_voidp(0) else: if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']: data = data.copy('C') d...
java
private void processBrowserFieldAdvancedUsage(String dirName, Node entry) { for (Node child : entry.children()) { Node value = child.getFirstChild(); checkState(child.isStringKey() && (value.isString() || value.isFalse())); String path = child.getString(); if (path.startsWith(ModuleLoader...
java
public ComputationGraph fitMultiDataSet(JavaRDD<MultiDataSet> rdd) { if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueue(); trainingMaster.executeTrainingMDS(this, rdd); network.incrementEpochCount(); return network; ...
python
def heating_degree_days(tas, thresh='17.0 degC', freq='YS'): r"""Heating degree days Sum of degree days below the temperature threshold at which spaces are heated. Parameters ---------- tas : xarray.DataArray Mean daily temperature [℃] or [K] thresh : str Threshold temperature on w...
java
public static <C extends Compound> int indexOf(Sequence<C> sequence, C compound) { int index = 1; for (C currentCompound : sequence) { if (currentCompound.equals(compound)) { return index; } index++; } return 0; }
python
def fifty_fifty(network, storage, feedin_threshold=0.5): """ Operational mode where the storage operation depends on actual power by generators. If cumulative generation exceeds 50% of nominal power, the storage is charged. Otherwise, the storage is discharged. The time series for active power is wr...
java
public Long getMin() { return processFunction(new AbstractSplitFunction<Long>(Long.MAX_VALUE) { @Override public void evaluate(long runningFor) { if (runningFor < result) { result = runningFor; } } }); }
python
def inventory(self, modules_inventory=False): """ Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. """ self.c_info = self.get_attributes() for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()): ...
python
def split(self, seps, predicate=None, index=None): """ Split this match in multiple matches using given separators. :param seps: :type seps: string containing separator characters :return: list of new Match objects :rtype: list """ split_match = copy.deepc...
java
private static int port(final File file) throws Exception { while (!file.exists()) { TimeUnit.MILLISECONDS.sleep(1L); } final int port; try (InputStream input = Files.newInputStream(file.toPath())) { // @checkstyle MagicNumber (1 line) final byte[] buf...
java
public Terms getAllTerms(String listId, String language, GetAllTermsOptionalParameter getAllTermsOptionalParameter) { return getAllTermsWithServiceResponseAsync(listId, language, getAllTermsOptionalParameter).toBlocking().single().body(); }
python
def chunks(self, chunk_size: int) -> Generator['TranslatorInput', None, None]: """ Takes a TranslatorInput (itself) and yields TranslatorInputs for chunks of size chunk_size. :param chunk_size: The maximum size of a chunk. :return: A generator of TranslatorInputs, one for each chunk cre...
python
def get_installed_daps(location=None, skip_distro=False): '''Returns a set of all installed daps Either in the given location or in all of them''' if location: locations = [location] else: locations = _data_dirs() s = set() for loc in locations: if skip_distro and loc == ...
java
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver(Function<ResolverContext, String> getter) { return (resolver, ctx) -> resolver.convert(getter.apply(ctx)); }
java
public void insertNewRow() { // reset all fields for (int i = 0; i < komponente.length; i++) { komponente[i].clearContent(); } // end of for (int i=0; i<komponente.length; i++) // reset the field for the primary keys for (int i = 0; i < primaryKeys.length; i++) {...
python
def start(self, wait=60, *, server_settings={}, **opts): """Start the cluster.""" status = self.get_status() if status == 'running': return elif status == 'not-initialized': raise ClusterError( 'cluster in {!r} has not been initialized'.format( ...
python
def create(self, create_missing=None): """Manually fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1219654 <https://bugzilla.redhat.com/show_bug.cgi?id=1219654>`_. """ return Domain( self._server_config, id=self.c...
java
@BetaApi public final Operation deleteGlobalAddress(String address) { DeleteGlobalAddressHttpRequest request = DeleteGlobalAddressHttpRequest.newBuilder().setAddress(address).build(); return deleteGlobalAddress(request); }
java
public Collection<EntityAnnotation> getEntityAnnotationsByConfidenceValue( final Double confidenceValue) { return FluentIterable.from(getEntityAnnotations()) .filter(new Predicate<EntityAnnotation>() { @Override public boolean apply(EntityAnnot...
java
@Override public double d(Concept x, Concept y) { if (x.taxonomy != y.taxonomy) { throw new IllegalArgumentException("Concepts are not from the same taxonomy."); } List<Concept> xPath = x.getPathFromRoot(); List<Concept> yPath = y.getPathFromRoot(); Iterator<Con...
java
@Process(actionType = ModifyStandardRole.class) public void modifyStandardRole(final ModifyStandardRole action, final Channel channel) { Role role = action.getRole(); new Async<FunctionContext>().waterfall(new FunctionContext(), new ReloadOutcome(channel), new AccessControlFunctions....
java
public void reportCompletion(NodeT completed) { completed.setPreparer(true); String dependency = completed.key(); for (String dependentKey : nodeTable.get(dependency).dependentKeys()) { DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey); dependent.lock().lock()...
python
def ispymodule(self): '''Check if this :class:`Path` is a python module.''' if self.isdir(): return os.path.isfile(os.path.join(self, '__init__.py')) elif self.isfile(): return self.endswith('.py')
java
static char[] obtain(int len) { char[] buf; synchronized (sLock) { buf = sTemp; sTemp = null; } if (buf == null || buf.length < len) buf = new char[ArrayUtils.idealCharArraySize(len)]; return buf; }
python
def query( self, query, job_config=None, job_id=None, job_id_prefix=None, location=None, project=None, retry=DEFAULT_RETRY, ): """Run a SQL query. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration....
python
def power_cycle(env, identifier): """Power cycle a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' ...
java
@SafeVarargs public static <T> Optional<T> lowestCommonAncestor(TreeDef.Parented<T> treeDef, T... nodes) { return lowestCommonAncestor(treeDef, Arrays.asList(nodes)); }
python
def get_hash(self, handle): """Return the hash.""" fpath = self._fpath_from_handle(handle) return DiskStorageBroker.hasher(fpath)
python
def transformer_nat_base(): """Set of hyperparameters.""" hparams = transformer_nat_small() hparams.batch_size = 2048 hparams.hidden_size = 512 hparams.filter_size = 4096 hparams.num_hidden_layers = 6 return hparams
python
def dataset_docs_str(datasets=None): """Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format). """ m...
java
@SafeVarargs public static <T> Set<T> newSets(T... values) { if(null == values || values.length == 0){ Assert.notNull(values, "values not is null."); } return new HashSet<>(Arrays.asList(values)); }
python
def _dens(self,R,z,phi=0.,t=0.): """ NAME: _dens PURPOSE: evaluate the density for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the densi...
java
@Override public CreateStackInstancesResult createStackInstances(CreateStackInstancesRequest request) { request = beforeClientExecution(request); return executeCreateStackInstances(request); }
java
public <T extends Relation> T add(T statement, int num, Collection<T> anonRelationCollection, HashMap<QualifiedName, Collection<T>> namedRelationMap, HashMap<QualifiedName,...
java
private void replaceProperties(Set<CmsResource> matchedResources) { for (CmsResource resource : matchedResources) { try { CmsProperty prop = getCms().readPropertyObject(resource, m_settings.getProperty().getName(), false); Matcher matcher = Pattern.compile(m_settings...
java
public DescribeHsmConfigurationsRequest withTagKeys(String... tagKeys) { if (this.tagKeys == null) { setTagKeys(new com.amazonaws.internal.SdkInternalList<String>(tagKeys.length)); } for (String ele : tagKeys) { this.tagKeys.add(ele); } return this; }
python
def list_buckets(self, offset=0, limit=100): """Limit breaks above 100""" # TODO: If limit > 100, do multiple fetches if limit > 100: raise Exception("Zenobase can't handle limits over 100") return self._get("/users/{}/buckets/?order=label&offset={}&limit={}".format(self.clie...
java
private static Integer sysctlGetInt(String sysctlKey) throws IOException { Process process = new ProcessBuilder("sysctl", sysctlKey).start(); try { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new Bu...
java
@Override public void ok(Object result) { Object resultCvt = _marshal.convert(result); delegate().ok(resultCvt); }
python
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki,...
python
def write(self, outfile, format='ESRI Shapefile', overwrite=True): """ write the Vector object to a file Parameters ---------- outfile: the name of the file to write format: str the output file format overwrite: bool overwrite ...
python
def setup_hds_obs(hds_file,kperk_pairs=None,skip=None,prefix="hds"): """a function to setup using all values from a layer-stress period pair for observations. Writes an instruction file and a _setup_ csv used construct a control file. Parameters ---------- hds_file : str a MODFLOW ...
java
protected Operation snapshotTable(String snapshotName, TableName tableName) throws IOException { SnapshotTableRequest.Builder requestBuilder = SnapshotTableRequest.newBuilder() .setCluster(getSnapshotClusterName().toString()) .setSnapshotId(snapshotName) .setName(options.getInstanceNa...