query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Convert the image to a NormalCloud object. Returns ------- :obj:`autolab_core.NormalCloud` The corresponding NormalCloud.
def to_normal_cloud(self): """Convert the image to a NormalCloud object. Returns ------- :obj:`autolab_core.NormalCloud` The corresponding NormalCloud. """ return NormalCloud( data=self._data.reshape( self.height * ...
csn
Ensure a group contains only the members in the list Args: name (str): The name of the group to modify members_list (str): A single user or a comma separated list of users. The group will contain only the users specified in this list. Returns: bool...
def members(name, members_list, **kwargs): ''' Ensure a group contains only the members in the list Args: name (str): The name of the group to modify members_list (str): A single user or a comma separated list of users. The group will contain only the u...
csn
Send the emails message. @param \Swift_Transport $transport The swift transport @param null|string[] $failedRecipients The failed recipients @param SpoolEmailInterface[] $emails The spool emails @return int The count of sent emails
protected function sendEmails(Swift_Transport $transport, &$failedRecipients, array $emails) { $count = 0; $time = time(); $emails = $this->prepareEmails($emails); $skip = false; foreach ($emails as $email) { if ($skip) { $email->setStatus(SpoolEm...
csn
Update counter filter @see http://api.yandex.ru/metrika/doc/beta/management/filters/editfilter.xml @param int $id @param int $counterId @param Models\Filter $filter @return array
public function updateFilter($id, $counterId, Models\Filter $filter) { $resource = 'counter/' . $counterId . '/filter/' . $id; $response = $this->sendPutRequest($resource, ["filter" => $filter->toArray()]); $filterResponse = new Models\UpdateFilterResponse($response); return $filterR...
csn
Sort the analyses by AR ID ascending and subsorted by priority sortkey within the AR they belong to
def sorted_analyses(self, analyses): """Sort the analyses by AR ID ascending and subsorted by priority sortkey within the AR they belong to """ analyses = sorted(analyses, key=lambda an: an.getRequestID()) def sorted_by_sortkey(objs): return sorted(objs, key=lambda a...
csn
Lowercase internal types and replace alias type with full type. @param string $type @return string
public function normalizeType(string $type): string { if (strpos($type, '|') !== false) { $types = array_map([$this, __FUNCTION__], explode('|', $type)); return join('|', $types); } if (substr($type, -2) === '[]') { $subtype = substr($type, 0, -2); ...
csn
Get the number of seconds the script should wait after each getUpdates request. @return int
public function getLoopInterval(): int { $interval_time = $this->params->getScriptParam('i'); if (null === $interval_time || (\is_string($interval_time) && '' === trim($interval_time))) { return 2; } // Minimum interval is 1 second. return max(1, (int) $interval...
csn
Creates all prepared statemenst
protected function createPreparedStatements() { if ($this->prepared_statements_created == false) { $this->preparedInsertStatement = $this->PDO->prepare("INSERT INTO document_infos (document_info) VALUES (?);"); $this->preparedSelectStatement = $this->PDO->prepare("SELECT * FROM document_infos...
csn
Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive lis...
def play_song(self, song, tempo=120, delay=0.05): """ Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and...
csn
1 2 5 10 25 50 100 250 500 etc
function quantizedNumber(i) { var adjust = [1, 2.5, 5]; return Math.floor(Math.pow(10, Math.floor(i/3)) * adjust[i % 3]); }
csn
Read annotation file. Store annotation data in a list of namedtuples.
def init_associations(self, fin_anno, taxids=None): """Read annotation file. Store annotation data in a list of namedtuples.""" nts = [] if fin_anno is None: return nts tic = timeit.default_timer() lnum = -1 line = "\t"*len(self.flds) try: ...
csn
Generate Basket string in the older non-XML format This is called if "useOldBasketFormat" is set to true in the gateway config @return string Basket field in format of: 1:Item:2:10.00:0.00:10.00:20.00 [number of lines]:[item name]:[quantity]:[unit cost]:[item tax]:[item total]:[line total]
protected function getItemDataNonXML() { $result = ''; $items = $this->getItems(); $count = 0; foreach ($items as $basketItem) { $description = $this->filterNonXmlItemName($basketItem->getName()); $vat = '0.00'; if ($basketItem instanceof ExtendI...
csn
// Convert_autoscaling_MetricStatus_To_v2beta1_MetricStatus is an autogenerated conversion function.
func Convert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in *autoscaling.MetricStatus, out *v2beta1.MetricStatus, s conversion.Scope) error { return autoConvert_autoscaling_MetricStatus_To_v2beta1_MetricStatus(in, out, s) }
csn
Convert type to human-readable form @param integer $type @return string
static public function getReadableType( $type ) { switch ( $type ) { case self::TYPE_GOOGLE: return 'google'; case self::TYPE_FACEBOOK: return 'facebook'; case self::TYPE_YAHOO: return 'yahoo'; case self::TYPE_TWITTER: return 'twitter'; ...
csn
Parses CLI options. @param args CLI args @return Alluxio-FUSE configuration options
private static AlluxioFuseOptions parseOptions(String[] args, AlluxioConfiguration alluxioConf) { final Options opts = new Options(); final Option mntPoint = Option.builder("m") .hasArg() .required(true) .longOpt("mount-point") .desc("Desired local mount point for alluxio-fuse.")...
csn
Get pid informations. @public @param {Number|Number[]|String|String[]} pids A pid or a list of pids. @param {Object} [options={}] Options object @param {Function} [callback=undefined] Called when the statistics are ready. If not provided a promise is returned instead. @returns {Promise.<Object>} Only when the callb...
function pidusage (pids, options, callback) { if (typeof options === 'function') { callback = options options = {} } if (options === undefined) { options = {} } if (typeof callback === 'function') { stats(pids, options, callback) return } return new Promise(function (resolve, reject...
csn
Return a random number of entities from this collection. If n = 1 you will recieve a entity otherwise you will get a container @param int @param bool Force a container to always be returned @param bool Remove the items from the container as they are returned @return ContainerableInterface|Container
public function randomGet( $n = null, $returnContainer = false, $removeFromContainer = false ) { $n = $n === null ? 1 : (int) $n; // anything to give? if( 0 === $containerSize = $this->count() ) { if( $returnContainer or $n > 1 ) { return $this->newContainer(); ...
csn
Load's and return's the varchar attributes for the passed entity ID. @param integer $entityId The entity ID of the attributes @return array The varchar attributes
public function findAllByEntityId($entityId) { // prepare the params $params = array(ParamNames::ENTITY_ID => $entityId); // load and return the customer varchar attributes with the passed entity ID $this->customerVarcharsStmt->execute($params); return $this->customerVarcha...
csn
Get the table headings. @param EnvironmentInterface $environment The environment. @return array
private function getTableHead(EnvironmentInterface $environment) { $tableHead = []; $definition = $environment->getDataDefinition(); $properties = $definition->getPropertiesDefinition(); $formatter = $this->getViewSection($definition)->getListingConfig()->getLabelFormatter($definit...
csn
Adds sort field parameters into given search object. @param Search $search @param array $sortField
private function addFieldToSort(Search $search, $sortField) { $search->addSort( new FieldSort( $sortField['field'], $sortField['order'], isset($sortField['mode']) ? ['mode' => $sortField['mode']] : [] ) ); }
csn
Take a function that reports its result using a callback and return a Promise that listenes for this callback. The function must accept a callback as its first parameter. The callback must take two arguments: - success : True or False - result : The result of the operation if success is True or th...
def makeCallbackPromise(function, *args, **kwargs): """ Take a function that reports its result using a callback and return a Promise that listenes for this callback. The function must accept a callback as its first parameter. The callback must take two arguments: - success : True or False ...
csn
// ZRevRange gets the data reversed.
func (db *DB) ZRevRange(key []byte, start int, stop int) ([]ScorePair, error) { return db.ZRangeGeneric(key, start, stop, true) }
csn
Recompute the value as the string at the node.
def visit_Str(self, node: ast.Str) -> str: """Recompute the value as the string at the node.""" result = node.s self.recomputed_values[node] = result return result
csn
Initializes streams and timeout settings.
@Override public void sessionOpened(IoSession session) { // Set timeouts session.getConfig().setWriteTimeout(writeTimeout); session.getConfig().setIdleTime(IdleStatus.READER_IDLE, readTimeout); // Create streams InputStream in = new IoSessionInputStream(); OutputStre...
csn
check whether a transfer is stopped or is being stopped
def is_stopped(self, is_stopping=True): ''' check whether a transfer is stopped or is being stopped ''' if is_stopping: return self._is_stopped or self._is_stopping return self._is_stopped
csn
Get the header values for the given header name, if it exists. There can be more than one value for a given header name. @param name the name of the header to get @return the values of the given header name
public List<String> getHeader(String name) { if (headers == null) { return null; } return headers.values(name); }
csn
Batch normalization on `input_layer` without tf.layers.
def _batch_norm_without_layers(self, input_layer, decay, use_scale, epsilon): """Batch normalization on `input_layer` without tf.layers.""" shape = input_layer.shape num_channels = shape[3] if self.data_format == "NHWC" else shape[1] beta = self.get_var...
csn
Call a command internally. This function is typically called by some other commands or "handle_natural_language" when handling NLPResult object. Note: If disable_interaction is not True, after calling this function, any previous command session will be overridden, even if the command being called ...
async def call_command(bot: NoneBot, ctx: Context_T, name: Union[str, CommandName_T], *, current_arg: str = '', args: Optional[CommandArgs_T] = None, check_perm: bool = True, disable_interaction: bool = Fa...
csn
// Sign mock signing
func (m *MockCryptoSuite) Sign(k core.Key, digest []byte, opts core.SignerOpts) (signature []byte, err error) { return []byte("testSignature"), nil }
csn
Get a random gender. Get a random title of gender, code for the representation of human sexes is an international standard that defines a representation of human sexes through a language-neutral single-digit code or symbol of gender. :param iso5218: Codes for the re...
def gender(self, iso5218: bool = False, symbol: bool = False) -> Union[str, int]: """Get a random gender. Get a random title of gender, code for the representation of human sexes is an international standard that defines a representation of human sexes through a language-...
csn
Creates a stream for download via multipart stream to S3. @params {S3} s3 @params {Object} s3Params @params {Object} options
function S3StreamDownload (s3, s3Params, options) { var downloader = new Downloader(s3, s3Params, options); return new DownloadStream(downloader); }
csn
Delete entity value. Delete a value from an entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. @param deleteValueOptions the {@link DeleteValueOptions} containing the options for the call @return a {@link ServiceCall} with a response type of Void
public ServiceCall<Void> deleteValue(DeleteValueOptions deleteValueOptions) { Validator.notNull(deleteValueOptions, "deleteValueOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "entities", "values" }; String[] pathParameters = { deleteValueOptions.workspaceId(), deleteValueOptions.entity...
csn
Gets a full URL to an icon for a particular application. @param \Package $pkg @return string URL to the package's icon
public function getPackageIconURL($pkg) { if ($pkg && file_exists($pkg->getPackagePath() . '/' . FILENAME_BLOCK_ICON)) { return $this->getPackageURL($pkg) . '/' . FILENAME_BLOCK_ICON; } else { return PACKAGE_GENERIC_ICON; } }
csn
Write p2sh to the given buffer. @param {String} scripthash For example multisig address @param {Buffer} buffer @param {Number} offset @returns {Number} new offset
function writeScriptPayToScriptHash(scripthash, buffer, offset) { offset = buffer.writeUInt8(23, offset); //Script length offset = buffer.writeUInt8(OPS.OP_HASH160, offset); //Write previous output address offset = buffer.writeUInt8(20, offset); //Address length offset += Buffer.from(base58check.dec...
csn
Map DN values from ANY type to DN-specific internal format. @param array ref $root @param string $path @param object $asn1 @access private
function _mapInDNs(&$root, $path, $asn1) { $dns = &$this->_subArray($root, $path); if (is_array($dns)) { for ($i = 0; $i < count($dns); $i++) { for ($j = 0; $j < count($dns[$i]); $j++) { $type = $dns[$i][$j]['type']; $value = &$dns...
csn
// Validate validates the subnet, checking the CIDR, and VLANTag, if present.
func (s *Subnet) Validate() error { if s.doc.CIDR != "" { _, _, err := net.ParseCIDR(s.doc.CIDR) if err != nil { return errors.Trace(err) } } else { return errors.Errorf("missing CIDR") } if s.doc.VLANTag < 0 || s.doc.VLANTag > 4094 { return errors.Errorf("invalid VLAN tag %d: must be between 0 and 40...
csn
Shifts only the present stream so that next will return the value for currentRow @param currentRow @throws IOException
protected void seekToPresentRow(long currentRow) throws IOException { if (currentRow != previousPresentRow + 1) { long rowInStripe = currentRow - rowBaseInStripe - 1; int rowIndexEntry = computeRowIndexEntry(currentRow); if (rowIndexEntry != computeRowIndexEntry(previousPresentRow) || cu...
csn
Joins path segments to one full path. @param string[] ...$paths @return string
public static function join (...$paths) : string { $normalized = []; foreach ($paths as $index => $path) { if (0 !== $index) { $path = \ltrim($path, "/"); } if ($index !== \count($paths) - 1) { $pat...
csn
Adds the given input map to the end of the node's list of input maps, so that an event will be pattern-matched against all other input maps currently "installed" in the node before being pattern-matched against the given input map.
public static void addFallbackInputMap(Node node, InputMap<?> im) { // getInputMap calls init, so can use unsafe setter setInputMapUnsafe(node, InputMap.sequence(getInputMap(node), im)); }
csn
Get value of Detect64BitPortabilityProblems property. @param compilerConfig compiler configuration. @return value of Detect64BitPortabilityProblems property.
private String getDetect64BitPortabilityProblems(final CommandLineCompilerConfiguration compilerConfig) { String warn64 = null; final String[] args = compilerConfig.getPreArguments(); for (final String arg : args) { if ("/Wp64".equals(arg)) { warn64 = this.trueLiteral; } } return...
csn
// tagsToMapRAM turns the list of RAM tags into a map.
func tagsToMapRAM(ts []*ram.Tag) map[string]string { result := make(map[string]string) for _, t := range ts { if !tagIgnoredRAM(t) { result[aws.StringValue(t.Key)] = aws.StringValue(t.Value) } } return result }
csn
Returns the path for a certain pid The result is cached internally for the session, thus you can call this function as much as you like without performance problems. @param int $pid The page id for which to get the path @return mixed[] The path.
public function recPath($pid) { if (!isset($this->recPath_cache[$pid])) { $this->recPath_cache[$pid] = BackendUtility::getRecordPath($pid, $this->perms_clause, 20); } return $this->recPath_cache[$pid]; }
csn
CPU burst max running time - self.runtime_cfg.inner_burst_op_count
def command_inner_burst_op_count(self, event=None): """ CPU burst max running time - self.runtime_cfg.inner_burst_op_count """ try: inner_burst_op_count = self.inner_burst_op_count_var.get() except ValueError: inner_burst_op_count = self.runtime_cfg.inner_burst_op_count ...
csn
compare coverage of two Cobertura reports
def diff( cobertura_file1, cobertura_file2, color, format, output, source1, source2, source_prefix1, source_prefix2, source): """compare coverage of two Cobertura reports""" cobertura1 = Cobertura( cobertura_file1, source=source1, source_prefix=source_prefix1 ...
csn
Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfault if the name was not *originally* creat...
def display_as(self, name_type): """ Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfau...
csn
Get the request from the container. @return \Dingo\Api\Http\Request
public function getRequest() { $request = $this->container['request']; if ($request instanceof IlluminateRequest && ! $request instanceof Request) { $request = (new Request())->createFromIlluminate($request); } return $request; }
csn
Estimate new centers, weights, and concentrations from Parameters ---------- posterior : array, [n_centers, n_examples] The posterior matrix from the expectation step. force_weights : None or array, [n_centers, ] If None is passed, will estimate weights. If an array is passed, ...
def _maximization(X, posterior, force_weights=None): """Estimate new centers, weights, and concentrations from Parameters ---------- posterior : array, [n_centers, n_examples] The posterior matrix from the expectation step. force_weights : None or array, [n_centers, ] If None is pa...
csn
creates precicate for given constraint @param mixed|\bovigo\assert\predicate\Predicate|\PHPUnit\Framework\Constraint\Constraint $constraint @return \bovigo\assert\predicate\Predicate
private function predicateFor($constraint): \bovigo\assert\predicate\Predicate { if ($constraint instanceof \PHPUnit\Framework\Constraint\Constraint) { return new \bovigo\assert\phpunit\ConstraintAdapter($constraint); } if ($constraint instanceof \bovigo\assert\predicate\Predica...
csn
Gets API key @param string $apiKeyIdentifier API key identifier (authentication scheme) @return string API key or token
public function getApiKey($apiKeyIdentifier) { return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; }
csn
Is a country an E1 nation? @param string $country Country to check @return boolean True if E1
public static function is_e1nation($country) { $e1nation = false; if ($country) { if (!($gdb = self::getGeoDBO())) { return $e1nation; } $gdb->setQuery("SELECT COUNT(*) FROM countrygroup WHERE LOWER(countrycode) = LOWER(" . $gdb->quote($country) . ") AND countrygroup = 'E1'"); $c = $gdb->load...
csn
Synchronously writes the new checkpoints to ZooKeeper and asynchronously removes older ones. @param checkpoint Completed checkpoint to add.
@Override public void addCheckpoint(final CompletedCheckpoint checkpoint) throws Exception { checkNotNull(checkpoint, "Checkpoint"); final String path = checkpointIdToPath(checkpoint.getCheckpointID()); // Now add the new one. If it fails, we don't want to loose existing data. checkpointsInZooKeeper.addAndLo...
csn
Process the disulfide bond info provided by an SSBOND record <pre> COLUMNS DATA TYPE FIELD DEFINITION ------------------------------------------------------------------- 1 - 6 Record name "SSBOND" 8 - 10 Integer serNum Serial number. 12 - 14 LString(3) ...
private void pdb_SSBOND_Handler(String line){ if (params.isHeaderOnly()) return; if (line.length()<36) { logger.info("SSBOND line has length under 36. Ignoring it."); return; } String chain1 = line.substring(15,16); String seqNum1 = line.substring(17,21).trim(); String icode1 = line.s...
csn
Update stats to a server. The method builds two lists: names and values and calls the export method to export the stats. Note: this class can be overwrite (for example in CSV and Graph).
def update(self, stats): """Update stats to a server. The method builds two lists: names and values and calls the export method to export the stats. Note: this class can be overwrite (for example in CSV and Graph). """ if not self.export_enable: return False...
csn
Get the Calligraphy Activity Fragment Instance to allow callbacks for when views are created. @param activity The activity the original that the ContextWrapper was attached too. @return Interface allowing you to call onActivityViewCreated
static CalligraphyActivityFactory get(Activity activity) { if (!(activity.getLayoutInflater() instanceof CalligraphyLayoutInflater)) { throw new RuntimeException("This activity does not wrap the Base Context! See CalligraphyContextWrapper.wrap(Context)"); } return (CalligraphyActivit...
csn
Send an slack message with the data
def returner(ret): ''' Send an slack message with the data ''' _options = _get_options(ret) channel = _options.get('channel') username = _options.get('username') as_user = _options.get('as_user') api_key = _options.get('api_key') changes = _options.get('changes') only_show_fail...
csn
Prepares controller for execution. This method is final, use doPrepare for defining actions in prepare step. @param PageRequest $request
final public function prepare(PageRequest $request) { $this->request = $request; $this->response = $this->createBlockResponse($request); $this->properties = $request->getBlockPropertySet() ->getBlockPropertySet($this->block); try { $this->doPrepare(); } catch (\Exception $e) { $this->exception ...
csn
Get position stats instance for a slot and optional variant no. @param int $slot The slot no. @param int|null $variant if provided then we want the object which stores a variant of a position's stats. @return calculated|calculated_for_subquestion An instance of the class storing the calculated position stats. @throws...
public function for_slot($slot, $variant = null) { if ($variant === null) { if (!isset($this->questionstats[$slot])) { throw new \coding_exception('Reference to unknown slot ' . $slot); } else { return $this->questionstats[$slot]; } } e...
csn
Close the stream. Assumes stream has 'close' method.
def close(self): """ Close the stream. Assumes stream has 'close' method. """ self.out_stream.close() # If we're asked to write in place, substitute the named # temporary file for the current file if self.in_place: shutil.move(self.temp_file.name, self...
csn
Set the date that this content becomes available for playback. @param \Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $availableDate
public function setAvailableDate(\Lullabot\Mpx\DataService\DateTime\DateTimeFormatInterface $availableDate) { $this->availableDate = $availableDate; }
csn
TEAL interface for the `acsccd` function.
def run(configobj=None): """ TEAL interface for the `acsccd` function. """ acsccd(configobj['input'], exec_path=configobj['exec_path'], time_stamps=configobj['time_stamps'], verbose=configobj['verbose'], quiet=configobj['quiet'] #, #dqicorr=config...
csn
Store uploaded file by configured path pattern and fill data to this model. @param Symfony\Component\HttpFoundation\File\UploadedFile $file @return Illuminate\Database\Eloquent\Model
public function upload(UploadedFile $file) { self::$generic_file->moveUploadedFile(new File($file, $file->getClientOriginalName()), null, $this); return $this; }
csn
Combine predictions with the optimal weights to minimize RMSE. Args: es (list of float): RMSEs of predictions ps (list of np.array): predictions e0 (float): RMSE of all zero prediction l (float): lambda as in the ridge regression Returns: Ensemble prediction (np.array) ...
def netflix(es, ps, e0, l=.0001): """ Combine predictions with the optimal weights to minimize RMSE. Args: es (list of float): RMSEs of predictions ps (list of np.array): predictions e0 (float): RMSE of all zero prediction l (float): lambda as in the ridge regression Re...
csn
Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type.
def GetEventTypeString(self, event_type): """Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type. """ if 0 <= event_type < len(self._EVENT_TYPES): return self._EVENT_TYPES[event_type] return 'Unk...
csn
// Collect returns the metrics with values
func (c Metrics) Collect(ch chan<- prometheus.Metric) { ch <- prometheus.MustNewConstMetric( c.TotalPushCount, prometheus.GaugeValue, float64(StatStorage.GetTotalCount()), ) ch <- prometheus.MustNewConstMetric( c.IosSuccess, prometheus.GaugeValue, float64(StatStorage.GetIosSuccess()), ) ch <- prometheu...
csn
Return the sum along diagonals of the array. If 2-D array, computes the summation along its diagonal with the given offset, i.e., sum of `a[i,i+offset]`. If more than 2-D array, the diagonal is determined from the axes specified by axis argument. The default is axis=[-2,-1]. @param offset [Integer] (optional, def...
def trace(offset=nil,axis=nil,nan:false) diagonal(offset,axis).sum(nan:nan,axis:-1) end
csn
List all cluster.
def get(self, name=None, provider='AwsEKS', print_output=True): """List all cluster. """ # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name) self.kubeconf.open() if name is None: clusters = self.kubeconf.get_clusters...
csn
Determines whether the cache file metadata header is valid. Args: cache_file_metadata_header (firefox_cache2_file_metadata_header): cache file metadata header. Returns: bool: True if the cache file metadata header is valid.
def _ValidateCacheFileMetadataHeader(self, cache_file_metadata_header): """Determines whether the cache file metadata header is valid. Args: cache_file_metadata_header (firefox_cache2_file_metadata_header): cache file metadata header. Returns: bool: True if the cache file metadata he...
csn
Set current thread's logging context to specified `values`
def set_threadlocal(self, **values): """Set current thread's logging context to specified `values`""" with self._lock: self._ensure_threadlocal() self._tpayload.context = values
csn
A generator which yields a list of all valid keys starting at the given `start` offset. If `start` is `None`, we will start from the root of the tree.
def get_all_keys(self, start=None): """ A generator which yields a list of all valid keys starting at the given `start` offset. If `start` is `None`, we will start from the root of the tree. """ s = self.stream if not start: start = HEADER_SIZE + self...
csn
Create new list. It will fail to create a new list if the given name already exists. @param string $name List name @return bool
protected function _createList(string $name) : bool { /** * @var \CsvMigrations\Model\Table\DblistsTable */ $table = $this->loadModel('CsvMigrations.Dblists'); if ($table->exists(['name' => $name])) { return false; } $entity = $table->newEntity...
csn
Save results to a numpy array file format.
def save_to_npy_file(self, parameter_space, result_parsing_function, filename, runs): """ Save results to a numpy array file format. """ np.save(filename, self.get_results_as_numpy_array( parameter_space, result_parsing_functi...
csn
Retrieve a chunk, and return the full response.
def __GetChunk(self, start, end, additional_headers=None): """Retrieve a chunk, and return the full response.""" self.EnsureInitialized() request = http_wrapper.Request(url=self.url) self.__SetRangeHeader(request, start, end=end) if additional_headers is not None: req...
csn
Auto-assign and return the total amount for this tax.
def compute_amount(self): """Auto-assign and return the total amount for this tax.""" self.amount = self.base_amount * self.aliquot / 100 return self.amount
csn
// Wrap a normal datapoint to give it dimensions about the current hostname
func Wrap(dp *datapoint.Datapoint) *datapoint.Datapoint { hostname, err := osXXXHostname() if dp.Dimensions == nil { dp.Dimensions = make(map[string]string, 2) } if err != nil { hostname = "unknown" } dp.Dimensions["host"] = hostname dp.Dimensions["source"] = "proxy" return dp }
csn
Shutdown the AIO library.
public static void shutdown() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "shutdown"); } synchronized (oneAtATime) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "have lock"); // runn...
csn
save playback with more options @param opts @return @throws PiliException
public String save(SaveOptions opts) throws PiliException { String path = baseUrl + "/saveas"; String json = gson.toJson(opts); try { String resp = cli.callWithJson(path, json); SaveRet ret = gson.fromJson(resp, SaveRet.class); return ret.fname; } cat...
csn
Sets an access token and adds it to `AuthMiddleware` so the application can make authenticated requests. @param AccessToken $token @return void @codeCoverageIgnore
public function setAccessToken(AccessToken $token) { $this->container->get('config') ->set('access_token', json_encode($token->jsonSerialize())); }
csn
Set the position on the x-axis. @param int $x A position on the x-axis. @throws \InvalidArgumentException If $x is nto an integer value.
public function setX($x) { if (is_int($x)) { $this->x = $x; } else { $msg = "The X argument must be an integer value, '" . gettype($x) . "' given."; throw new InvalidArgumentException($msg); } }
csn
Write version file into the storage directory. The version file should always be written last. Missing or corrupted version file indicates that the checkpoint is not valid. @param sd storage directory @throws IOException
@Override // Storage protected void setFields(Properties props, StorageDirectory sd) throws IOException { super.setFields(props, sd); boolean uState = getDistributedUpgradeState(); int uVersion = getDistributedUpgradeVersion(); if (uState && uVersion != getLayoutVersion()) { props.setPro...
csn
calls parseSubfields but makes sure only one subfield is present. @param string $subfieldspec A subfieldspec @return array An Array of subfieldspec
public function subfieldToArray($subfieldspec) { if (!$_sf = $this->parseSubfields($subfieldspec)) { throw new InvalidMARCspecException( InvalidMARCspecException::SF. InvalidMARCspecException::UNKNOWN, $subfieldspec ); } ...
csn
Return a random RGB color using datatype specified. Parameters ---------- dtype: numpy dtype of result Returns ---------- color: (4,) dtype, random color that looks OK
def random_color(dtype=np.uint8): """ Return a random RGB color using datatype specified. Parameters ---------- dtype: numpy dtype of result Returns ---------- color: (4,) dtype, random color that looks OK """ hue = np.random.random() + .61803 hue %= 1.0 color = np.arra...
csn
// Retry db queries in case postgres has been deployed
func (c *context) execWithRetries(query string, args ...interface{}) error { return execAttempts.Run(func() error { return c.db.Exec(query, args...) }) }
csn
Send the txnId of the snapshot that was picked to restore from to the other hosts. If there was no snapshot to restore from, send 0. @param txnId
private void sendSnapshotTxnId(SnapshotInfo toRestore) { long txnId = toRestore != null ? toRestore.txnId : 0; String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}"; LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes"); try { m_...
csn
// Mask returns a new resource list that only has the values with the specified names
func Mask(resources corev1.ResourceList, names []corev1.ResourceName) corev1.ResourceList { nameSet := ToSet(names) result := corev1.ResourceList{} for key, value := range resources { if nameSet.Has(string(key)) { result[key] = *value.Copy() } } return result }
csn
// Waits synchronously waits for the container to shutdown or terminate.
func (container *container) Wait() error { err := container.system.Wait() if err == nil { err = container.system.ExitError() } return convertSystemError(err, container) }
csn
Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions.
int spread(int x) { x = ((x >>> 16) ^ x) * 0x45d9f3b; x = ((x >>> 16) ^ x) * 0x45d9f3b; return (x >>> 16) ^ x; }
csn
// Set the current count of the bar. It returns ErrMaxCurrentReached when trying n exceeds the total value. This is atomic operation and concurancy safe.
func (b *Bar) Set(n int) error { b.mtx.Lock() defer b.mtx.Unlock() if n > b.Total { return ErrMaxCurrentReached } b.current = n return nil }
csn
// HeightRange returns a range of block hashes for the given start and end // heights. It is inclusive of the start height and exclusive of the end // height. The end height will be limited to the current main chain height. // // This function is safe for concurrent access.
func (b *BlockChain) HeightRange(startHeight, endHeight int32) ([]chainhash.Hash, error) { // Ensure requested heights are sane. if startHeight < 0 { return nil, fmt.Errorf("start height of fetch range must not "+ "be less than zero - got %d", startHeight) } if endHeight < startHeight { return nil, fmt.Error...
csn
Initialize all steps in this recipe using their parameters. Args: variables (dict): A dictionary of global variable definitions that may be used to replace or augment the parameters given to each step. Returns: list of RecipeActionObject like ins...
def prepare(self, variables): """Initialize all steps in this recipe using their parameters. Args: variables (dict): A dictionary of global variable definitions that may be used to replace or augment the parameters given to each step. Returns: ...
csn
Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of.
def respond_list_directory(self, dir_path, query=None): """ Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of. """ del query try: dir_contents = os.listdir(dir_path) except os.error: self...
csn
Convert a string to a URL and fallback to classpath resource, if not convertible. @param s The string to convert. @return The URL.
public static URL asUrlOrResource(String s) { if (Strings.isNullOrEmpty(s)) { return null; } try { return new URL(s); } catch (MalformedURLException e) { //If its not a valid URL try to treat it as a local resource. return findConfigResour...
csn
Returns the path extensions from environment or a default
def get_pathext(default_pathext=None): """Returns the path extensions from environment or a default""" if default_pathext is None: default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ]) pathext = os.environ.get('PATHEXT', default_pathext) return pathext
csn
recursively find the references
private void findReferencesBean( Object base, Class<?> declaredClass, Map<Object, Integer> objects, SerIterator parentIterator) { if (base == null) { return; } // has this object been seen before, if so no need to check it again ...
csn
Inverts a list of ordered BMP characters and ranges
function invertBmp(range) { var output = ''; var lastEnd = -1; XRegExp.forEach( range, /(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/, function(m) { var start = charCode(m[1]); if (start > (lastEnd + 1)) { ...
csn
Adds a processor to the pipeline of processors.
public void addProcessor(ItemProcessor processor) { if (processors == null) { processors = new ArrayList<>(); } processors.add(processor); }
csn
Returns the first Long value found for this tag @param name Tag name @return First long value found
public Long getFirstLongValue(String name) { Object objs[] = getValues(name); for (Object obj : objs) { if (obj instanceof Long) { return (Long) obj; } } return null; }
csn
Efficient copy of file in case of local file system. @param fileUrl source file @return path of target file @throws IOException if problems during copy @throws PluginException in case of other problems
protected Path copyLocalFile(URL fileUrl) throws IOException, PluginException { Path destination = Files.createTempDirectory("pf4j-update-downloader"); destination.toFile().deleteOnExit(); try { Path fromFile = Paths.get(fileUrl.toURI()); String path = fileUrl.getPath();...
csn
Set the widget's attachment grouping. Prevents the relationship from deleting all non related attachments. @param string $group The group identifier. @throws InvalidArgumentException If the group key is invalid. @return self
public function setGroup($group) { if (!is_string($group) && $group !== null) { throw new InvalidArgumentException(sprintf( 'Attachment group must be string, received %s', is_object($group) ? get_class($group) : gettype($group) )); } $...
csn
Retrieve resource name. @return string
public function getResourceName() { return $this->name !== null ? $this->name : str_replace('_', '-', (new Inflector())->tableize($this->getManager()->getName())); }
csn
Return a re.match object if an empty comment was found on line.
def _match_space_at_line(line): """Return a re.match object if an empty comment was found on line.""" regex = re.compile(r"^{0}$".format(_MDL_COMMENT)) return regex.match(line)
csn