query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Pause the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @note: Not all services support this. @see: L{get_services}, L{get_active_services}, L{start_service}, L{stop_service}, L{resume_service}
def pause_service(name): """ Pause the service given by name. @warn: This method requires UAC elevation in Windows Vista and above. @note: Not all services support this. @see: L{get_services}, L{get_active_services}, L{start_service}, L{stop_service}, L{resume_serv...
csn
Get the pusher client. @param string[] $auth @return \Pusher\Pusher
protected function getClient(array $auth): Pusher { return new Pusher( $auth['auth_key'], $auth['secret'], $auth['app_id'], $auth['options'], $auth['host'], $auth['port'], $auth['timeout'] ); }
csn
// SwitchBlockOn switches desired block on for the current model. // Valid block types are "BlockDestroy", "BlockRemove" and "BlockChange".
func (c *Client) SwitchBlockOn(blockType, msg string) error { args := params.BlockSwitchParams{ Type: blockType, Message: msg, } var result params.ErrorResult if err := c.facade.FacadeCall("SwitchBlockOn", args, &result); err != nil { return errors.Trace(err) } if result.Error != nil { // cope with typ...
csn
Composes & sends the email from a contact message @param Contact $contactMessage @return mixed
public function sendMessage(Contact $contactMessage) { $serverName = ($_SERVER['HTTP_HOST'] ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']); // PREPARE THE EMAIL MESSAGE $message = new Message(); $message->addFrom(new Address($contactMessage->getEmail(), $contactMessage->getFirst...
csn
Get the value of the given configuration path. @param string $name The dotted path to the configuration value (e.g. "path.to.the.value") @return mixed The value of the configuration value. This can be anything JSON supports (e.g. boolean, integer, string, array or map). @throws UnknownConfigValueException If the con...
public function getValue($name) { if (!$this->hasValue($name)) { throw new UnknownConfigValueException($name); } $itemData = $this->configData->{$name}; if (isset($itemData->value)) { return $itemData->value; } if (isset($itemData->defaultValue)) { return $itemData->defaultValue; } t...
csn
send the given Particle to application Particle fifo @param [Particle] p the Particle to send
def send_p p puts " * send_p #{(p.next_dst.nil? ? 'no dst' : p.next_dst)} ..." if @spin.debug_routing _send p puts " -> #{p.dst.path}#{Edoors::ACT_SEP}#{p.action}" if @spin.debug_routing @spin.post_p p end
csn
Handler for validate the response body. @param string $responseBody Content body of the response @return string
private function responseHandler($responseBody) { if ('json' === $this->outputFormat) { return $this->validateJsonResponse($responseBody); } return $this->validateXmlResponse($responseBody); }
csn
// GetAllAWSServiceDiscoveryPrivateDnsNamespaceResources retrieves all AWSServiceDiscoveryPrivateDnsNamespace items from an AWS CloudFormation template
func (t *Template) GetAllAWSServiceDiscoveryPrivateDnsNamespaceResources() map[string]*resources.AWSServiceDiscoveryPrivateDnsNamespace { results := map[string]*resources.AWSServiceDiscoveryPrivateDnsNamespace{} for name, untyped := range t.Resources { switch resource := untyped.(type) { case *resources.AWSServic...
csn
gets the mosaic rule object as a dictionary
def value(self): """ gets the mosaic rule object as a dictionary """ if self.mosaicMethod == "esriMosaicNone" or\ self.mosaicMethod == "esriMosaicCenter" or \ self.mosaicMethod == "esriMosaicNorthwest" or \ self.mosaicMethod == "esriMosaicNadir": ...
csn
Sets the User Creation Datetime attribute value. @param mixed $creation_datetime New value for attribute @return CNabuDataObject Returns self instance to grant chained setters call.
public function setCreationDatetime($creation_datetime) : CNabuDataObject { if ($creation_datetime === null) { throw new ENabuCoreException( ENabuCoreException::ERROR_NULL_VALUE_NOT_ALLOWED_IN, array("\$creation_datetime") ); } ...
csn
Return each row as a vector in an array. @return \Rubix\Tensor\Vector[]
public function asVectors() : array { $vectors = []; foreach ($this->a as $row) { $vectors[] = Vector::quick($row); } return $vectors; }
csn
Get the Value of this field as a double. For a boolean, return 0 for false 1 for true. @return The value of this field.
public double getValue() { // Get this field's value Boolean bField = (Boolean)this.getData(); // Get the physical data if (bField == null) return 0; boolean bValue = bField.booleanValue(); if (bValue == false) return 0; else retu...
csn
Runs the specified SearchVariantRequest.
def runSearchVariants(self, request): """ Runs the specified SearchVariantRequest. """ return self.runSearchRequest( request, protocol.SearchVariantsRequest, protocol.SearchVariantsResponse, self.variantsGenerator)
csn
// Move will move one entry from one location to another. Cross-store moves are // supported. Moving an entry will decode it from the old location, encode it // for the destination store with the right set of recipients and remove it // from the old location afterwards.
func (r *Store) Move(ctx context.Context, from, to string) error { return r.move(ctx, from, to, true) }
csn
Formats a vrrp configuration dictionary to match the information as presented from the get and getall methods. vrrp configuration dictionaries passed to the create method may contain data for setting properties which results in a default value on the node. In these instances, the data ...
def vrconf_format(self, vrconfig): """Formats a vrrp configuration dictionary to match the information as presented from the get and getall methods. vrrp configuration dictionaries passed to the create method may contain data for setting properties which results in a default valu...
csn
Generate an order container from a quote object. :param quote_id: ID number of target quote
def get_order_container(self, quote_id): """Generate an order container from a quote object. :param quote_id: ID number of target quote """ quote = self.client['Billing_Order_Quote'] container = quote.getRecalculatedOrderContainer(id=quote_id) return container
csn
Try to set us as active
function (element, scroller) { if (!element || !_Global.document.body || !_Global.document.body.contains(element)) { return false; } if (!_ElementUtilities._setActive(element, scroller)) { return false; ...
csn
Convert emoji lexicon file to a dictionary
def make_emoji_dict(self): """ Convert emoji lexicon file to a dictionary """ emoji_dict = {} for line in self.emoji_full_filepath.split('\n'): (emoji, description) = line.strip().split('\t')[0:2] emoji_dict[emoji] = description return emoji_dict
csn
Finds intersection of two ranges @param {Range} range @returns {Range} <code>null</code> if ranges does not overlap
function(range) { if (this.overlap(range)) { var start = Math.max(range.start, this.start); var end = Math.min(range.end, this.end); return new Range(start, end - start); } return null; }
csn
Convert the coordinates of an DOM Event from screen into element coordinates. @param doc Document context @param tag Element containing the coordinate system @param evt Event to interpret @return coordinates
public static SVGPoint elementCoordinatesFromEvent(Document doc, Element tag, Event evt) { try { DOMMouseEvent gnme = (DOMMouseEvent) evt; SVGMatrix mat = ((SVGLocatable) tag).getScreenCTM(); SVGMatrix imat = mat.inverse(); SVGPoint cPt = ((SVGDocument) doc).getRootElement().createSVGPoint()...
csn
// NextFields returns the next `count` fields
func (s *scanner) NextFields(count int) []string { fields := make([]string, 0, count) for i := 0; i < count; i++ { if field := s.Next(); field != "" { fields = append(fields, field) } else { break } } return fields }
csn
Mark the current job as having failed @param \Exception $e
public function fail(\Exception $e) { $this->stopped(); $this->setStatus(Job::STATUS_FAILED, $e); // For the failed jobs we store a lot more data for debugging $packet = $this->getPacket(); $failed_payload = array_merge(json_decode($this->payload, true), array( ...
csn
Add a file to a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. file...
def add_file( profile, branch, file_path, file_contents, is_executable=False, commit_message=None): """Add a file to a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this...
csn
returns True if the data dictionary is configured for variant calling
def has_variantcalls(data): """ returns True if the data dictionary is configured for variant calling """ analysis = get_analysis(data).lower() variant_pipeline = analysis.startswith(("standard", "variant", "variant2")) variantcaller = get_variantcaller(data) return variant_pipeline or varia...
csn
// listEntries returns a list of bonjour entries. It's convoluted because for // some reason they decided they wanted to make it asynchronous. Seems like writing // javascript, bleah.
func listEntries() ([]bonjour.ServiceEntry, error) { // Define some helper channels that don't have to survive the function finished := make(chan bool) // allows us to communicate that the reading has been completed errs := make(chan error) // allows us to communicate that an error has occurred defer func() { ...
csn
Get a scoped query for the pivot table. @param \Illuminate\Database\Eloquent\Relations\BelongsToMany $relation @return \Illuminate\Database\Query\Builder
protected function newPivotQuery(BelongsToMany $relation) { $query = $relation->newPivotStatement()->where( $this->getForeignPivotKeyName($relation), $relation->getParent()->getKey() ); return Models::scope()->applyToRelationQuery( $query, $relation->getT...
csn
For testing only. @param CloudFrontClient $client
public function setClient($client) { if (!$client instanceof CloudFrontClient) { @trigger_error('The '.__METHOD__.' expects a CloudFrontClient as parameter.', E_USER_DEPRECATED); } $this->client = $client; }
csn
condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer
def compose(self, data): """ condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer """ g = self.__separate(data) if self.__cgr_type in (1, 2, 3, 4, 5, 6) else self.__condense(data) g.meta.upda...
csn
glyphicon for task status; requires bootstrap
def status_icon(self): 'glyphicon for task status; requires bootstrap' icon = self.status_icon_map.get(self.status.lower(), self.unknown_icon) style = self.status_style.get(self.status.lower(), '') return mark_safe( '<span class="glyphi...
csn
Gets the corresponding error code of an Alluxio exception. @param e an Alluxio exception @return the corresponding error code
private static int getAlluxioErrorCode(AlluxioException e) { try { throw e; } catch (FileDoesNotExistException ex) { return -ErrorCodes.ENOENT(); } catch (FileAlreadyExistsException ex) { return -ErrorCodes.EEXIST(); } catch (InvalidPathException ex) { return -ErrorCodes.EFAULT()...
csn
update an item by id @param {String} data The new data @param {Function} done The callback when done
function(data, done) { if(!this._key) { done('no key found for metadata'); return; } var key = data[this._key]; var self = this; this._getCollection(function(err) { if(err) { done(err); } var kobj = {}; kobj[self._key.getName()] = k...
csn
Performs full review data validation @param array $submitted @param array $options @return array|boolean
public function review(array &$submitted, array $options = array()) { $this->options = $options; $this->submitted = &$submitted; $this->validateReview(); $this->validateBool('status'); $this->validateTextReview(); $this->validateCreatedReview(); $this->valida...
csn
read in a single task element @param el @return matching task to Element @throws PageException
private ScheduleTaskImpl readInTask(Element el) throws PageException { long timeout = su.toLong(el, "timeout"); if (timeout > 0 && timeout < 1000) timeout *= 1000; if (timeout < 0) timeout = 600000; try { ScheduleTaskImpl st = new ScheduleTaskImpl(this, su.toString(el, "name").trim(), su.toResource(config, el,...
csn
Sets legend position. Default is 'r'. b - At the bottom of the chart, legend entries in a horizontal row. bv - At the bottom of the chart, legend entries in a vertical column. t - At the top of the chart, legend entries in a horizontal row. tv - At the top of the chart, legend entries i...
def set_legend_position(self, legend_position): """Sets legend position. Default is 'r'. b - At the bottom of the chart, legend entries in a horizontal row. bv - At the bottom of the chart, legend entries in a vertical column. t - At the top of the chart, legend entries in a horizontal ...
csn
r""" Set the working directory to ``path``\ . All relative paths will be resolved relative to it. :type path: str :param path: the path of the directory :raises: :exc:`~exceptions.IOError`
def set_working_directory(self, path): r""" Set the working directory to ``path``\ . All relative paths will be resolved relative to it. :type path: str :param path: the path of the directory :raises: :exc:`~exceptions.IOError` """ _complain_ifclosed(self...
csn
Implement pep8 'ignore_code' hook.
def putty_ignore_code(options, code): """Implement pep8 'ignore_code' hook.""" reporter, line_number, offset, text, check = get_reporter_state() try: line = reporter.lines[line_number - 1] except IndexError: line = '' options.ignore = options._orig_ignore options.select = option...
csn
Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if the character is a hyphen '-'. Different letters for the qubit specify ...
def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]: """Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if th...
csn
Return the mutants created by Gaussian mutation on the candidates. This function performs Gaussian mutation. This function makes use of the bounder function as specified in the EC's ``evolve`` method. .. Arguments: random -- the random number generator object candidate -- the candidat...
def gaussian_mutation(random, candidate, args): """Return the mutants created by Gaussian mutation on the candidates. This function performs Gaussian mutation. This function makes use of the bounder function as specified in the EC's ``evolve`` method. .. Arguments: random -- the random n...
csn
// Parse collection of historical prices.
func parseHistorical(data [][]string) ([]PriceH, error) { // This is the list of prices with allocated space. Length of space should // subtracted by 1 because the first row of data is title. var list = make([]PriceH, len(data)-1) // We need to leave the first row, because it contains title of columns. for k, v :=...
csn
// NewAuth returns a pointer to an initialized Auth
func NewAuth(r *Robot) *Auth { a := &Auth{robot: r} c := &authConfig{} env.MustProcess(c) if c.Enabled { if c.Admins != "" { a.admins = strings.Split(c.Admins, ",") } r.Handle( addUserRoleHandler, removeUserRoleHandler, listUserRolesHandler, listAdminsHandler, ) } return a }
csn
// BoolArray adds an array of bool to the event.
func BoolArray(name string, values []bool) FieldOpt { return func(em *eventMetadata, ed *eventData) { em.writeArray(name, inTypeUint8, outTypeBoolean, 0) ed.writeUint16(uint16(len(values))) for _, v := range values { bool8 := uint8(0) if v { bool8 = uint8(1) } ed.writeUint8(bool8) } } }
csn
True if the given identifier is part of a type reference
function isTypeReferenceIdentifier(entityName) { var node = entityName; while (node.parent && node.parent.kind === 139 /* QualifiedName */) { node = node.parent; } return node.parent && (node.parent.kind === 155 /* TypeReference */ || node.parent.kind === ...
csn
Serves the Swagger description of the REST API. As host, fills in the host where the controller lives. As options for the entity names, contains only those entity names that the user can actually see.
@GetMapping(value = "/swagger.yml", produces = "text/yaml") public String swagger(Model model, HttpServletResponse response) { response.setContentType("text/yaml"); response.setCharacterEncoding("UTF-8"); final UriComponents uriComponents = ServletUriComponentsBuilder.fromCurrentContextPath().buil...
csn
Convert a request token to an access token @param string $token @return mixed
public function processRequestToken($token) { // Setup the params $params = [ 'client_id' => $this->clientID, 'client_secret' => $this->secret, 'code' => $token, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->re...
csn
Factory method which uses the parameters to retrieve all matching instances from the database @param string $table The table to retrieve from @param string $classname The name of the class to instantiate @param array $params An array of conditions like $fieldname => $fieldvalue @return array|bool Array of object insta...
public static function fetch_all_helper($table, $classname, $params) { global $DB; // Need to introspect DB here. $instance = new $classname(); $classvars = (array)$instance; $params = (array)$params; $wheresql = array(); $newparams = array(); $columns = $D...
csn
// Query returns the set of releases that match the provided set of labels
func (mem *Memory) Query(keyvals map[string]string) ([]*rspb.Release, error) { defer unlock(mem.rlock()) var lbs labels lbs.init() lbs.fromMap(keyvals) var ls []*rspb.Release for _, recs := range mem.cache { recs.Iter(func(_ int, rec *record) bool { // A query for a release name that doesn't exist (has be...
csn
To enable "run out of the box for testing".
private static String[] prepareDefaultConf() throws IOException { final File templateFolder = new File("test/local-conf-templates"); final File localConfFolder = new File("local/conf"); if (!localConfFolder.exists()) { FileUtils.copyDirectory(templateFolder, localConfFolder.getParentFile()); log...
csn
// SetReconnectHandler will set the reconnect event handler.
func (nc *Conn) SetReconnectHandler(rcb ConnHandler) { if nc == nil { return } nc.mu.Lock() defer nc.mu.Unlock() nc.Opts.ReconnectedCB = rcb }
csn
Returns reverse relational data @param int $many @return array
public function getReverseRelations($many = -1) { $results = []; $name = $this->getName(); $payload = cradle()->makePayload(); cradle()->trigger( 'system-schema-search', $payload['request'], $payload['response'] ); $rows = $paylo...
csn
Removes a group from the vector QueryControllerEntity
public void removeGroup(String groupId) { for (Iterator<QueryControllerEntity> iterator = entities.iterator(); iterator.hasNext();) { Object temporal = iterator.next(); if (!(temporal instanceof QueryControllerGroup)) { continue; } QueryControllerGroup element = (QueryControllerGroup) temporal; if ...
csn
// gtk_combo_box_get_popup_accessible // gtk_combo_box_get_row_separator_func // gtk_combo_box_set_row_separator_func
func (v *ComboBox) SetAddTearoffs(add_tearoffs bool) { C.gtk_combo_box_set_add_tearoffs(COMBO_BOX(v), gbool(add_tearoffs)) }
csn
// MarshalDateTime marshals time.Time to SOAP "dateTime" type. Note that this // converts to local time.
func MarshalDateTime(v time.Time) (string, error) { return v.In(localLoc).Format("2006-01-02T15:04:05"), nil }
csn
Save resource to json or yaml file @param [String] file_path The full path to the file @param [Symbol] format The format. Options: [:json, :yml, :yaml]. Defaults to .json @note If a .yml or .yaml file extension is given in the file_path, the format will be set automatically @return [True] The Resource was saved suc...
def to_file(file_path, format = :json) format = :yml if %w[.yml .yaml].include? File.extname(file_path) temp_data = { type: self.class.name, api_version: @api_version, data: @data } case format.to_sym when :json File.open(file_path, 'w') { |f| f.write(JSON.pretty_generate(temp_data)) } ...
csn
Recursively lists bunch of directories. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Yields: (subject<->children urns) tuples...
def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME): """Recursively lists bunch of directories. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, ...
csn
Make sure directory exist, create it if not.
private static boolean makeSureExists(File dir) { // Make sure the dest directories exist. if (!dir.exists()) { if (!dir.mkdirs()) { Log.error("Could not create the directory "+dir.getPath()); return false; } } return true; }
csn
Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates name : str Name of your custom template to use for re...
def from_custom_template(cls, searchpath, name): """ Factory function for creating a subclass of ``Styler`` with a custom template and Jinja environment. Parameters ---------- searchpath : str or list Path or paths of directories containing the templates ...
csn
Load countries. @return \PragmaRX\Coollection\Package\Coollection
public function loadCountries() { $this->countriesJson = $this->loadCountriesJson(); $overload = $this->helper->loadJsonFiles($this->helper->dataDir('countries/overload'))->mapWithKeys(function ($country, $code) { return [upper($code) => $country]; }); $this->countriesJ...
csn
Query for page by title
def fetch_page(self, title, method='GET'): """ Query for page by title """ params = { 'prop': 'revisions', 'format': 'json', 'action': 'query', 'explaintext': '', 'titles': title, 'rvprop': 'content' } ...
csn
Updates the schema version in the database. @param version the version to set the schema to @throws SQLException a SQLException @since 1.2.0
public void updateSchemaVersion(VersionComparator version) throws SQLException { PreparedStatement statement = null; PreparedStatement updateStatement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\"");...
csn
Reports a mandatory note to the log. If mandatory notes are not being enforced, treat this as an ordinary note.
private void logMandatoryNote(JavaFileObject file, String msg, Object... args) { if (enforceMandatory) log.mandatoryNote(file, msg, args); else log.note(file, msg, args); }
csn
Filter subdirs that have already been visited. This is used to avoid loops in the search performed by os.walk() in index_files_by_size. curr_dir is the path of the current directory, as returned by os.walk(). subdirs is the list of subdirectories for the current directory, as returned by os.walk(...
def filter_visited(curr_dir, subdirs, already_visited, follow_dirlinks, on_error): """Filter subdirs that have already been visited. This is used to avoid loops in the search performed by os.walk() in index_files_by_size. curr_dir is the path of the current directory, as returned by os.walk(). su...
csn
// MinFactory returns function check minimum value.
func MinFactory(e *MinErrorOption) ValidationFunc { if e == nil { e = &MinErrorOption{} } if e.UnsupportedTypeErrorOption == nil { e.UnsupportedTypeErrorOption = &UnsupportedTypeErrorOption{UnsupportedTypeError} } if e.ParamParseErrorOption == nil { e.ParamParseErrorOption = &ParamParseErrorOption{ParamParse...
csn
Returns tuple key rect of below left cell
def get_below_left_key_rect(self): """Returns tuple key rect of below left cell""" key_left = self.row, self.col - 1, self.tab key_below_left = self.row + 1, self.col - 1, self.tab border_width_right = \ float(self.cell_attributes[key_below_left]["borderwidth_right"]) \ ...
csn
Add the required HTML to the parsed content for in-line editing, such as the icon and edit form if the object is deemed to be editable - either it has an ``editable`` method which returns ``True``, or the logged in user has change permissions for the model.
def editable(parsed, context, token): """ Add the required HTML to the parsed content for in-line editing, such as the icon and edit form if the object is deemed to be editable - either it has an ``editable`` method which returns ``True``, or the logged in user has change permissions for the mod...
csn
Creates the upload dir if needed.
@VisibleForTesting static void createUploadDir(final Path uploadDir, final Logger log, final boolean initialCreation) throws IOException { if (!Files.exists(uploadDir)) { if (initialCreation) { log.info("Upload directory {} does not exist. " + uploadDir); } else { log.warn("Upload directory {} has been...
csn
Execute an operation with the store. This method enforces thread safety based on the store factory. @param storeOperation The store. @param rootModule The root module to use for store initialization. @throws MojoExecutionException On execution errors. @throws MojoFailureException On execution failures.
protected void execute(StoreOperation storeOperation, MavenProject rootModule, Set<MavenProject> executedModules) throws MojoExecutionException, MojoFailureException { synchronized (cachingStoreProvider) { Store store = getStore(rootModule); if (isResetStoreBeforeExecution() ...
csn
// generateMacAddress returns net.HardwareAddr filled with fixed 3 byte prefix // complemented by 3 random bytes.
func generateMacAddress() (net.HardwareAddr, error) { mac := []byte{ 2, // locally administered unicast 0x65, 0x02, // OUI (randomly chosen by jell) 0, 0, 0, // bytes to randomly overwrite } _, err := rand.Read(mac[3:6]) if err != nil { return nil, errwrap.Wrap(errors.New("cannot generate random m...
csn
Returns the xml object corresponding to the league Only designed for internal use
def __get_league_object(): """Returns the xml object corresponding to the league Only designed for internal use""" # get data data = mlbgame.data.get_properties() # return league object return etree.parse(data).getroot().find('leagues').find('league')
csn
// Float has the same behaviour as String but converts the response to float.
func (self *Config) Float(section string, option string) (value float64, err error) { sv, err := self.String(section, option) if err == nil { value, err = strconv.ParseFloat(sv, 64) } return value, err }
csn
Add a NOT BETWEEN WHERE condition. @param string $column column name @param mixed $min minimum value @param mixed $max maximum value @param string $connector optional logical connector, default AND @param bool|null $quote optional auto-escape value, default to global @return Miner
public function whereNotBetween($column, $min, $max, $connector = self::LOGICAL_AND, $quote = null) { return $this->criteriaNotBetween($this->where, $column, $min, $max, $connector, $quote); }
csn
Extracts the import zip contents. @param string $zipfilepath Zip file path @return array [0] => \stdClass, [1] => string
public function extract_import_contents(string $zipfilepath) : array { $importtempdir = make_request_directory('analyticsimport' . microtime(false)); $zip = new \zip_packer(); $filelist = $zip->extract_to_pathname($zipfilepath, $importtempdir); if (empty($filelist[self::CONFIG_FILE_NA...
csn
Returns the descriptors of database-based datastore types available in DataCleaner.
public List<DatastoreDescriptor> getAvailableDatabaseBasedDatastoreDescriptors() { final List<DatastoreDescriptor> availableCloudBasedDatabaseDescriptors = new ArrayList<>(); availableCloudBasedDatabaseDescriptors.add(POSTGRESQL_DATASTORE_DESCRIPTOR); availableCloudBasedDatabaseDescriptors.add(...
csn
Draws a circle with the specified diameter using the given point coordinates as center and fills it with the current color of the graphics context. @param g Graphics context @param centerX X coordinate of circle center @param centerY Y coordinate of circle center @param diam Circle diameter
public static void fillCircle(Graphics g, int centerX, int centerY, int diam){ g.fillOval((int) (centerX-diam/2), (int) (centerY-diam/2), diam, diam); }
csn
Determines what parent array object to get based on the directive used. @param array $objectSchema @param string $schemaName @return array @throws SchemaParserException
protected function getParentSchemaObject(array $objectSchema, $schemaName) { if (isset($objectSchema['extends_default'])) { $parent = $this->getExtendedDefaultSchemaObject($objectSchema); } elseif (isset($objectSchema['extends']) && is_string($objectSchema['extends'])) { $par...
csn
Test if two disk elements should be considered like the same device
def _disks_equal(disk1, disk2): ''' Test if two disk elements should be considered like the same device ''' target1 = disk1.find('target') target2 = disk2.find('target') source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None source2 = ElementTree.t...
csn
Gets the table definition for the specified table name from the tableDefinitions object @private
function getTableDefinition(tableDefinitions, tableName) { Validate.isObject(tableDefinitions); Validate.notNull(tableDefinitions); Validate.isString(tableName); Validate.notNullOrEmpty(tableName); return tableDefinitions[tableName.toLowerCase()]; }
csn
Write a file with the PID of this server instance. Call when setting up a command line testserver.
def write_pid_file(): """Write a file with the PID of this server instance. Call when setting up a command line testserver. """ pidfile = os.path.basename(sys.argv[0])[:-3] + '.pid' # strip .py, add .pid with open(pidfile, 'w') as fh: fh.write("%d\n" % os.getpid()) fh.close()
csn
Link Node Dataset File Read from File Method
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Link Node Dataset File Read from File Method """ # Set file extension property self.fileExtension = extension # Dictionary of keywords/cards and parse...
csn
Converts a timetuple, integer or datetime object into the seconds from epoch in utc.
def _date_to_unix(arg): """Converts a timetuple, integer or datetime object into the seconds from epoch in utc. """ if isinstance(arg, datetime): arg = arg.utctimetuple() elif isinstance(arg, integer_types + (float,)): return int(arg) year, month, day, hour, minute, second = arg[...
csn
Returns true if the parameter has a namespace and value, false if not. @param p Parameter
private static boolean validParameter(final Parameter p) { if (p.getNamespace() == null) { return false; } if (p.getValue() == null) { return false; } return true; }
csn
Determines if a tool is enabled or not @param $toolName @return bool
public function toolEnabled($toolName) { if (isset($this->tools[$toolName])) return $this->tools[$toolName]->enabled(); return false; }
csn
Handles the trash-delete migration action
protected function delete($step) { $itemsCollection = $this->matchItems('delete', $step); $this->setReferences($itemsCollection, $step); $trashService = $this->repository->getTrashService(); foreach ($itemsCollection as $key => $item) { $trashService->deleteTrashItem($i...
csn
Validates the csrf token in the HTTP request. This method should be called in the beginning of the request. By default, POST, PUT and DELETE requests will be validated for a valid CSRF token. If the request does not provide a valid CSRF token, this method will kill the script and send a HTTP 400 (bad request) response...
public function validateRequest($throw = false) { // Ensure that the actual token is generated and stored $this->getTrueToken(); if (!$this->isValidatedRequest()) { return true; } if (!$this->validateRequestToken()) { if ($throw) { th...
csn
plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter Args: another PhononBSPl...
def plot_compare(self, other_plotter): """ plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the Ph...
csn
Adds the values of the existing config to the config dictionary.
def append_existing_values(schema, config): """ Adds the values of the existing config to the config dictionary. """ for section_name in config: for option_name in config[section_name]: option_value = config[section_name][option_name] # Note that we must preserve existi...
csn
Helps prevent 'path traversal' attacks @param $filename @param $directory @return bool
static public function isFileInsideDirectory($filename, $directory) { $canonicalDirectory = realpath($directory); if (false === $canonicalDirectory) { return false; } $canonicalFilename = realpath($canonicalDirectory . DIRECTORY_SEPARATOR . $filename); if (false =...
csn
Removes a component from the lifecycle. This is generally not used.
public void removeComponent (BaseComponent comp) { if (_initers != null && comp instanceof InitComponent) { _initers.remove((InitComponent)comp); } if (_downers != null && comp instanceof ShutdownComponent) { _downers.remove((ShutdownComponent)comp); } }
csn
Hide the loading layer
function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }
csn
Run the bot
public function run() { $received = $this->request->getReceivedData(); if (!$received || empty($received['object']) || $received['object'] != 'page') { return; } $this->received = $received; if (!isset($received['entry'])) { return; } ...
csn
Creates the SSL context needed to create the socket factory used by this factory. The key and trust store parameters are optional. If they are null then the JRE defaults will be used. @return the newly created SSL context @throws ClientSslSocketFactoryException if an error is detected loading the specified key or trus...
private SSLContext createSSLContext() throws ClientSslSocketFactoryException { final KeyManager[] keyManagers = this.keyStore != null ? createKeyManagers() : null; final TrustManager[] trustManagers = this.trustStore != null ? createTrustManagers() : null; try { final SSLContext ssl...
csn
// Stop stops all scheduler processes for the master
func (s *scheduler) Stop() { s.Lock() defer s.Unlock() if !s.started { return } close(s.shutdown) <-s.stopped }
csn
// TimeToDate converts a golang Time to a Date.
func TimeToDate(t time.Time) *google_type.Date { return NewDate(int32(t.Month()), int32(t.Day()), int32(t.Year())) }
csn
Set the cluster key. @param fields the fields @return the table metadata builder
@TimerJ public TableMetadataBuilder withClusterKey(String... fields) { for (String field : fields) { clusterKey.add(new ColumnName(tableName, field)); } return this; }
csn
Generate a store key. @param string|string[] $ident The metadata identifier(s) to convert. @return string
public function serializeMetaKey($ident) { if (is_array($ident)) { sort($ident); $ident = implode(':', $ident); } return md5($ident); }
csn
Refreshes the contents tab with the latest selection from the browser.
def refreshContents( self ): """ Refreshes the contents tab with the latest selection from the browser. """ item = self.uiContentsTREE.currentItem() if not isinstance(item, XdkEntryItem): return item.load() url = item.url() if url:...
csn
Get the annotation entries from an edge data dictionary.
def _get_annotation_entries_from_data(self, graph: BELGraph, data: EdgeData) -> Optional[List[NamespaceEntry]]: """Get the annotation entries from an edge data dictionary.""" annotations_dict = data.get(ANNOTATIONS) if annotations_dict is not None: return [ entry ...
csn
Returns the batch size used for insert_records. This method tries to find the best batch size without getting into dml internals. Maximum 1000 records to save memory. @return int
private static function get_insert_batch_size(): int { global $DB; $dbconfig = $DB->export_dbconfig(); // 500 is pgsql default so using 1000 is fine, no other db driver uses a hardcoded value. if (empty($dbconfig) || empty($dbconfig->dboptions) || empty($dbconfig->dboptions['bulkinsert...
csn
%prog refallele vcffile > out.refAllele Make refAllele file which can be used to convert PLINK file to VCF file.
def refallele(args): """ %prog refallele vcffile > out.refAllele Make refAllele file which can be used to convert PLINK file to VCF file. """ p = OptionParser(refallele.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args ...
csn
// ContainerWait mocks base method
func (m *MockContainerAPIClient) ContainerWait(ctx context.Context, container string) (int64, error) { ret := m.ctrl.Call(m, "ContainerWait", ctx, container) ret0, _ := ret[0].(int64) ret1, _ := ret[1].(error) return ret0, ret1 }
csn
// Equal returns true if the two Currencies are the same
func (c CurrSymbol) Equal(o CurrSymbol) bool { return c.String() == o.String() }
csn