query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
// ListBlockedModels returns a list of all models on the controller // which have a block in place. The resulting slice is sorted by model // name, then owner. Callers must be controller administrators to retrieve the // list.
func (c *ControllerAPI) ListBlockedModels() (params.ModelBlockInfoList, error) { results := params.ModelBlockInfoList{} if err := c.checkHasAdmin(); err != nil { return results, errors.Trace(err) } blocks, err := c.state.AllBlocksForController() if err != nil { return results, errors.Trace(err) } modelBlock...
csn
r""" Iteratively yeilds individual configuration points inside a defined basis. Args: grid_basis (list): a list of 2-component tuple. The named tuple looks like this: CommandLine: python -m utool.util_gridsearch --test-grid_search_generator Example: >>> # ENABL...
def grid_search_generator(grid_basis=[], *args, **kwargs): r""" Iteratively yeilds individual configuration points inside a defined basis. Args: grid_basis (list): a list of 2-component tuple. The named tuple looks like this: CommandLine: python -m utool.util_gridsearch...
csn
Binds a property to Hibernate runtime meta model. Deals with cascade strategy based on the Grails domain model @param grailsProperty The grails property instance @param prop The Hibernate property @param mappings The Hibernate mappings
protected void bindProperty(PersistentProperty grailsProperty, Property prop, InFlightMetadataCollector mappings) { // set the property name prop.setName(grailsProperty.getName()); if (isBidirectionalManyToOneWithListMapping(grailsProperty, prop)) { prop.setInsertable(false); ...
csn
Selects a virtual server by UDP port to allow further interaction. @param integer $port @param boolean $virtual @return void
public function serverSelectByPort($port, $virtual = null) { if($this->whoami !== null && $this->serverSelectedPort() == $port) return; $virtual = ($virtual !== null) ? $virtual : $this->start_offline_virtual; $getargs = func_get_args(); $this->execute("use", array("port" => $port, $virtual ?...
csn
Test for well-formedness of a chord label. Parameters ---------- chord : str Chord label to validate.
def validate_chord_label(chord_label): """Test for well-formedness of a chord label. Parameters ---------- chord : str Chord label to validate. """ # This monster regexp is pulled from the JAMS chord namespace, # which is in turn derived from the context-free grammar of # Hart...
csn
Reduce the size of this block :param int new_size: The new size :return: None
def shrink(self, new_size): """ Reduce the size of this block :param int new_size: The new size :return: None """ self.size = new_size if self.sort == 'string': self.null_terminated = False # string without the null byte terminator self._...
csn
// Creates a zk node only if it does not exist.
func (z *zookeeperKV) Create( key string, val interface{}, ttl uint64, ) (*kvdb.KVPair, error) { if ttl != 0 { return nil, kvdb.ErrTTLNotSupported } bval, err := common.ToBytes(val) if err != nil { return nil, err } if len(bval) == 0 { return nil, kvdb.ErrEmptyValue } err = z.createFullPath(key, fals...
csn
Validate instance passwords
def validate_instance_password(self, password): ''' Validate instance passwords ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', password) is not None: if len(password) <= 41 and len(password) >= ...
csn
// SetFullLoadErrorPercentage sets the FullLoadErrorPercentage field's value.
func (s *ElasticsearchSettings) SetFullLoadErrorPercentage(v int64) *ElasticsearchSettings { s.FullLoadErrorPercentage = &v return s }
csn
Get a Translation from Zanata using the Zanata Document ID and Locale. @param id The ID of the document in Zanata. @param locale The locale of the translation to find. @return null if the translation doesn't exist or an error occurred, otherwise the TranslationResource containing the Translation Strings (TextFlowT...
public TranslationsResource getTranslations(final String id, final LocaleId locale) throws NotModifiedException { ClientResponse<TranslationsResource> response = null; try { final ITranslatedDocResource client = proxyFactory.getTranslatedDocResource(details.getProject(), details.getVersion()...
csn
Downloads all data files associated with the game specified by the game id passed in.
def download_all_for_game(gid) download_xml_for_game(gid) download_batters_for_game(gid) download_inning_for_game(gid) download_media_for_game(gid) download_notification_for_game(gid) download_onbase_for_game(gid) download_pitchers_for_game(gid) end
csn
Writes the PDF data into ``file_``. Note that ``file_`` can actually be a Django Response object as well. This function may be used as a helper that can be used to save a PDF file to a file (or anything else outside of a request/response cycle), eg:: :param str html: A rendered HTML. :param file f...
def render_pdf( template, file_, url_fetcher=staticfiles_url_fetcher, context=None, ): """ Writes the PDF data into ``file_``. Note that ``file_`` can actually be a Django Response object as well. This function may be used as a helper that can be used to save a PDF file to a file (o...
csn
Build quantifier from parameters @param int|null $min @param float|int $max @param bool $lazyLoad @return string
public static function fetchQuantifier($min = null, $max = INF, bool $lazyLoad = false) : string { $lazy = $lazyLoad ? '?' : ''; switch (true) { case ($min === 0 && $max === 1): return '?'.$lazy; case ($min === 0 && $max === INF): return '*'.$...
csn
Returns the uri for internal Zend_Service_Amazon_S3 use. @param string $filename @return string
protected function _getUri($filename): string { $this->_verifyPath(); // Note: AWS SDK does not want the URI to start with a slash, as opposed to the old Zend // Framework implementation. $path = trim($this->_config['path'], '/'); return $path . '/' . $filename; }
csn
// AppendUints64 encodes the input uint64s to json and // appends the encoded string list to the input byte slice.
func (Encoder) AppendUints64(dst []byte, vals []uint64) []byte { if len(vals) == 0 { return append(dst, '[', ']') } dst = append(dst, '[') dst = strconv.AppendUint(dst, vals[0], 10) if len(vals) > 1 { for _, val := range vals[1:] { dst = strconv.AppendUint(append(dst, ','), val, 10) } } dst = append(dst...
csn
Hydrate the subject with data @param HydrationEvent $event @param string $eventName @param EventDispatcherInterface $eventDispatcher @return \Tmdb\Model\AbstractModel
public function hydrate(HydrationEvent $event, $eventName, $eventDispatcher) { // Possibility to load serialized cache $eventDispatcher->dispatch(TmdbEvents::BEFORE_HYDRATION, $event); if ($event->isPropagationStopped()) { return $event->getSubject(); } $subject...
csn
Delete a Contact by ID @param integer $id @return boolean
public function delete($id) { $data = $this->findById($id); $this->client ->DebtorContact_Delete(array( "debtorContactHandle" => $data->Handle )); return true; }
csn
// NewWorker calls NewFlagWorker but returns a more convenient type. It's // a suitable default value for ManifoldConfig.NewWorker.
func NewWorker(config FlagConfig) (worker.Worker, error) { worker, err := NewFlagWorker(config) if err != nil { return nil, errors.Trace(err) } return worker, nil }
csn
list of words not to let the parser use stops praser returning implied dates against server local time
function constainRestrictedWords(text) { var i, restictedWords = ['today', 'tomorrow', 'yesterday', 'tonight']; text = text.toLowerCase(); i = restictedWords.length; while (i--) { if (text.indexOf(restictedWords[i]) > -1) { return true; } } return false; }
csn
// SetP10 sets the P10 field's value.
func (s *Latency) SetP10(v float64) *Latency { s.P10 = &v return s }
csn
Decorate the results object with the mutation score for each directory. @param {object} results - (part of) mutation testing results, decorated with mutation stats @returns {object} - Mutation test results decorated with mutation scores
function addMutationScores(results) { _.forOwn(results, function(result) { if(_.has(result, 'stats')) { addMutationScores(result); } }); results.mutationScore = getMutationScore(results.stats); return results; }
csn
Returns the document being processed. If the scraper was created with a URL, this method will attempt to retrieve the page and parse it. If the scraper was created with a string, this method will attempt to parse the page. Be advised that calling this method may raise an exception (HTTPError or HTMLParseError)...
def document if @document.is_a?(URI) # Attempt to read page. May raise HTTPError. options = {} READER_OPTIONS.each { |key| options[key] = option(key) } request(@document, options) end if @document.is_a?(String) # Parse the page. May raise HTMLParseError. ...
csn
Check fb photo title against provided title, returns true if they match
def _title_uptodate(self,fullfile,pid,_title): """Check fb photo title against provided title, returns true if they match""" i=self.fb.get_object(pid) if i.has_key('name'): if _title == i['name']: return True return False
csn
Deletes an entire addressbook and all its contents. @param int $addressBookId
public function deleteAddressBook($addressBookId) { $stmt = $this->pdo->prepare('DELETE FROM '.$this->cardsTableName.' WHERE addressbookid = ?'); $stmt->execute([$addressBookId]); $stmt = $this->pdo->prepare('DELETE FROM '.$this->addressBooksTableName.' WHERE id = ?'); $stmt->execut...
csn
Removes an object from the set. @param object the object to remove @return true if the object is in the set and removed successfully, otherwise false
@Override public boolean remove(Object object) { if (object == null) { return false; } // Locking this object protects against removing the exact object that might be in the // process of being added, but does not protect against removing a distinct, but equivalent // object. synchronize...
csn
Evaluate if the module must be included in the Odoo addons. :param string module: the name of the module :rtype: bool
def _is_module_included(self, module): """Evaluate if the module must be included in the Odoo addons. :param string module: the name of the module :rtype: bool """ if module in self.exclude_modules: return False if self.include_modules is None: r...
csn
// HostsWithoutPort strips the port from each HostPort, returning just // the addresses.
func HostsWithoutPort(hps []HostPort) []Address { addrs := make([]Address, len(hps)) for i, hp := range hps { addrs[i] = hp.Address } return addrs }
csn
Run a query to completion. @param string[] $params Query parameters @param string $contName Result subelement name for continue details @param string $resName Result element name for main results array @param string $pageIdName Result element name for page ID @param bool $cont Whether to continue the query, using mult...
protected function runQuery( $params, $contName, $resName, $pageIdName = 'pageid', $cont = true ) { $pages = new Pages(); $negativeId = -1; do { // Set up continue parameter if it's been set already. if ( isset( $result['continue'][$contName] ) ) { $params[$contName] = $result['continue'][$contName]; ...
csn
The 'url' constraint - field value must be a valid URL. @return constraint
public static Constraint url() { return new Constraint("url", simplePayload("url")) { public boolean isValid(Object actualValue) { if (actualValue != null) { if (!Utils.isValidURL(actualValue.toString())) { return false; } } return true; } }; }
csn
// NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider.
func NewGRPCService(endpoint string, callTimeout time.Duration) (Service, error) { klog.V(4).Infof("Configure KMS provider with endpoint: %s", endpoint) addr, err := parseEndpoint(endpoint) if err != nil { return nil, err } connection, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grp...
csn
Tries to isolate the smallest config that reproduces a problem @param {string} text The source text to lint @param {Object} config A config object that causes a crash or autofix error @param {("crash"|"autofix")} problemType The type of problem that occurred @returns {Object} A config object with only one rule enabled ...
function isolateBadConfig(text, config, problemType) { for (const ruleId of Object.keys(config.rules)) { const reducedConfig = Object.assign({}, config, { rules: { [ruleId]: config.rules[ruleId] } }); let fixResult; try { fixResult = linter.verifyAndFix(text,...
csn
Set options. @param kwargs: keyword arguments. @see: L{Options}
def set_options(self, **kwargs): """ Set options. @param kwargs: keyword arguments. @see: L{Options} """ p = Unskin(self.options) p.update(kwargs)
csn
get LinkHeader instance from response @param \Symfony\Component\HttpFoundation\Response $response response to get header from @return LinkHeader
public static function fromResponse(Response $response) { $header = $response->headers->get('Link'); if (is_array($header)) { implode(',', $header); } return self::fromString($header); }
csn
In Symfony applications is common to have lots of consecutive "translation not found" log messages. This method combines them all to generate a more compact output. @param array $records @param int $currentRecordIndex @return string
private function processTranslationLogRecord(array $records, $currentRecordIndex) { $record = $records[$currentRecordIndex]; if (isset($records[$currentRecordIndex - 1]) && $this->isTranslationLog($records[$currentRecordIndex - 1])) { $record['_properties']['display_log_info'] = false; ...
csn
Deletes the access host.
public function delete() { $this->getContext()->invokeApiPost('DATABASES', [ 'action' => 'accesshosts', 'delete' => 'yes', 'db' => $this->database->getDatabaseName(), 'select0' => $this->getName(), ]); $this->database->clearCache(); }
csn
Checks if the given source and target elements are related considering the defined relation and the temp. @param source source @param target target @param relation relation @return true if the relation holds between source and target, false otherwise.
private boolean isRelated(final INode source, final INode target, final char relation) { return relation == defautlMappings.getRelation(source, target); }
csn
Instantiate the correct builder class from a given filter array. @param array $filter The filter. @param FilterBuilder $builder The builder instance. @return BaseFilterBuilder @throws DcGeneralInvalidArgumentException When an invalid operation is encountered.
public static function getBuilderFromArray($filter, $builder) { switch ($filter['operation']) { case 'AND': return AndFilterBuilder::fromArray($filter, $builder); case 'OR': return OrFilterBuilder::fromArray($filter, $builder); case '=': ...
csn
// MkdirAll makes a directory and any intervening directories with the // permissions specified by the core.sharedRepository setting.
func MkdirAll(path string, config repositoryPermissionFetcher) error { umask := 0777 & ^config.RepositoryPermissions(true) return doWithUmask(int(umask), func() error { return os.MkdirAll(path, config.RepositoryPermissions(true)) }) }
csn
Create a new array and add it to the pool for the specified length. @param {number} length The length of the array to create. @return {Array} The new array.
function create(length) { var array = new Array(length); // Create a non-enumerable property as a flag to know if the array is in use Object.defineProperties(array, { inUse: { enumerable: false, writable: true, value: false }, originalLength: { enumerable: false, value: ...
csn
Intercept the call with the registered interceptors for the client @param array $interceptors @param \Google\Protobuf\Internal\Message $request @param string $method @param array $metadata @param array $options @param callable $callback @return mixed
private function intercept(array &$interceptors, &$request, &$method, &$metadata, &$options, callable $callback) { /** @var Client\Interceptors\Base $i */ $i = array_shift($interceptors); if ($i) { $i->setRequest($request); $i->setMethod($method); $i->setM...
csn
Break a result set into subsets with the same keys. :param rs: Result set, rows of a result as a list of dicts :type rs: list of dict :return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column
def result_subsets(self, rs): """Break a result set into subsets with the same keys. :param rs: Result set, rows of a result as a list of dicts :type rs: list of dict :return: A set with distinct keys (tuples), and a dict, by these tuples, of max. widths for each column """ ...
csn
Generates a form to define the values of a specific property for a resource @param core_kernel_classes_Resource $resource @param core_kernel_classes_Property $property @return tao_helpers_form_GenerisTreeForm
public static function buildTree(core_kernel_classes_Resource $resource, core_kernel_classes_Property $property) { $tree = new self($resource, $property); $range = $property->getRange(); $tree->setData('rootNode', $range->getUri()); $tree->setData('dataUrl', _url('getData', 'GenerisTree', 'tao')); $tree-...
csn
Callback when the MQTT client is connected. :param client: the client being connected. :param userdata: unused. :param flags: unused. :param result_code: result code.
def on_connect(self, client, userdata, flags, result_code): """ Callback when the MQTT client is connected. :param client: the client being connected. :param userdata: unused. :param flags: unused. :param result_code: result code. """ self.log_info("Connected wit...
csn
Prepend the given string to the current string. @param string $str String you wish to append @return $this
public function prepend($str) { $value = $this->val(); $this->val($str . $value); return $this; }
csn
// take is a utility function to consume tokens from a overall rate.Limiter and deviceLimiter. // No call to WaitN can be larger than the limiter burst size so we split it up into // several calls when necessary.
func take(waiter waiter, tokens int) { if tokens < limiterBurstSize { // This is the by far more common case so we get it out of the way // early. waiter.WaitN(context.TODO(), tokens) return } for tokens > 0 { // Consume limiterBurstSize tokens at a time until we're done. if tokens > limiterBurstSize { ...
csn
return the collation key @param name @return the collation key
public static String getCollationKey(String name) { byte [] arr = getCollationKeyInBytes(name); try { return new String(arr, 0, getKeyLen(arr), "ISO8859_1"); } catch (Exception ex) { return ""; } }
csn
Return the first argument value given in a docopt arg dict. When not given, return default.
def get_name_arg(argd, *argnames, default=None): """ Return the first argument value given in a docopt arg dict. When not given, return default. """ val = None for argname in argnames: if argd[argname]: val = argd[argname].lower().strip() break return val if v...
csn
Calculate the content for the track info field using the other fields @param array $data The field values @return string The description to save as track_info
public function calculateFieldsInfo(array $data) { if (! $this->exists) { return null; } $output = array(); foreach ($this->_fields as $key => $field) { if ($field instanceof FieldInterface) { if ($field->toTrackInfo()) { ...
csn
Try to match something on head of buffer @param string $regex @param array $out @param boolean $eatWhitespace @return boolean
protected function match($regex, &$out, $eatWhitespace = null) { $r = '/' . $regex . '/' . $this->patternModifiers; if (! preg_match($r, $this->buffer, $out, null, $this->count)) { return false; } $this->count += strlen($out[0]); if (! isset($eatWhitespace)) { ...
csn
// newInstances returns a new instances.InstancesClient.
func newInstances(c context.Context, acc, host string) instances.InstancesClient { return instances.NewInstancesPRPCClient(&prpc.Client{ C: client.NewClient(getMetadata(c), acc), Host: host, }) }
csn
Import network data from CSVs in a folder. The CSVs must follow the standard form, see pypsa/examples. Parameters ---------- csv_folder_name : string Name of folder encoding : str, default None Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python standard enc...
def import_from_csv_folder(network, csv_folder_name, encoding=None, skip_time=False): """ Import network data from CSVs in a folder. The CSVs must follow the standard form, see pypsa/examples. Parameters ---------- csv_folder_name : string Name of folder encoding : str, default Non...
csn
Function that adds a description to a model Class. :param model_class: The model class the descriptor is to be added to. :param name: The attribute name the descriptor will be assigned to. :param descriptor: The descriptor instance to be used. If none is specified it will default to ``icekit.pl...
def contribute_to_class(model_class, name='slots', descriptor=None): """ Function that adds a description to a model Class. :param model_class: The model class the descriptor is to be added to. :param name: The attribute name the descriptor will be assigned to. :param descriptor: The descriptor...
csn
Binds an array as a texture reference. <pre> CUresult cuTexRefSetArray ( CUtexref hTexRef, CUarray hArray, unsigned int Flags ) </pre> <div> <p>Binds an array as a texture reference. Binds the CUDA array <tt>hArray</tt> to the texture reference <tt>hTexRef</tt>. Any previous address or CUDA array state associated wit...
public static int cuTexRefSetArray(CUtexref hTexRef, CUarray hArray, int Flags) { return checkResult(cuTexRefSetArrayNative(hTexRef, hArray, Flags)); }
csn
Set a repository into the space alert for checking. In HPEL, the LogManager for log and the LogManager for Trace should set themselves as repositories to watch. This is done on the opening of each file. Thus, if a destination is moved, a file is rolled, or a server is started, the info will be updated @param reposito...
public synchronized void setRepositoryInfo(LogRepositoryManager manager, File repositoryLocation, long repositorySpaceNeeded) throws IllegalArgumentException { if (manager == null) throw new IllegalArgumentException("Null manager passed to LogRepositorySpaceAlert.setRepositoryInfo") ; if (repositoryLocation == nu...
csn
Enables the type conversion buttons based on selected items counts in the viewer.
private void enableButtons() { final int itemCount = this.list.getTable().getItemCount(); final boolean hasElement = itemCount > 0; IStructuredSelection selection; if (hasElement) { selection = this.list.getStructuredSelection(); final int selectionCount = selection.size(); if (selectionCount <= 0 || s...
csn
// FindRestartingPods inspects all Pods to see if they've restarted more than the threshold. logsCommandName is the name of // the command that should be invoked to see pod logs. securityPolicyCommandPattern is a format string accepting two replacement // variables for fmt.Sprintf - 1, the namespace of the current pod,...
func FindRestartingPods(g osgraph.Graph, f osgraph.Namer, logsCommandName, securityPolicyCommandPattern string) []osgraph.Marker { markers := []osgraph.Marker{} for _, uncastPodNode := range g.NodesByKind(kubegraph.PodNodeKind) { podNode := uncastPodNode.(*kubegraph.PodNode) pod, ok := podNode.Object().(*corev1....
csn
Write a blob of data to the XPI manager.
def write(self, name, data): """Write a blob of data to the XPI manager.""" if isinstance(data, StringIO): self.zf.writestr(name, data.getvalue()) else: self.zf.writestr(name, to_utf8(data))
csn
Run the api
def run(self): ''' Run the api ''' ui = salt.spm.SPMCmdlineInterface() self.parse_args() self.setup_logfile_logger() v_dirs = [ self.config['spm_cache_dir'], ] verify_env(v_dirs, self.config['user'], ...
csn
Devuelte un style de tipo "exception_trace" @param \PlanB\Beautifier\Style\StyleType $type @return null|\PlanB\Beautifier\Style\Style
public function makeExceptionTrace(StyleType $type): ?Style { if (!$type->isExceptionTrace()) { return null; } return Style::make() ->setFgColor(Color::GREEN()) ->margin(2); }
csn
Return other properties. @param renderer_base $output @return array @throws coding_exception @throws Exception
protected function get_other_values(renderer_base $output) { $values = []; $formattedbases = []; $lawfulbases = explode(',', $this->persistent->get('lawfulbases')); if (!empty($lawfulbases)) { foreach ($lawfulbases as $basis) { if (empty(trim($basis))) { ...
csn
Returns standard URL to category @param int $iLang language @param array $aParams additional params to use [optional] @return string
public function getStdLink($iLang = null, $aParams = []) { if (isset($this->oxcategories__oxextlink) && $this->oxcategories__oxextlink->value) { return \OxidEsales\Eshop\Core\Registry::getUtilsUrl()->processUrl($this->oxcategories__oxextlink->value, true); } if ($iLang === null)...
csn
// NewPetList creates a new http.Handler for the pet list operation
func NewPetList(ctx *middleware.Context, handler PetListHandler) *PetList { return &PetList{Context: ctx, Handler: handler} }
csn
// GetAll retrieves all key value pairs in a bucket, it stores the map of key value pairs // inside the DataList attribute.
func (s Storage) GetAll(bucket string, nested ...string) Storage { return s.execute(bucket, "", nil, nested, getAll) }
csn
This method create symlinks for all files in a given dir in another directory @param conf the configuration @param jobCacheDir the target directory for creating symlinks @param workDir the directory in which the symlinks are created @throws IOException
public static void createAllSymlink(Configuration conf, File jobCacheDir, File workDir) throws IOException{ if ((jobCacheDir == null || !jobCacheDir.isDirectory()) || workDir == null || (!workDir.isDirectory())) { return; } boolean createSymlink = getSymlink(conf); if (createS...
csn
Method to create vlan's :param vlans: List containing vlan's desired to be created on database :return: None
def create(self, vlans): """ Method to create vlan's :param vlans: List containing vlan's desired to be created on database :return: None """ data = {'vlans': vlans} return super(ApiVlan, self).post('api/v3/vlan/', data)
csn
Static method to load and parse a JSON string from an InputStream. @param diseasePanelInputStream InputStream with the JSON string representing this panel. @return A DiseasePanel object. @throws IOException Propagate Jackson IOException.
public static DiseasePanel load(InputStream diseasePanelInputStream) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(diseasePanelInputStream, DiseasePanel.class); }
csn
// GetDomainName returns local auth domain of the current auth server
func (c *Client) GetDomainName() (string, error) { out, err := c.Get(c.Endpoint("domain"), url.Values{}) if err != nil { return "", trace.Wrap(err) } var domain string if err := json.Unmarshal(out.Bytes(), &domain); err != nil { return "", trace.Wrap(err) } return domain, nil }
csn
Client connection's TCP port.
def client_port(self): """Client connection's TCP port.""" address = self._client.getpeername() if isinstance(address, tuple): return address[1] # Maybe a Unix domain socket connection. return 0
csn
If the article has meta canonical link set in the url @return string|null
private function getCanonicalLink(): ?string { $nodes = $this->getNodesByLowercasePropertyValue($this->article()->getDoc(), 'link', 'rel', 'canonical'); if ($nodes->count()) { return trim($nodes->first()->attr('href')); } $nodes = $this->getNodesByLowercasePropertyValue($th...
csn
// SetColumnsFromFields Explicityly set column names from fields.
func (m *Table) SetColumnsFromFields() { m.FieldPositions = make(map[string]int, len(m.Fields)) cols := make([]string, len(m.Fields)) for idx, f := range m.Fields { col := strings.ToLower(f.Name) m.FieldPositions[col] = idx cols[idx] = col } m.cols = cols }
csn
Replace an existing edge in a graph, identified graph name and edge id This will replace the edge on the server This will throw if the edge cannot be Replaced If policy is set to error (locally or globally through the ConnectionOptions) and the passed document has a _rev value set, the database will check that the r...
public function replaceEdge($graph, $edgeId, $label, Edge $document, array $options = [], $collection = null) { if ($graph instanceof Graph) { $graph = $graph->getKey(); } $parts = explode('/', $edgeId); if (count($parts) === 2) { list($collection, $edgeId) = ...
csn
Import contact list @param string $group_name @param array $contact[] @option string "phone" @option string "email" @option string "first_name" @option string "last_name" @option string "company" @return object @option bool "success" @option int "id" @option int "correct" Number of contacts imported correctly @option ...
public function import($group_name, $contact) { $params = array( 'group_name' => $group_name, 'contact' => $contact ); return $this->master->call('contacts/import', $params); }
csn
Update rowMergeWith property of target rows for row merge. @param {Array.<Array.<object>>} targetRows - target rows @param {number} startColIndex - start column index @param {number} endColIndex - end column index @param {number} rowMergeWith - index of row merger @private
function _updateRowMergeWith(targetRows, startColIndex, endColIndex, rowMergeWith) { const limitColIndex = endColIndex + 1; targetRows.forEach(rowData => { rowData.slice(startColIndex, limitColIndex).forEach(cellData => { cellData.rowMergeWith = rowMergeWith; }); }); }
csn
// discardTask returns the task for discarding a Cacheable.
func discardTask(id string, responsec responder) task { return func(c *cache) error { bucket, ok := c.buckets[id] if !ok { // Not found, so nothing to discard. responsec <- func() (Cacheable, error) { return nil, nil } return nil } // Discard Cacheable, notify possible waiters, // delete buck...
csn
strict expression equality that didn't involve parameters.
public List<AbstractExpression> bindingToIndexedExpression( AbstractExpression expr) { // Defer the result construction for as long as possible on the // assumption that this function mostly gets applied to eliminate // negative cases. if (m_type != expr.m_type) { ...
csn
// PatchResource patches resource
func (k KubectlCmd) PatchResource(config *rest.Config, gvk schema.GroupVersionKind, name string, namespace string, patchType types.PatchType, patchBytes []byte) (*unstructured.Unstructured, error) { dynamicIf, err := dynamic.NewForConfig(config) if err != nil { return nil, err } disco, err := discovery.NewDiscove...
csn
method to add a group to the grouping section of the HELM2Notation @param notation new group @param position position of the new group @param helm2notation input HELM2Notation
public final static void addGroup(final GroupingNotation notation, final int position, final HELM2Notation helm2notation) { helm2notation.getListOfGroupings().add(position, notation); }
csn
Determine the output type of this accumulator.
static Class<?> getOutputType(Class<?> fieldType) { if (!Number.class.isAssignableFrom(fieldType)) { throw new IllegalStateException("Aggregation SUM cannot be applied to property of type " + fieldType.getName()); } if (fieldType == Double.class || fieldType == Float.class) { return ...
csn
Method to deploy resources defined in the swagger file. ret a dictionary for returning status to Saltstack api_key_required True or False, whether api key is required to access this method. lambda_integration_role name of the IAM role or IAM role arn that A...
def deploy_resources(self, ret, api_key_required, lambda_integration_role, lambda_region, authorization_type): ''' Method to deploy resources defined in the swagger file. ret a dictionary for returning status to Saltstack api_key_required True or False, whether ...
csn
Compare two IMolecularFormula looking at type and number of IIsotope and charge of the formula. @param formula1 The first IMolecularFormula @param formula2 The second IMolecularFormula @return True, if the both IMolecularFormula are the same
public static boolean compare(IMolecularFormula formula1, IMolecularFormula formula2) { if (!Objects.equals(formula1.getCharge(), formula2.getCharge())) return false; if (formula1.getIsotopeCount() != formula2.getIsotopeCount()) return false; for (IIsotope isotope : formula1.isotopes()) { ...
csn
prepare the group by @access private @return string
private function _prepareGroupBy() { $sQuery = ''; if (is_array($this->_aGroupBy) && count($this->_aGroupBy) > 0) { $sQuery .= ' GROUP BY '.implode(',', $this->_aGroupBy).' '; } return $sQuery; }
csn
Parses a GeoJSON coordinate array and check if it's wellformed. The first token corresponds to the first X value. The last token correponds to the end of the coordinate array "]". Parsed syntax: 100.0, 0.0] @param jp @throws IOException @return Coordinate
private void parseCoordinateMetadata(JsonParser jp) throws IOException { jp.nextToken(); jp.nextToken(); // second value //We look for a z value jp.nextToken(); if (jp.getCurrentToken() != JsonToken.END_ARRAY) { jp.nextToken(); // exit array } jp.nextT...
csn
This method initializes map for glyphs and their respective ports. @param glyphs Glyph list of SBGN model
private void initPortIdToGlyphMap(List<Glyph> glyphs) { for(Glyph glyph: glyphs) { for(Port p: glyph.getPort()) { portIDToOwnerGlyph.put(p.getId(), glyph ); } if(glyph.getGlyph().size() > 0) initPortIdToGlyphMap(glyph.ge...
csn
Perform an atomic prepend for a new resource
def add_resource(self, resource): '''Perform an atomic prepend for a new resource''' resource.validate() self.update(__raw__={ '$push': { 'resources': { '$each': [resource.to_mongo()], '$position': 0 } ...
csn
Calculate the dependency paths to the reasons of the blockers. Paths will be in reverse-dependency order (i.e. parent projects are in ascending order).
def reasons_to_paths(reasons): """Calculate the dependency paths to the reasons of the blockers. Paths will be in reverse-dependency order (i.e. parent projects are in ascending order). """ blockers = set(reasons.keys()) - set(reasons.values()) paths = set() for blocker in blockers: ...
csn
Parse a named event or explicit stream trigger into a TriggerDefinition.
def _parse_trigger(self, trigger_clause): """Parse a named event or explicit stream trigger into a TriggerDefinition.""" cond = trigger_clause[0] named_event = None explicit_stream = None explicit_trigger = None # Identifier parse tree is Group(Identifier) if c...
csn
// buildJoinOptions builds endpoint Join options from a given network.
func buildJoinOptions(networkSettings *internalnetwork.Settings, n interface { Name() string }) ([]libnetwork.EndpointOption, error) { var joinOptions []libnetwork.EndpointOption if epConfig, ok := networkSettings.Networks[n.Name()]; ok { for _, str := range epConfig.Links { name, alias, err := opts.ParseLink(s...
csn
setter for descriptorName - sets see MeSH @generated @param v value to set into the feature
public void setDescriptorName(String v) { if (MeshHeading_Type.featOkTst && ((MeshHeading_Type)jcasType).casFeat_descriptorName == null) jcasType.jcas.throwFeatMissing("descriptorName", "de.julielab.jules.types.MeshHeading"); jcasType.ll_cas.ll_setStringValue(addr, ((MeshHeading_Type)jcasType).casFeatCode...
csn
Registers a new job-type a workers is capable of doing. @param string $jobName @param string $workerId @return bool
protected function registerJob(string $jobName, string $workerId) : bool { if (!isset($this->workerJobCapabilities[$workerId])) { $this->workerJobCapabilities[$workerId] = []; } if (!in_array($jobName, $this->workerJobCapabilities[$workerId])) { array_push($this->work...
csn
Receive notification of the start of the non-text event. This is sent to the current processor when any non-text event occurs. @param handler non-null reference to current StylesheetHandler that is constructing the Templates.
public void startNonText(StylesheetHandler handler) throws org.xml.sax.SAXException { if (this == handler.getCurrentProcessor()) { handler.popProcessor(); } int nChars = m_accumulator.length(); if ((nChars > 0) && ((null != m_xslTextElement) ||!XMLCharacterRecog...
csn
Sorts the individual argument list in unsorted according to CompareArgumentsByName @param unsorted @return
private List<Map<String, Object>> sortArguments(final List<Map<String, Object>> unsorted) { Collections.sort(unsorted, new CompareArgumentsByName()); return unsorted; }
csn
Checks if a list of containers has the specified key. @since [*next-version*] @param string|Stringable $key The key to check for. @param array|stdClass|Traversable $list A list of containers. @throws InvalidArgumentException If the key or the list are of the wrong type. @throws BaseContainerExceptio...
protected function _containerListHas($key, $list) { $list = $this->_normalizeIterable($list); foreach ($list as $_container) { if ($this->_containerHas($_container, $key)) { return true; } } return false; }
csn
returns if one signature is a Character and the other is a primitive @param sig1 the first method signature @param sig2 the second method signature @return if one signature is a Character and the other a primitive
private static boolean confusingSignatures(String sig1, String sig2) { if (sig1.equals(sig2)) { return false; } List<String> type1 = SignatureUtils.getParameterSignatures(sig1); List<String> type2 = SignatureUtils.getParameterSignatures(sig2); if (type1.size() != ty...
csn
Performs a redirect to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI. We request the given attributes for the authenticated user by default (name, email, language, and username). If you don't need all tho...
def authenticate_redirect(self, callback_uri=None, ask_for=["name", "email", "language", "username"]): """ Performs a redirect to the authentication URL for this service. After authentication, the service will redirect back to the given callback URI. ...
csn
Returns a cookie by name. @param $name @return Cookie|null
public function get($name) { return isset($this->cookies[$name]) ? $this->cookies[$name] : null; }
csn
Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None
def merge_wheres(self, wheres, bindings): """ Merge a list of where clauses and bindings :param wheres: A list of where clauses :type wheres: list :param bindings: A list of bindings :type bindings: list :rtype: None """ self.wheres = self.where...
csn
Processes an import. Calculates the possible names generated from an import and invokes registered callbacks if needed. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer.
def _ProcessImportBySuffix(name, fromlist, globals): """Processes an import. Calculates the possible names generated from an import and invokes registered callbacks if needed. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed ...
csn
Return the AggregateType that is referred to by the given command. @param string $attribute_name @param string $embedded_type_prefix @return EntityTypeInterface
protected function getEmbeddedEntityTypeFor($attribute_name, $embedded_type_prefix) { $attribute = $this->getType()->getAttribute($attribute_name); return $attribute->getEmbeddedTypeByPrefix($embedded_type_prefix); }
csn
Compare a juicer repo def with a given pulp definition. Compute and return the update necessary to make `pulp_def` match `juicer_def`. `juicer_def` - A JuicerRepo() object representing a juicer repository `pulp_def` - A PulpRepo() object representing a pulp repository
def repo_def_matches_reality(juicer_def, pulp_def): """Compare a juicer repo def with a given pulp definition. Compute and return the update necessary to make `pulp_def` match `juicer_def`. `juicer_def` - A JuicerRepo() object representing a juicer repository `pulp_def` - A PulpRepo() object representi...
csn
Application entry point. @return {Promise<void>} Completes when the program is terminated.
async function main() { // Initialize the application. process.title = 'Which.js'; // Parse the command line arguments. program.name('which') .description('Find the instances of an executable in the system path.') .version(packageVersion, '-v, --version') .option('-a, --all', 'list all instances of...
csn