comment
stringlengths
16
255
code
stringlengths
52
3.87M
// eq returns whether this and that are equal.
func eq(this, that *MyStruct) bool { return (this == nil && that == nil) || this != nil && that != nil && this.Int64 == that.Int64 && ((this.StringPtr == nil && that.StringPtr == nil) || (this.StringPtr != nil && that.StringPtr != nil && *(this.StringPtr) == *(that.StringPtr))) }
akede@users - 1.7.2 patch Files readonly
public void setDataReadOnly(boolean value) { // Changing the Read-Only mode for the table is only allowed if the // the database can realize it. if (!value && database.isFilesReadOnly() && isFileBased()) { throw Error.error(ErrorCode.DATA_IS_READONLY); } isReadOnly = value; }
Send an ON message to device group.
def on(self): """""" on_command = ExtendedSend(self._address, COMMAND_LIGHT_ON_0X11_NONE, self._udata, cmd2=0xff) on_command.set_checksum() self._send_method(on_command, self._on_message_received)
Clean the config params from unnecessary params no to make the notification too heavy. @return array
private function cleanConfigParams() { /** * Add the params you want to be removed from the push notification */ $paramsToBeRemoved = ['apiKey']; return array_filter($this->config, function ($key) use ($paramsToBeRemoved) { return !in_array($key, $paramsToBeRemoved); }, ARRAY_FILTER_USE_KEY); }
Fetch the file names with status from the commit. @param string $commitId The commit identifier. @param GitRepository $git The git repository. @return string
private function fetchNameStatusFromCommit($commitId, GitRepository $git) { $arguments = [ $git->getConfig()->getGitExecutablePath(), 'show', $commitId, '-M', '--name-status', '--format=' ]; // git show $commitId -M --name-status --format='' return $this->runCustomGit($arguments, $git); }
Returns the declared return type of a method (for PHP < 7.0 this will always return null) @param string $className @param string $methodName @return string The declared return type of the method or null if none was declared
public function getMethodDeclaredReturnType($className, $methodName) { $className = $this->prepareClassReflectionForUsage($className); if (!isset($this->classReflectionData[$className][self::DATA_CLASS_METHODS][$methodName][self::DATA_METHOD_DECLARED_RETURN_TYPE])) { return null; } return $this->classReflectionData[$className][self::DATA_CLASS_METHODS][$methodName][self::DATA_METHOD_DECLARED_RETURN_TYPE]; }
Marshall the given parameter object.
public void marshall(AssociateCreatedArtifactRequest associateCreatedArtifactRequest, ProtocolMarshaller protocolMarshaller) { if (associateCreatedArtifactRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(associateCreatedArtifactRequest.getProgressUpdateStream(), PROGRESSUPDATESTREAM_BINDING); protocolMarshaller.marshall(associateCreatedArtifactRequest.getMigrationTaskName(), MIGRATIONTASKNAME_BINDING); protocolMarshaller.marshall(associateCreatedArtifactRequest.getCreatedArtifact(), CREATEDARTIFACT_BINDING); protocolMarshaller.marshall(associateCreatedArtifactRequest.getDryRun(), DRYRUN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Store a new user. @return \Illuminate\Http\Response
public function store() { $password = Str::random(); $input = array_merge(Binput::only(['first_name', 'last_name', 'email']), [ 'password' => $password, 'activated' => true, 'activated_at' => new DateTime(), ]); $rules = UserRepository::rules(array_keys($input)); $rules['password'] = 'required|min:6'; $val = UserRepository::validate($input, $rules, true); if ($val->fails()) { return Redirect::route('users.create')->withInput()->withErrors($val->errors()); } try { $user = UserRepository::create($input); $groups = GroupRepository::index(); foreach ($groups as $group) { if (Binput::get('group_'.$group->id) === 'on') { $user->addGroup($group); } } $mail = [ 'url' => URL::to(Config::get('credentials.home', '/')), 'password' => $password, 'email' => $user->getLogin(), 'subject' => Config::get('app.name').' - New Account Information', ]; Mail::queue('credentials::emails.newuser', $mail, function ($message) use ($mail) { $message->to($mail['email'])->subject($mail['subject']); }); return Redirect::route('users.show', ['users' => $user->id]) ->with('success', 'The user has been created successfully. Their password has been emailed to them.'); } catch (UserExistsException $e) { return Redirect::route('users.create')->withInput()->withErrors($val->errors()) ->with('error', 'That email address is taken.'); } }
XYZ to RGB conversion.
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs): temp_X = cobj.xyz_x temp_Y = cobj.xyz_y temp_Z = cobj.xyz_z logger.debug(" \- Target RGB space: %s", target_rgb) target_illum = target_rgb.native_illuminant logger.debug(" \- Target native illuminant: %s", target_illum) logger.debug(" \- XYZ color's illuminant: %s", cobj.illuminant) # If the XYZ values were taken with a different reference white than the # native reference white of the target RGB space, a transformation matrix # must be applied. if cobj.illuminant != target_illum: logger.debug(" \* Applying transformation from %s to %s ", cobj.illuminant, target_illum) # Get the adjusted XYZ values, adapted for the target illuminant. temp_X, temp_Y, temp_Z = apply_chromatic_adaptation( temp_X, temp_Y, temp_Z, orig_illum=cobj.illuminant, targ_illum=target_illum) logger.debug(" \* New values: %.3f, %.3f, %.3f", temp_X, temp_Y, temp_Z) # Apply an RGB working space matrix to the XYZ values (matrix mul). rgb_r, rgb_g, rgb_b = apply_RGB_matrix( temp_X, temp_Y, temp_Z, rgb_type=target_rgb, convtype="xyz_to_rgb") # v linear_channels = dict(r=rgb_r, g=rgb_g, b=rgb_b) # V nonlinear_channels = {} if target_rgb == sRGBColor: for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v <= 0.0031308: nonlinear_channels[channel] = v * 12.92 else: nonlinear_channels[channel] = 1.055 * math.pow(v, 1 / 2.4) - 0.055 elif target_rgb == BT2020Color: if kwargs.get('is_12_bits_system'): a, b = 1.0993, 0.0181 else: a, b = 1.099, 0.018 for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v < b: nonlinear_channels[channel] = v * 4.5 else: nonlinear_channels[channel] = a * math.pow(v, 0.45) - (a - 1) else: # If it's not sRGB... for channel in ['r', 'g', 'b']: v = linear_channels[channel] nonlinear_channels[channel] = math.pow(v, 1 / target_rgb.rgb_gamma) return target_rgb( nonlinear_channels['r'], nonlinear_channels['g'], nonlinear_channels['b'])
Encode a string for use in the URL @param toEncode @return
private static String encoder(final String toEncode) { try { return URLEncoder.encode(toEncode, URL_ENCODING); } catch (UnsupportedEncodingException ex) { LOG.warn("Failed to encode: {}", ex.getMessage(), ex); return ""; } }
Handle request. @throws \EntWeChat\Core\Exceptions\RuntimeException @throws \EntWeChat\Server\BadRequestException @return array
protected function handleRequest() { $message = $this->getMessage(); $response = $this->handleMessage($message); return [ 'to' => $message['FromUserName'], 'from' => $message['ToUserName'], 'response' => $response, ]; }
Closes all tabs of the states editor for a specific sm_id
def close_pages_for_specific_sm_id(self, sm_id): """""" states_to_be_closed = [] for state_identifier in self.tabs: state_m = self.tabs[state_identifier]["state_m"] if state_m.state.get_state_machine().state_machine_id == sm_id: states_to_be_closed.append(state_identifier) for state_identifier in states_to_be_closed: self.close_page(state_identifier, delete=False)
Send to data output back to editor's associated element.
function updateEditorElement() { var element = this.element; // Some editor creation mode will not have the // associated element. if ( element && this.elementMode != CKEDITOR.ELEMENT_MODE_APPENDTO ) { var data = this.getData(); if ( this.config.htmlEncodeOutput ) data = CKEDITOR.tools.htmlEncode( data ); if ( element.is( 'textarea' ) ) element.setValue( data ); else element.setHtml( data ); return true; } return false; }
Removes a task from a taskType queue @param taskType the taskType to identify the queue @param taskId the id of the task to be removed
public void removeTaskFromQueue(String taskType, String taskId) { Preconditions.checkArgument(StringUtils.isNotBlank(taskType), "Task type cannot be blank"); Preconditions.checkArgument(StringUtils.isNotBlank(taskId), "Task id cannot be blank"); delete("tasks/queue/{taskType}/{taskId}", taskType, taskId); }
@param array $components @param array $keys @return null|string
protected function guessBestComponent(array $components, array $keys) { foreach ($keys as $key) { if (isset($components[$key]) && !empty($components[$key])) { return $components[$key]; } } return null; }
Uninstalls the Docker image associated with a given bug.
def uninstall(self, bug: Bug) -> bool: r = self.__api.post('bugs/{}/uninstall'.format(bug.name)) raise NotImplementedError
// Close closes the alias store.
func (a *Aliases) Close() error { a.mtx.Lock() defer a.mtx.Unlock() return a.db.Close() }
Same as ActiveModel::model but allows you to define the main model in the composition using +:on+. class CoverSongForm < Reform::Form model :song, on: :cover_song
def model(main_model, options={}) super composition_model = options[:on] || main_model # FIXME: this should just delegate to :model as in FB, and the comp would take care of it internally. [:persisted?, :to_key, :to_param].each do |method| define_method method do model[composition_model].send(method) end end self end
Pobranie plików dla podanych obiektów (np. news, categorywidget itp.) @param array $objects @return array indeksowane po nazwie md5
public function getFileList($objects) { //błąd if (!is_array($objects)) { return []; } //zwrot meta plików return (new \Cms\Orm\CmsFileQuery)->whereObject()->equals($objects) ->findPairs('name', 'original'); }
Execute the command.
public function handle() { $config = $this->getConfig(); if (! $config->isForce() && ! $this->confirm('Are you sure you want to scrap the view?')) { $this->line('Alright, nothing happened.'); return; } (new Destroyer($config, $this->getPath()))->destroy(); $this->info('View scrapped successfully.'); }
Invokes the property grid with this element as its target.
public void editProperties() { try { PropertyGrid.create(this, null); } catch (Exception e) { DialogUtil.showError("Displaying property grid: \r\n" + e.toString()); } }
@param $name @param null $value @param null|bool $literal @return mixed @throws KeyDoesNotExistException
public function item($name, $value = null, $literal = null) { $literal = is_null($literal) ? $this->isLiteral() : $literal; func_num_args() < 2 || $this->items[$name] = $value; if (!$literal) { return $this->find($name, $this->items); } isset($this->items[$name]) || $this->throwKeyDoesNotExist($name); return $this->items[$name]; }
Initialize the console
protected function initConsole() { $consoles = $this->setConsoles(); foreach ($consoles as $console) { if ($console[0] == $this->consoleArguments[0]) { Console::add($console[1], $this->consoleArguments); } } Console::dispatch(); }
Remove broken entity references This removes references from nodes to entities which don't exist anymore. @param string $workspaceName @return void @throws NodeException @throws PropertyException @throws SecurityException
public function removeBrokenEntityReferences($workspaceName) { $this->dispatch(self::EVENT_NOTICE, 'Checking for broken entity references ...'); /** @var \Neos\ContentRepository\Domain\Model\Workspace $workspace */ $workspace = $this->workspaceRepository->findByIdentifier($workspaceName); $nodeTypesWithEntityReferences = []; foreach ($this->nodeTypeManager->getNodeTypes() as $nodeType) { /** @var NodeType $nodeType */ foreach (array_keys($nodeType->getProperties()) as $propertyName) { $propertyType = $nodeType->getPropertyType($propertyName); if (strpos($propertyType, '\\') !== false) { if (!isset($nodeTypesWithEntityReferences[$nodeType->getName()])) { $nodeTypesWithEntityReferences[$nodeType->getName()] = []; } $nodeTypesWithEntityReferences[$nodeType->getName()][$propertyName] = $propertyType; } } } $nodesWithBrokenEntityReferences = []; $brokenReferencesCount = 0; foreach ($nodeTypesWithEntityReferences as $nodeTypeName => $properties) { $nodeDatas = $this->nodeDataRepository->findByParentAndNodeTypeRecursively('/', $nodeTypeName, $workspace); foreach ($nodeDatas as $nodeData) { /** @var NodeData $nodeData */ foreach ($properties as $propertyName => $propertyType) { $propertyValue = $nodeData->getProperty($propertyName); $convertedProperty = null; if (is_object($propertyValue)) { $convertedProperty = $propertyValue; } if (is_string($propertyValue) && strlen($propertyValue) === 36) { $convertedProperty = $this->propertyMapper->convert($propertyValue, $propertyType); if ($convertedProperty === null) { $nodesWithBrokenEntityReferences[$nodeData->getIdentifier()][$propertyName] = $nodeData; $this->dispatch(self::EVENT_NOTICE, sprintf('Broken reference in "<i>%s</i>", property "<i>%s</i>" (<i>%s</i>) referring to <i>%s</i>.', $nodeData->getPath(), $nodeData->getIdentifier(), $propertyName, $propertyType, $propertyValue)); $brokenReferencesCount ++; } } if ($convertedProperty instanceof Proxy) { try { $convertedProperty->__load(); } /** @noinspection PhpRedundantCatchClauseInspection */ catch (EntityNotFoundException $e) { $nodesWithBrokenEntityReferences[$nodeData->getIdentifier()][$propertyName] = $nodeData; $this->dispatch(self::EVENT_NOTICE, sprintf('Broken reference in "<i>%s</i>", property "<i>%s</i>" (<i>%s</i>) referring to <i>%s</i>.', $nodeData->getPath(), $nodeData->getIdentifier(), $propertyName, $propertyType, $propertyValue)); $brokenReferencesCount ++; } } } } } if ($brokenReferencesCount === 0) { return; } $taskDescription = sprintf('Remove <i>%d</i> broken entity reference%s.', $brokenReferencesCount, $brokenReferencesCount > 1 ? 's' : ''); $taskClosure = function () use ($nodesWithBrokenEntityReferences) { foreach ($nodesWithBrokenEntityReferences as $nodeIdentifier => $properties) { foreach ($properties as $propertyName => $nodeData) { /** @var NodeData $nodeData */ $nodeData->setProperty($propertyName, null); } } $this->persistenceManager->persistAll(); }; $taskRequiresConfirmation = true; $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure, $taskRequiresConfirmation); }
Check if the IP address is valid and routable Return either True or False
def _valid_ip(ip_address): ''' ''' try: address = ipaddress.IPv4Address(ip_address) except ipaddress.AddressValueError: return False if address.is_unspecified or \ address.is_loopback or \ address.is_link_local or \ address.is_multicast or \ address.is_reserved: return False return True
Find document root @return string @access public
public function getDocumentRootPath() { /** * The absolute pathname of the currently executing script. * Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, * $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. */ if (isset($_SERVER['SCRIPT_FILENAME'])) { $sRealPath = dirname($_SERVER['SCRIPT_FILENAME']); } else { /** * realpath — Returns canonicalized absolute pathname */ $sRealPath = realpath('.') ; } $sRealPath = $this->trimPathTrailingSlashes($sRealPath); /** * The filename of the currently executing script, relative to the document root. * For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar * would be /test.php/foo.bar. */ $sSelfPath = dirname($_SERVER['PHP_SELF']); $sSelfPath = $this->trimPathTrailingSlashes($sSelfPath); return $this->trimPathTrailingSlashes(substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath))); }
Marshall the given parameter object.
public void marshall(PutTelemetryRecordsRequest putTelemetryRecordsRequest, ProtocolMarshaller protocolMarshaller) { if (putTelemetryRecordsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putTelemetryRecordsRequest.getTelemetryRecords(), TELEMETRYRECORDS_BINDING); protocolMarshaller.marshall(putTelemetryRecordsRequest.getEC2InstanceId(), EC2INSTANCEID_BINDING); protocolMarshaller.marshall(putTelemetryRecordsRequest.getHostname(), HOSTNAME_BINDING); protocolMarshaller.marshall(putTelemetryRecordsRequest.getResourceARN(), RESOURCEARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Run build given the following skyuxconfig object. Starts server and resolves when ready.
function prepareBuild(config) { function serve(exitCode) { // Save our exitCode for testing _exitCode = exitCode; // Reset skyuxconfig.json resetConfig(); return server.start('unused-root', tmp) .then(port => browser.get(`https://localhost:${port}/dist/`)); } writeConfig(config); return new Promise((resolve, reject) => { rimrafPromise(path.join(tmp, 'dist')) .then(() => exec(`node`, [cliPath, `build`, `--logFormat`, `none`], cwdOpts)) .then(serve) .then(resolve) .catch(err => reject(err)); }); }
// ResetNetwork resets all properties of a network to its initial (empty) state
func (s *Server) ResetNetwork(w http.ResponseWriter, req *http.Request) { s.network.Reset() w.WriteHeader(http.StatusOK) }
// NewFromFile attempts to create a policy list from the given file. // // TODO: Have policies be created via an API call and stored in REST storage.
func NewFromFile(path string) (PolicyList, error) { // File format is one map per line. This allows easy concatenation of files, // comments in files, and identification of errors by line number. file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() scanner := bufio.NewScanner(file) pl := make(PolicyList, 0) decoder := abac.Codecs.UniversalDecoder() i := 0 unversionedLines := 0 for scanner.Scan() { i++ p := &abac.Policy{} b := scanner.Bytes() // skip comment lines and blank lines trimmed := strings.TrimSpace(string(b)) if len(trimmed) == 0 || strings.HasPrefix(trimmed, "#") { continue } decodedObj, _, err := decoder.Decode(b, nil, nil) if err != nil { if !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) { return nil, policyLoadError{path, i, b, err} } unversionedLines++ // Migrate unversioned policy object oldPolicy := &v0.Policy{} if err := runtime.DecodeInto(decoder, b, oldPolicy); err != nil { return nil, policyLoadError{path, i, b, err} } if err := abac.Scheme.Convert(oldPolicy, p, nil); err != nil { return nil, policyLoadError{path, i, b, err} } pl = append(pl, p) continue } decodedPolicy, ok := decodedObj.(*abac.Policy) if !ok { return nil, policyLoadError{path, i, b, fmt.Errorf("unrecognized object: %#v", decodedObj)} } pl = append(pl, decodedPolicy) } if unversionedLines > 0 { klog.Warningf("Policy file %s contained unversioned rules. See docs/admin/authorization.md#abac-mode for ABAC file format details.", path) } if err := scanner.Err(); err != nil { return nil, policyLoadError{path, -1, nil, err} } return pl, nil }
Creates an UploadedFileMap from the $_FILES superglobal. @param array $files @return array
public static function createFromFilesGlobal(array $files) : array { $items = []; $files = self::normalizeSuperglobal($files); self::buildMap($files, $items); return $items; }
Returns a list of game objects matching the search query. Learn more: https://github.com/justintv/Twitch-API/blob/master/v3_resources/search.md#get-searchgames @param string $query Search query @param array $params Optional params @return array
public function searchGames($query, $params = []) { $defaults = [ 'query' => urlencode($query), 'limit' => 25, 'type' => 'suggest', 'live' => false, ]; return $this->wrapper->request('GET', 'search/games', ['query' => $this->resolveOptions($params, $defaults)]); }
@see \PDO::quote() @param string $string @param int $parameter_type @return string
public function quote($string, $parameter_type = \PDO::PARAM_STR): string { return $this->connection->quote($string, $parameter_type); }
Get items array of target dirctory @param string $dirname itemId path @param bool $recursive @param number $maxResults @param string $query @return array Items array
protected function getItems($dirname, $recursive = false, $maxResults = 0, $query = '') { list (, $itemId) = $this->splitPath($dirname); $maxResults = min($maxResults, 1000); $results = []; $parameters = [ 'pageSize' => $maxResults ?: 1000, 'fields' => $this->fetchfieldsList, 'spaces' => $this->spaces, 'q' => sprintf('trashed = false and "%s" in parents', $itemId) ]; if ($query) { $parameters['q'] .= ' and (' . $query . ')'; } $parameters = $this->applyDefaultParams($parameters, 'files.list'); $pageToken = NULL; $gFiles = $this->service->files; $this->cacheHasDirs[$itemId] = false; $setHasDir = []; do { try { if ($pageToken) { $parameters['pageToken'] = $pageToken; } $fileObjs = $gFiles->listFiles($parameters); if ($fileObjs instanceof Google_Service_Drive_FileList) { foreach ($fileObjs as $obj) { $id = $obj->getId(); $this->cacheFileObjects[$id] = $obj; $result = $this->normaliseObject($obj, $dirname); $results[$id] = $result; if ($result['type'] === 'dir') { if ($this->useHasDir) { $setHasDir[$id] = $id; } if ($this->cacheHasDirs[$itemId] === false) { $this->cacheHasDirs[$itemId] = true; unset($setHasDir[$itemId]); } if ($recursive) { $results = array_merge($results, $this->getItems($result['path'], true, $maxResults, $query)); } } } $pageToken = $fileObjs->getNextPageToken(); } else { $pageToken = NULL; } } catch (Exception $e) { $pageToken = NULL; } } while ($pageToken && $maxResults === 0); if ($setHasDir) { $results = $this->setHasDir($setHasDir, $results); } return array_values($results); }
Tests the existance and eventually creates a directory @param string $dir @param int $mode @param boolean $recursive @return boolean
public static function safeMkdir($dir, $mode = 0777, $recursive = true) { if (! \is_dir ( $dir )) return \mkdir ( $dir, $mode, $recursive ); return true; }
Go through all the values of an object and adds the corresponding value inside its entries using the provided keyName @param {Object} container @param {String} keyName
function (container, keyName) { for (var element in container) { if (container.hasOwnProperty(element)) { container[element][keyName] = element; } } }
Store a value in an encrypted cookie @param string $name @return mixed|null (typically an array) @throws InvalidDigestLength @throws InvalidSignature @throws CannotPerformOperation @throws InvalidType @throws \TypeError
public function fetch(string $name) { if (!isset($_COOKIE[$name])) { return null; } try { /** @var string|array|int|float|bool $stored */ $stored = $_COOKIE[$name]; if (!\is_string($stored)) { throw new InvalidType('Cookie value is not a string'); } $config = self::getConfig($stored); $decrypted = Crypto::decrypt( $stored, $this->key, $config->ENCODING ); return \json_decode($decrypted->getString(), true); } catch (InvalidMessage $e) { return null; } }
Lazy-load the available choices for the select box
public function load_choices() { if (during_initial_install()) { return false; } if (is_array($this->choices)) { return true; } $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')]; $manager = new \core_privacy\local\sitepolicy\manager(); $plugins = $manager->get_all_handlers(); foreach ($plugins as $pname => $unused) { $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin', ['name' => new lang_string('pluginname', $pname), 'component' => $pname]); } return true; }
Attempts to get all information about this user. This method will make 3 requests! @param mixed $identities @return Dto\Summoner;
public function allInfo($identities) { $summoners = $this->info($identities); $this->runePages($summoners); $this->masteryPages($summoners); return $summoners; }
Copy the application into the package.
function (options, dir, callback) { var applicationDir = path.join(dir, 'lib', options.id) options.logger('Copying application to ' + applicationDir) async.waterfall([ async.apply(fs.ensureDir, applicationDir), async.apply(fs.copy, options.src, applicationDir) ], function (err) { callback(err && new Error('Error copying application directory: ' + (err.message || err))) }) }
Scan for miflora devices. Note: this must be run as root!
def scan(backend, timeout=10): result = [] for (mac, name) in backend.scan_for_devices(timeout): if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \ mac is not None and mac.upper().startswith(DEVICE_PREFIX): result.append(mac.upper()) return result
Get an MD5 for a geometry object Parameters ------------ geometry : object Returns ------------ MD5 : str
def geometry_hash(geometry): if hasattr(geometry, 'md5'): # for most of our trimesh objects md5 = geometry.md5() elif hasattr(geometry, 'tostring'): # for unwrapped ndarray objects md5 = str(hash(geometry.tostring())) if hasattr(geometry, 'visual'): # if visual properties are defined md5 += str(geometry.visual.crc()) return md5
process any watches in the last time period
function processWatches(items) { // queue up matches // { "member" : { "uri" : [ "match", "match" ] } } var toSend = {}; GLOBAL.svc.indexer.retrieveWatches({}, function(err, res) { if (res.hits) { var watches = _.pluck(res.hits.hits, '_source'); // for each hit items.forEach(function(item) { var matches = watchLib.matches(item, watches); if (matches.length) { matches.forEach(function(match) { toSend[match.member] = toSend[match.member] || {}; toSend[match.member][item.uri] = toSend[match.member][item.uri] || []; toSend[match.member][item.uri].push(match.match); }); } }); send(toSend); } }); }
Construct a DataFrame from an RDD of DataFrames. No checking or validation occurs.
def fromDataFrameRDD(cls, rdd, sql_ctx): """""" result = DataFrame(None, sql_ctx) return result.from_rdd_of_dataframes(rdd)
Get sort structure. @return array
public function getSortStructure() { $sort = [$this->getField() => (object)['order' => $this->getOrder()]]; if ($this->getMode()) { $sort[$this->getField()]->mode = $this->getMode(); } if ($this->getMissing()) { $sort[$this->getField()]->missing = $this->getMissing(); } return (object)$sort; }
// GetBucketInfo gets bucket metadata..
func (l *b2Objects) GetBucketInfo(ctx context.Context, bucket string) (bi minio.BucketInfo, err error) { if _, err = l.Bucket(ctx, bucket); err != nil { return bi, err } return minio.BucketInfo{ Name: bucket, Created: time.Unix(0, 0), }, nil }
Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file.
def absolute(self): # XXX untested yet! if self.is_absolute(): return self # FIXME this must defer to the specific flavour (and, under Windows, # use nt._getfullpathname()) obj = self._from_parts([os.getcwd()] + self._parts, init=False) obj._init(template=self) return obj
Indents a string. @param String string @param Number nchars @param String prefix @return String
function indent(string, nchars, prefix) { "use strict"; return string.split('\n').map(function(line) { return (prefix || '') + new Array(nchars).join(' ') + line; }).join('\n'); }
get MetricSnapshot formatted value string
public static String getMetricValue(MetricSnapshot snapshot) { if (snapshot == null) return null; MetricType type = MetricType.parse(snapshot.get_metricType()); switch (type) { case COUNTER: return format(snapshot.get_longValue()); case GAUGE: return format(snapshot.get_doubleValue()); case METER: return format(snapshot.get_m1()); case HISTOGRAM: return format(snapshot.get_mean()); default: return "0"; } }
Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in.
def format_search_results(self, search_results): formatted_lines = [] for search_result in search_results: lines = self._format_search_result(search_result) formatted_lines.extend(lines) return formatted_lines
Marshall the given parameter object.
public void marshall(DescribePullRequestEventsRequest describePullRequestEventsRequest, ProtocolMarshaller protocolMarshaller) { if (describePullRequestEventsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describePullRequestEventsRequest.getPullRequestId(), PULLREQUESTID_BINDING); protocolMarshaller.marshall(describePullRequestEventsRequest.getPullRequestEventType(), PULLREQUESTEVENTTYPE_BINDING); protocolMarshaller.marshall(describePullRequestEventsRequest.getActorArn(), ACTORARN_BINDING); protocolMarshaller.marshall(describePullRequestEventsRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(describePullRequestEventsRequest.getMaxResults(), MAXRESULTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Dumps the node descendants into a string using HTML formatting. @param string $delimiter @return string
public function innerHtml($delimiter = '') { $innerHtml = []; foreach ($this->node->childNodes as $childNode) { $innerHtml[] = $childNode->ownerDocument->saveHTML($childNode); } return implode($delimiter, $innerHtml); }
// SetSshKey sets the SshKey field's value.
func (s *Source) SetSshKey(v string) *Source { s.SshKey = &v return s }
Arguments are comma-separated expressions
function() { var args = [], arg; arg = $(this.expression); while (arg) { args.push(arg); if (! $(',')) { break; } arg = $(this.expression); } return args; }
remove the source path from the dirname (if it exists)
def digest_dirname(file_path) slash_path(File.dirname(file_path)).sub(slash_path(self.source.path), '') end
Create the Whisper file on disk
def _create(self): """""" if not os.path.exists(settings.SALMON_WHISPER_DB_PATH): os.makedirs(settings.SALMON_WHISPER_DB_PATH) archives = [whisper.parseRetentionDef(retentionDef) for retentionDef in settings.ARCHIVES.split(",")] whisper.create(self.path, archives, xFilesFactor=settings.XFILEFACTOR, aggregationMethod=settings.AGGREGATION_METHOD)
@param \Platformsh\Client\Model\Certificate $cert @param string $alias @return string|bool
protected function getCertificateIssuerByAlias(Certificate $cert, $alias) { foreach ($cert->issuer as $issuer) { if (isset($issuer['alias'], $issuer['value']) && $issuer['alias'] === $alias) { return $issuer['value']; } } return false; }
Run the system test suite.
def system(session): """""" # Sanity check: Only run system tests if the environment variable is set. if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environment variable.') # Install all test dependencies, then install this package into the # virtualenv's dist-packages. session.install('pytest') session.install('-e', os.path.join('..', 'test_utils')) for local_dep in LOCAL_DEPS: session.install('-e', local_dep) session.install('-e', '.[pandas,fastavro]') # Run py.test against the system tests. session.run('py.test', '--quiet', 'tests/system/')
//MarshalAnsilbe mashals the struct into an Ansible supported JSON
func (h *Host) MarshalAnsible() map[string]interface{} { var vStr []map[string]interface{} if len(h.Vars) > 0 { for i := range h.Vars { vStr = append(vStr, h.Vars[i].MarshalAnsible()) } return map[string]interface{}{h.Name: map[string]interface{}{"vars": vStr}} } return map[string]interface{}{h.Name: ""} }
// AddSSHKeyToAllInstances adds an SSH public key as a legal identity for all instances // expected format for the key is standard ssh-keygen format: <protocol> <blob>
func (g *Cloud) AddSSHKeyToAllInstances(ctx context.Context, user string, keyData []byte) error { ctx, cancel := cloud.ContextWithCallTimeout() defer cancel() return wait.Poll(2*time.Second, 30*time.Second, func() (bool, error) { project, err := g.c.Projects().Get(ctx, g.projectID) if err != nil { klog.Errorf("Could not get project: %v", err) return false, nil } keyString := fmt.Sprintf("%s:%s %s@%s", user, strings.TrimSpace(string(keyData)), user, user) found := false for _, item := range project.CommonInstanceMetadata.Items { if item.Key == "sshKeys" { if strings.Contains(*item.Value, keyString) { // We've already added the key klog.Info("SSHKey already in project metadata") return true, nil } value := *item.Value + "\n" + keyString item.Value = &value found = true break } } if !found { // This is super unlikely, so log. klog.Infof("Failed to find sshKeys metadata, creating a new item") project.CommonInstanceMetadata.Items = append(project.CommonInstanceMetadata.Items, &compute.MetadataItems{ Key: "sshKeys", Value: &keyString, }) } mc := newInstancesMetricContext("add_ssh_key", "") err = g.c.Projects().SetCommonInstanceMetadata(ctx, g.projectID, project.CommonInstanceMetadata) mc.Observe(err) if err != nil { klog.Errorf("Could not Set Metadata: %v", err) return false, nil } klog.Infof("Successfully added sshKey to project metadata") return true, nil }) }
Renders the provided value. @param array<string, mixed> $context @param mixed $value @param array<string, mixed> $parameters @param string $viewContext @return string
public function renderValue(array $context, $value, array $parameters = [], ?string $viewContext = null): string { try { return $this->renderer->renderValue( $value, $this->getViewContext($context, $viewContext), $parameters ); } catch (Throwable $t) { $message = sprintf( 'Error rendering a value of type "%s"', is_object($value) ? get_class($value) : gettype($value) ); $this->errorHandler->handleError($t, $message, ['object' => $value]); } return ''; }
// SetSubmitTimeMillis sets the SubmitTimeMillis field's value.
func (s *Timing) SetSubmitTimeMillis(v int64) *Timing { s.SubmitTimeMillis = &v return s }
Safely create a symbolic link to an input field.
def make_symlink(src_path, lnk_path): """""" # Check for Lustre 60-character symbolic link path bug if CHECK_LUSTRE_PATH_LEN: src_path = patch_lustre_path(src_path) lnk_path = patch_lustre_path(lnk_path) # os.symlink will happily make a symlink to a non-existent # file, but we don't want that behaviour # XXX: Do we want to be doing this? if not os.path.exists(src_path): return try: os.symlink(src_path, lnk_path) except EnvironmentError as exc: if exc.errno != errno.EEXIST: raise elif not os.path.islink(lnk_path): # Warn the user, but do not interrupt the job print("Warning: Cannot create symbolic link to {p}; a file named " "{f} already exists.".format(p=src_path, f=lnk_path)) else: # Overwrite any existing symbolic link if os.path.realpath(lnk_path) != src_path: os.remove(lnk_path) os.symlink(src_path, lnk_path)
/* At this point, any content is assumed to be an URL
function(url) { var self = this, deferred = $.Deferred(); /* we are using load so one can specify a target with: url.html #targetelement */ var $container = $('<div></div>').load(url, function(response, status){ if ( status !== "error" ) { deferred.resolve($container.contents()); } deferred.reject(); }); return deferred.promise(); }
// GetPassword gets a line with the prefix and doesn't echo input.
func (term *Terminal) GetPassword(prefix string) (string, error) { prefix += " " if !term.t.supportsEditing { return term.simplePrompt(prefix) } buf := NewBuffer(prefix, term.Out, false) return term.password(buf, NewAnsiReader(term.In)) }
Loads the context map from the VFS.<p> @return the context map @throws Exception if something goes wrong
private Map<String, CmsTemplateContext> initMap() throws Exception { Map<String, CmsTemplateContext> result = new LinkedHashMap<String, CmsTemplateContext>(); String path = getConfigurationPropertyPath(); CmsResource resource = m_cms.readResource(path); CmsFile file = m_cms.readFile(resource); String fileContent = new String(file.getContents(), "UTF-8"); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setCmsObject(m_cms); for (Map.Entry<String, String> param : m_params.entrySet()) { resolver.addMacro(param.getKey(), param.getValue()); } fileContent = resolver.resolveMacros(fileContent); JSONTokener tok = new JSONTokener(fileContent); tok.setOrdered(true); JSONObject root = new JSONObject(tok, true); for (String templateContextName : root.keySet()) { JSONObject templateContextJson = (JSONObject)(root.opt(templateContextName)); CmsJsonMessageContainer jsonMessage = new CmsJsonMessageContainer(templateContextJson.opt(A_NICE_NAME)); String templatePath = (String)templateContextJson.opt(A_PATH); JSONObject variantsJson = (JSONObject)templateContextJson.opt(A_VARIANTS); List<CmsClientVariant> variants = new ArrayList<CmsClientVariant>(); if (variantsJson != null) { for (String variantName : variantsJson.keySet()) { JSONObject variantJson = (JSONObject)variantsJson.opt(variantName); CmsJsonMessageContainer variantMessage = new CmsJsonMessageContainer(variantJson.opt(A_NICE_NAME)); int width = variantJson.optInt(A_WIDTH, 800); int height = variantJson.optInt(A_HEIGHT, 600); CmsClientVariant variant = new CmsClientVariant( variantName, variantMessage, width, height, new HashMap<String, String>()); variants.add(variant); } } CmsTemplateContext templateContext = new CmsTemplateContext( templateContextName, templatePath, jsonMessage, this, variants, false); result.put(templateContextName, templateContext); } return result; }
Get informations about SaaS CSP2 options REST: GET /order/cart/{cartId}/csp2/options @param cartId [required] Cart identifier @param planCode [required] Identifier of a SaaS CSP2 main offer
public ArrayList<OvhGenericOptionDefinition> cart_cartId_csp2_options_GET(String cartId, String planCode) throws IOException { String qPath = "/order/cart/{cartId}/csp2/options"; StringBuilder sb = path(qPath, cartId); query(sb, "planCode", planCode); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, t2); }
Write a list of Strings to document as elements with given tag name. @param xmlOutput the XMLOutput object to write to @param tagName the tag name @param listValues Collection of String values to write
public static void writeElementList(XMLOutput xmlOutput, String tagName, Iterable<String> listValues) throws IOException { writeElementList(xmlOutput, tagName, listValues.iterator()); }
See neighbor_graph.
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None, weighting='none'): '''''' assert ((k is not None) or (epsilon is not None) ), "Must provide `k` or `epsilon`" assert (_issequence(k) ^ _issequence(epsilon) ), "Exactly one of `k` or `epsilon` must be a sequence." assert weighting in ('binary','none'), "Invalid weighting param: " + weighting is_weighted = weighting == 'none' if precomputed: D = X else: D = pairwise_distances(X, metric='euclidean') # pre-sort for efficiency order = np.argsort(D)[:,1:] if k is None: k = D.shape[0] # generate the sequence of graphs # TODO: convert the core of these loops to Cython for speed W = np.zeros_like(D) I = np.arange(D.shape[0]) if _issequence(k): # varied k, fixed epsilon if epsilon is not None: D[D > epsilon] = 0 old_k = 0 for new_k in k: idx = order[:, old_k:new_k] dist = D[I, idx.T] W[I, idx.T] = dist if is_weighted else 1 yield Graph.from_adj_matrix(W) old_k = new_k else: # varied epsilon, fixed k idx = order[:,:k] dist = D[I, idx.T].T old_i = np.zeros(D.shape[0], dtype=int) for eps in epsilon: for i, row in enumerate(dist): oi = old_i[i] ni = oi + np.searchsorted(row[oi:], eps) rr = row[oi:ni] W[i, idx[i,oi:ni]] = rr if is_weighted else 1 old_i[i] = ni yield Graph.from_adj_matrix(W)
@param Queries\ISegment[] $segments @return Queries\ISegment[]
protected function processSegments(array $segments) { $this->segments = []; foreach ($segments as $segment) { $this->segments[] = $segment->traverse($this); } return $this->segments; }
// NewAddress is called to get new addresses for delivery, change etc.
func (m *mockWalletController) NewAddress(addrType lnwallet.AddressType, change bool) (btcutil.Address, error) { addr, _ := btcutil.NewAddressPubKey( m.rootKey.PubKey().SerializeCompressed(), &chaincfg.MainNetParams) return addr, nil }
Apply a predicate to the optional, if the optional is present, and the predicate is true, return the optional, otherwise return empty. @param predicate the predicate to apply @return the optional if the predicate is true, empty if not @since 1.7
public Optional<T> filter(final Predicate<? super T> predicate) { if (isPresent() && predicate.test(get())) { return this; } return empty(); }
----- private methods -----
private void updateAccessInformation(final SecurityContext securityContext, final PropertyContainer propertyContainer) throws FrameworkException { try { if (securityContext.modifyAccessTime()) { final Principal user = securityContext.getUser(false); String modifiedById = null; if (user != null) { if (user instanceof SuperUser) { // "virtual" UUID of superuser modifiedById = Principal.SUPERUSER_ID; } else { modifiedById = user.getUuid(); } propertyContainer.setProperty(AbstractNode.lastModifiedBy.dbName(), modifiedById); } propertyContainer.setProperty(AbstractNode.lastModifiedDate.dbName(), System.currentTimeMillis()); } } catch (Throwable t) { // fail without throwing an exception here logger.warn("", t); } }
Delete migration file if options is set @param string $migration @return null
protected function deleteIfNeeded($migration) { if (!$this->input->getOption('delete')) { return; } if ($this->migrator->deleteMigrationFile($migration)) { $this->message("<info>Deleted:</info> {$migration}.php"); } }
/* The source of Slack message can be either Json asset or process variable.
public JSONObject getMessage() throws ActivityException { String message = null; String slackMessageName = getAttributeValueSmart(SLACK_MESSAGE); if (slackMessageName == null) throw new ActivityException("slack message attribute is not set"); Asset template = AssetCache.getAsset(slackMessageName); if (template == null) { message = slackMessageName; } else { message = context.evaluateToString(template.getStringContent()); } JSONObject json = new JSONObject(); String env = ApplicationContext.getRuntimeEnvironment().toUpperCase(); json.put("text", env + " - " + getSlackPrefix() + " - " + message); String altText = null; if (json.has("text")) { String text = json.getString("text"); if (text.length() > 200) altText = text.substring(0, 197) + "..."; } if (altText != null) json.put("text", altText); return json; }
Get the data from a *hole instance.
async def main(): """""" async with aiohttp.ClientSession() as session: data = Hole('192.168.0.215', loop, session) await data.get_data() # Get the raw data print(json.dumps(data.data, indent=4, sort_keys=True)) print("Status:", data.status) print("Domains being blocked:", data.domains_being_blocked)
Store given transition in the backend
def store_transition(self, frame, action, reward, done, extra_info=None): self.current_idx = (self.current_idx + 1) % self.buffer_capacity if self.frame_stack_compensation: # Compensate for frame stack built into the environment idx_range = np.arange(-frame.shape[-1] // self.frame_history, 0) frame = np.take(frame, indices=idx_range, axis=-1) self.state_buffer[self.current_idx] = frame self.action_buffer[self.current_idx] = action self.reward_buffer[self.current_idx] = reward self.dones_buffer[self.current_idx] = done if extra_info is not None: for name in extra_info: if name not in self.extra_data: assert self.current_size == 0, f"New data {name} encountered in the middle of the training" array = extra_info[name] self.extra_data[name] = np.zeros([self.buffer_capacity] + list(array.shape), dtype=array.dtype) self.extra_data[name][self.current_idx] = extra_info[name] if self.current_size < self.buffer_capacity: self.current_size += 1 return self.current_idx
Throw a new UnsupportedFilterException if the given filter cannot be adapted to bigtable reader expressions. @param scan a {@link org.apache.hadoop.hbase.client.Scan} object. @param filter a {@link org.apache.hadoop.hbase.filter.Filter} object.
public void throwIfUnsupportedFilter(Scan scan, Filter filter) { List<FilterSupportStatus> filterSupportStatuses = new ArrayList<>(); FilterAdapterContext context = new FilterAdapterContext(scan, null); collectUnsupportedStatuses(context, filter, filterSupportStatuses); if (!filterSupportStatuses.isEmpty()) { throw new UnsupportedFilterException(filterSupportStatuses); } }
Returns the opitmal SNR squared in the given detector. Parameters ---------- det : str The name of the detector. Returns ------- float : The opimtal SNR squared.
def det_optimal_snrsq(self, det): # try to get it from current stats try: return getattr(self._current_stats, '{}_optimal_snrsq'.format(det)) except AttributeError: # hasn't been calculated yet; call loglr to do so self._loglr() # now try returning again return getattr(self._current_stats, '{}_optimal_snrsq'.format(det))
NOTE: This method is used by hierarchy report template, harmless for others. Creates the HTML fragments for any features assigned to this suite, and stores them in `featureMarkup` attribute of the suite so we can render them in index.tmpl @param suite
function (suite) { return _.template(readFileForRespectiveTemplates('features.html'))({ suite: suite, _: _, calculateDuration: calculateDuration, columnLayoutWidth: getColumnLayoutWidth(), decideScenarioTitlePadding: preventOverlappingTheScenarioTitle }); }
Register js for ajax notifications
protected function registerJs() { $config['options'] = $this->options; $config['layerOptions'] = $this->layerOptions; $config['layerOptions']['layerId'] = $this->layer->getLayerId(); $config = Json::encode($config); $layerClass = Json::encode($this->layerClass); $this->view->registerJs(" $.ajaxSetup({ showNoty: true // default for all ajax calls }); $(document).ajaxComplete(function (event, xhr, settings) { if (settings.showNoty && (settings.type=='POST' || settings.container)) { $.ajax({ url: '$this->url', method: 'POST', cache: false, showNoty: false, global: false, data: { layerClass: '$layerClass', config: '$config' }, success: function(data) { $('#" . $this->layer->getLayerId() . "').html(data); } }); } }); ", View::POS_END); }
Initialize the YouTubeSupportFrament attached as top fragment to the DraggablePanel widget and reproduce the YouTube video represented with a YouTube url.
private void initializeYoutubeFragment() { youtubeFragment = new YouTubePlayerSupportFragment(); youtubeFragment.initialize(YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { if (!wasRestored) { youtubePlayer = player; youtubePlayer.loadVideo(VIDEO_KEY); youtubePlayer.setShowFullscreenButton(true); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) { } }); }
Return extracted data (configured by fields array) from node.
private function getFieldsData( Row $row, NodeInterface $node, $document, $fields, $templateKey, $webspaceKey, $locale ) { $fieldsData = []; foreach ($fields as $field) { // determine target for data in result array if (isset($field['target'])) { if (!isset($fieldsData[$field['target']])) { $fieldsData[$field['target']] = []; } $target = &$fieldsData[$field['target']]; } else { $target = &$fieldsData; } // create target if (!isset($target[$field['name']])) { $target[$field['name']] = ''; } if (null !== ($data = $this->getFieldData( $field, $row, $node, $document, $templateKey, $webspaceKey, $locale )) ) { $target[$field['name']] = $data; } } return $fieldsData; }
Do Transition from C @return self Fluent Interface
private function doTransitionFromC() : self { if ($this->getToken() === Grammar::T_X) { if ($this->hasToken(1) && $this->getToken(1) === Grammar::T_X) { if ($this->hasToken(2) && $this->getToken(2) === Grammar::T_X) { $this ->setState(self::STATE_B) ->addPosition(3) ->addTokenValue(Grammar::T_X, null, 3); return $this; } $this ->setState(self::STATE_B) ->addPosition(2) ->addTokenValue(Grammar::T_X, null, 2); return $this; } $this ->setState(self::STATE_B) ->addPosition(1) ->addTokenValue(Grammar::T_X); return $this; } $this->setState(self::STATE_B); return $this; }
Генерация тега keywords @return Tag
public function keywords($default = null) { if (!$k = $this->getKeywords()) { $d = $default ?: $this->getDefaultKeywords(); $k = is_null($d) ? $this->getTitle() : $d; } return new Tag('meta', null, array('name' => 'keywords', 'content' => $k), true); }
Copies the atributes from an obj to a destination obj @param sourceResource source resource obj @param destinationResource destination resource obj @param <T> @return @throws MPException
private static <T extends MPBase> T fillResource(T sourceResource, T destinationResource) throws MPException { Field[] declaredFields = destinationResource.getClass().getDeclaredFields(); for (Field field : declaredFields) { try { Field originField = sourceResource.getClass().getDeclaredField(field.getName()); field.setAccessible(true); originField.setAccessible(true); field.set(destinationResource, originField.get(sourceResource)); } catch (Exception ex) { throw new MPException(ex); } } return destinationResource; }
Import's object from given Python path.
def get_object_from_path(path): try: return sys.IMPORT_CACHE[path] except KeyError: _path = path.split('.') module_path = '.'.join(_path[:-1]) class_name = _path[-1] module = importlib.import_module(module_path) sys.IMPORT_CACHE[path] = getattr(module, class_name) return sys.IMPORT_CACHE[path]
Throws an exception if any included/excluded variable pattern is not applicable to the given input definition.
private void assertApplicable( FunctionInputDef inputDef) throws IllegalArgumentException { try { for( VarNamePattern varNamePattern : getIncludedVars()) { assertApplicable( inputDef, varNamePattern); } for( VarNamePattern varNamePattern : getExcludedVars()) { assertApplicable( inputDef, varNamePattern); } } catch( Exception e) { throw new IllegalArgumentException( "Can't apply " + this + " to " + inputDef, e); } }
Heuristically extracts the base indentation from the provided code. Finds the smallest indentation following a newline not at the end of the string.
def get_base_indentation(code, include_start=False): new_line_indentation = re_new_line_indentation[include_start].finditer(code) new_line_indentation = tuple(m.groups(0)[0] for m in new_line_indentation) if new_line_indentation: return min(new_line_indentation, key=len) else: return ""
Invokes the pipeline with the defined command. Command line arguments, and the command need to be set with arg_builder, and command_builder respectively before this method can be invoked.
def run(self, args, pipeline_command): # output that must be moved but not renamed consistentNaming = ['alignments/normal_dna_fix_pg_sorted.bam', 'alignments/normal_dna_fix_pg_sorted.bam.bai', 'alignments/rna_genome_sorted.bam', 'alignments/rna_genome_sorted.bam.bai', 'alignments/rna_transcriptome.bam', 'alignments/tumor_dna_fix_pg_sorted.bam', 'alignments/tumor_dna_fix_pg_sorted.bam.bai', 'mutations/merged/all_merged.vcf', 'rankboost/mhcii_rankboost_concise_results.tsv', 'rankboost/mhci_rankboost_concise_results.tsv', ] # output that must be renamed as well as moved # map of the original name to the final name renamingNeeded = {'binding_predictions': 'binding_predictions.tar', 'expression': 'expression.tar', 'haplotyping': 'haplotyping.tar', 'peptides': 'peptides.tar', 'rankboost': 'rankboost.tar', 'reports': 'reports.tar', 'mutations/snpeffed/mutations.vcf': 'all_snpeffed.vcf', 'mutations/transgened/mutations.vcf': 'all_transgened.vcf', 'mutations/merged': 'merged_perchrom.tar', 'mutations/muse': 'muse_perchrom.tar', 'mutations/mutect': 'mutect_perchrom.tar', 'mutations/radia': 'radia_perchrom.tar', 'mutations/somaticsniper': 'somaticsniper_perchrom.tar', 'mutations/strelka/snv': 'strelka_snv_perchrom.tar', 'mutations/strelka/indel': 'strelka_indel_perchrom.tar'} def make_output(output_dir, source_dir): """ :param output_dir: dir to write the output to :param source_dir: dir containing the directory structure to be parsed :return: """ def make_tar(dir, tar): with tarfile.open(tar, "w:gz") as tar: tar.add(dir) # the output dir is where the real output directories are written protect_outputs = os.listdir(source_dir) for protectOut in protect_outputs: def getName(fileName): return os.path.join(os.path.join(source_dir, protectOut), fileName) # move individual files out for fileName in consistentNaming: shutil.copyfile(getName(fileName), os.path.join(output_dir, os.path.basename(fileName))) for src, dst in renamingNeeded.iteritems(): if dst.endswith('.tar'): make_tar(getName(src), os.path.join(output_dir, dst)) else: shutil.copyfile(getName(src), os.path.join(output_dir, dst)) shutil.rmtree(source_dir) # prepare workdir mount = self._prepare_mount(args) self._workdir = os.path.join(mount, 'Toil-' + self._name) # insure the pairs are in the same directory, as protect expects # This is made more complicated by the fact CWLTool mounts inputs into random, read-only dirs # to get around this we copy all inputs into their own directories that we own tumor_dna_dir = os.path.expanduser('~/tumorDNA') tumor_rna_dir = os.path.expanduser('~/tumorRNA') normal_dna_dir = os.path.expanduser('~/normalDNA') os.mkdir(tumor_dna_dir) os.mkdir(tumor_rna_dir) os.mkdir(normal_dna_dir) shutil.copy(args.tumor_dna, tumor_dna_dir) shutil.copy(args.tumor_rna, tumor_rna_dir) shutil.copy(args.normal_dna, normal_dna_dir) shutil.copy(args.tumor_dna2, tumor_dna_dir) shutil.copy(args.tumor_rna2, tumor_rna_dir) shutil.copy(args.normal_dna2, normal_dna_dir) args.tumor_dna = os.path.join(tumor_dna_dir, os.path.basename(args.tumor_dna)) args.tumor_dna2 = os.path.join(tumor_dna_dir, os.path.basename(args.tumor_dna2)) args.tumor_rna = os.path.join(tumor_rna_dir, os.path.basename(args.tumor_rna)) args.tumor_rna2 = os.path.join(tumor_rna_dir, os.path.basename(args.tumor_rna2)) args.normal_dna = os.path.join(normal_dna_dir, os.path.basename(args.normal_dna)) args.normal_dna2 = os.path.join(normal_dna_dir, os.path.basename(args.normal_dna2)) # prepare config args_dict = vars(args) args_dict['output_dir'] = mount self._config = textwrap.dedent(self._config.format(**args_dict)) self._sample_name = args_dict["sample_name"] config_path = os.path.join(self._workdir, 'config') command = self._make_prefix(os.path.join(self._workdir, 'jobStore'), config_path, self._workdir) + pipeline_command if self._resume and args.resume: command.append('--restart') self._create_workdir(args) with open(config_path, 'w') as f: f.write(self._config) try: subprocess.check_call(command) except subprocess.CalledProcessError as e: print(e, file=sys.stderr) finally: log.info('Pipeline terminated, changing ownership of output files from root to user.') stat = os.stat(self._mount) subprocess.check_call(['chown', '-R', '{}:{}'.format(stat.st_uid, stat.st_gid), self._mount]) make_output(self._mount, os.path.join(self._mount, 'output')) if self._no_clean and args.no_clean: log.info('Flag "--no-clean" was used, therefore %s was not deleted.', self._workdir) else: log.info('Cleaning up temporary directory: %s', self._workdir) shutil.rmtree(self._workdir)
Simple helper hash function
def _my_hash(arg_list): # type: (List[Any]) -> int """""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
Calculate start/end date for event list TODO this should go in a helper class
public static function offset_date($type, $timestamp, $offset = 30) { if (!$timestamp) { $timestamp = time(); } // check whether the timestamp was // given as a date string (2016-09-05) if(strpos($timestamp, "-") > 0) { $timestamp = strtotime($timestamp); } $offsetCalc = $offset * 24 * 60 * 60; //days in secs $offsetTime = null; if ($type == 'start') { $offsetTime = $timestamp - $offsetCalc; } elseif ($type == 'end') { $offsetTime = $timestamp + $offsetCalc; } $str = date('Y-m-d', $offsetTime); return $str; }
Formats query. @param alert {@link net.anotheria.moskito.core.threshold.alerts.ThresholdAlert} @return query
private String formatQuery(final ThresholdAlert alert) { return String.format(SMS_QUERY_FORMAT, user, password, createMessage(alert, smsTemplate), recipients); // TODO: improve not to replace user/password/etc every time }
Skips empty lines before frame headers (they are allowed after \00)
private function skipEmptyLines() { $foundHeartbeat = false; while ($this->offset < $this->bufferSize) { $char = substr($this->buffer, $this->offset, 1); if ($char === "\x00" || $char === "\n" || $char === "\r") { $this->offset++; $foundHeartbeat = true; } else { break; } } if ($foundHeartbeat && $this->observer) { $this->observer->emptyLineReceived(); } }
Stretch the color map via altering the shift map.
def stretch(self, scale_factor, callback=True): self.scale_pct *= scale_factor self.scale_and_shift(self.scale_pct, 0.0, callback=callback)
Returns if the given URI is pointing to the OpenCms workplace UI.<p> @param uri the URI @return <code>true</code> if the given URI is pointing to the OpenCms workplace UI
public static boolean isWorkplaceUri(URI uri) { return (uri != null) && uri.getPath().startsWith(OpenCms.getSystemInfo().getWorkplaceContext()); }
Find published news categories by parent ID. @param int $pid @return Collection|null
public static function findPublishedByPid($pid) { $t = static::getTableAlias(); $columns = ["$t.pid=?"]; $values = [$pid]; if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findBy($columns, $values, ['order' => "$t.sorting"]); }
Checks if a task is revoked, returns a 2-tuple indicating: 1. Is task revoked? 2. Should task be restored?
def _check_revoked(self, revoke_id, timestamp=None, peek=True): res = self.get(revoke_id, peek=True) if res is None: return False, False revoke_until, revoke_once = res if revoke_until is not None and timestamp is None: timestamp = self._get_timestamp() if revoke_once: # This task *was* revoked for one run, but now it should be # restored to normal execution (unless we are just peeking). return True, not peek elif revoke_until is not None and revoke_until <= timestamp: # Task is no longer revoked and can be restored. return False, not peek else: # Task is still revoked. Do not restore. return True, False
Query currently-available TA checks, return the check ID and metadata of the 'performance/Service Limits' check. :returns: 2-tuple of Service Limits TA check ID (string), metadata (list), or (None, None). :rtype: tuple
def _get_limit_check_id(self): logger.debug("Querying Trusted Advisor checks") try: checks = self.conn.describe_trusted_advisor_checks( language='en' )['checks'] except ClientError as ex: if ex.response['Error']['Code'] == 'SubscriptionRequiredException': logger.warning( "Cannot check TrustedAdvisor: %s", ex.response['Error']['Message'] ) self.have_ta = False return (None, None) else: raise ex for check in checks: if ( check['category'] == 'performance' and check['name'] == 'Service Limits' ): logger.debug("Found TA check; id=%s", check['id']) return ( check['id'], check['metadata'] ) logger.debug("Unable to find check with category 'performance' and " "name 'Service Limits'.") return (None, None)
// Validate inspects the fields of the type to determine if they are valid.
func (s *CreateCaseInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "CreateCaseInput"} if s.CommunicationBody == nil { invalidParams.Add(request.NewErrParamRequired("CommunicationBody")) } if s.CommunicationBody != nil && len(*s.CommunicationBody) < 1 { invalidParams.Add(request.NewErrParamMinLen("CommunicationBody", 1)) } if s.Subject == nil { invalidParams.Add(request.NewErrParamRequired("Subject")) } if invalidParams.Len() > 0 { return invalidParams } return nil }