Dataset Viewer
Auto-converted to Parquet Duplicate
query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
how to retrieve index file python
def search_index_file(): """Return the default local index file, from the download cache""" from metapack import Downloader from os import environ return environ.get('METAPACK_SEARCH_INDEX', Downloader.get_instance().cache.getsyspath('index.json'))
cosqa
function (basepath, action, recursive) { var isDirectory = function (target) { return fs.statSync(target).isDirectory(); }; var nextLevel = function (subpath) { _.each(fs.readdirSync(path.join(basepath, subpath)), function (filename) { if (isDirectory(path.join(basepath, (filename = path.join(subpath, filename))))) {
if (recursive) { nextLevel(filename); } } else { action(filename); } }); }; nextLevel('./'); }
csn_ccr
func (t *migrateWorker) run() { for data := range t.work { // if we have no error and a filter func, determine if we need to ignore this resource if data.err == nil && t.filterFn != nil { ok, err := t.filterFn(data.info) // error if we cannot figure out how to filter this resource if err != nil { t.results <- resultData{found: true, result: attemptResultError, data: workData{info: data.info, err: err}} continue } // we want to ignore this resource if !ok { t.results <- resultData{found: true, result: attemptResultIgnore, data: data} continue } } // there was an error so do not attempt to process this data if data.err != nil { t.results <- resultData{result: attemptResultError, data: data}
continue } // we have no error and the resource was not ignored, so attempt to process it // try to invoke the migrateFn and saveFn on info, retrying any recalculation requests up to t.retries times result, err := t.try(data.info, t.retries) t.results <- resultData{found: true, result: result, data: workData{info: data.info, err: err}} } }
csn_ccr
import dicon file. @param string $dicon
public function import($dicon) { $defines = $this->get('yaml')->load($dicon); foreach ($defines as $name => $def) { $define = $this->getComponentDefine($def); $this->register($name, $define); } }
csn
public void removeAllBucketNotification(String bucketName) throws InvalidBucketNameException, InvalidObjectPrefixException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException {
NotificationConfiguration notificationConfiguration = new NotificationConfiguration(); setBucketNotification(bucketName, notificationConfiguration); }
csn_ccr
def authenticationRequest(): """AUTHENTICATION REQUEST Section 9.2.2""" a = TpPd(pd=0x5) b = MessageType(mesType=0x12) # 00010010 c =
CiphKeySeqNrAndSpareHalfOctets() d = AuthenticationParameterRAND() packet = a / b / c / d return packet
csn_ccr
public static void reportSegmentSplitsAndMerges(String scope, String streamName, long splits, long merges) { DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_SPLITS), splits); DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_SPLITS, splits, streamTags(scope, streamName));
DYNAMIC_LOGGER.updateCounterValue(globalMetricName(SEGMENTS_MERGES), merges); DYNAMIC_LOGGER.updateCounterValue(SEGMENTS_MERGES, merges, streamTags(scope, streamName)); }
csn_ccr
NAME update_measurements.py DESCRIPTION update the magic_measurements table with new orientation info SYNTAX update_measurements.py [command line options] OPTIONS -h prints help message and quits -f MFILE, specify magic_measurements file; default is magic_measurements.txt -fsa SFILE, specify er_samples table; default is er_samples.txt -F OFILE, specify output file, default is same as MFILE
def main(): """ NAME update_measurements.py DESCRIPTION update the magic_measurements table with new orientation info SYNTAX update_measurements.py [command line options] OPTIONS -h prints help message and quits -f MFILE, specify magic_measurements file; default is magic_measurements.txt -fsa SFILE, specify er_samples table; default is er_samples.txt -F OFILE, specify output file, default is same as MFILE """ dir_path='.' meas_file='magic_measurements.txt' samp_file="er_samples.txt" out_file='magic_measurements.txt' if '-h' in sys.argv: print(main.__doc__) sys.exit() if '-WD' in sys.argv: ind = sys.argv.index('-WD') dir_path=sys.argv[ind+1] if '-f' in sys.argv: ind = sys.argv.index('-f') meas_file=sys.argv[ind+1] if '-fsa' in sys.argv: ind = sys.argv.index('-fsa') samp_file=sys.argv[ind+1] if '-F' in sys.argv: ind = sys.argv.index('-F') out_file=sys.argv[ind+1] # read in measurements file meas_file=dir_path+'/'+meas_file out_file=dir_path+'/'+out_file samp_file=dir_path+'/'+samp_file data,file_type=pmag.magic_read(meas_file) samps,file_type=pmag.magic_read(samp_file) MeasRecs=[] sampnames,sflag=[],0 for rec in data: for samp in samps: if samp['er_sample_name'].lower()==rec['er_sample_name'].lower(): if samp['er_sample_name'] not in sampnames:sampnames.append(samp['er_sample_name'].lower()) rec['er_site_name']=samp['er_site_name'] rec['er_location_name']=samp['er_location_name'] MeasRecs.append(rec) break if rec['er_sample_name'].lower() not in sampnames: sampnames.append(rec['er_sample_name'].lower()) sflag=1 SampRec={} for key in list(samps[0].keys()):SampRec[key]="" SampRec['er_sample_name']=rec['er_sample_name'] SampRec['er_citation_names']="This study" SampRec['er_site_name']='MISSING' SampRec['er_location_name']='MISSING' SampRec['sample_desription']='recorded added by update_measurements - edit as needed' samps.append(SampRec) print(rec['er_sample_name'],' missing from er_samples.txt file - edit orient.txt file and re-import') rec['er_site_name']='MISSING' rec['er_location_name']='MISSING' MeasRecs.append(rec) pmag.magic_write(out_file,MeasRecs,'magic_measurements') print("updated measurements file stored in ", out_file) if sflag==1: pmag.magic_write(samp_file,samps,'er_samples') print("updated sample file stored in ", samp_file)
csn
Manually set the access token. @param string|array|TokenInterface $token An array of token data, an access token string, or a TokenInterface object
public function setAccessToken($token) { if ($token instanceof Token\TokenInterface) { $this->rawToken = $token; } else { $this->rawToken = is_array($token) ? $this->tokenFactory($token) : $this->tokenFactory(['access_token' => $token]); } if ($this->rawToken === null) { throw new Exception\OAuth2Exception("setAccessToken() takes a string, array or TokenInterface object"); } return $this; }
csn
async def delete_tree(self, prefix, *, separator=None): """Deletes all keys with a prefix of Key. Parameters: key (str): Key to delete separator (str): Delete only up to a given separator Response: bool: ``True`` on success
""" response = await self._discard(prefix, recurse=True, separator=separator) return response.body is True
csn_ccr
public static HtmlTree HTML(String lang, Content head, Content body) { HtmlTree htmltree = new HtmlTree(HtmlTag.HTML, nullCheck(head), nullCheck(body));
htmltree.addAttr(HtmlAttr.LANG, nullCheck(lang)); return htmltree; }
csn_ccr
Decorator for registering a function with PyPhi. Args: name (string): The name of the function
def register(self, name): """Decorator for registering a function with PyPhi. Args: name (string): The name of the function """ def register_func(func): self.store[name] = func return func return register_func
csn
Is prefixed. @param string $data @param string $prefix @param string $separator Default ''. @return bool
public static function isPrefixed(string $data, string $prefix, string $separator = ''): bool { if ($separator !== '') { $data = trim($data, $separator); } return static::substr($data, 0, static::length($prefix)) === $prefix; }
csn
Return class for button element @param string $btn class of button for process @return string Class for button element @link http://getbootstrap.com/css/#buttons
public function getBtnClass($btn = null) { $btnClass = $this->_getClassForElement($btn); if (!empty($btnClass)) { $result = $btnClass; } else { $result = $this->_getClassForElement('btn-default'); } return $result; }
csn
public function getColumnNames(GetPropertyOptionsEvent $event) { if (!$this->isBackendOptionRequestFor($event, ['tag_column', 'tag_alias', 'tag_sorting'])) {
return; } $result = $this->getColumnNamesFrom($event->getModel()->getProperty('tag_table')); if (!empty($result)) { \asort($result); $event->setOptions($result); } }
csn_ccr
def get_stddevs(self, C, stddev_shape, stddev_types, sites): """ Returns the standard deviations, with different site standard deviation for inferred vs. observed vs30 sites. """ stddevs = [] tau = C["tau_event"] sigma_s = np.zeros(sites.vs30measured.shape, dtype=float) sigma_s[sites.vs30measured] += C["sigma_s_obs"] sigma_s[np.logical_not(sites.vs30measured)] += C["sigma_s_inf"] phi = np.sqrt(C["phi0"] ** 2.0 + sigma_s ** 2.) for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt(tau ** 2. + phi ** 2.) + np.zeros(stddev_shape)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(phi + np.zeros(stddev_shape)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(tau + np.zeros(stddev_shape)) return stddevs
csn_ccr
function release(type) { target.test(); echo("Generating new version"); const newVersion = execSilent("npm version " + type).trim(); target.changelog(); // add changelog to commit exec("git add CHANGELOG.md"); exec("git commit --amend --no-edit"); // replace existing tag exec("git tag -f " + newVersion);
// push all the things echo("Publishing to git"); exec("git push origin master --tags"); echo("Publishing to npm"); exec("npm publish"); }
csn_ccr
Generate database code. @param $value @return string
private function generateDbCode($value) { $code = ''; $code .= "\t\t\t\t".'$'.Inflector::tabilize($this->model).'->'.$value['COLUMN_NAME'].' = $postArray["'.$value['COLUMN_NAME'].'"];'.PHP_EOL; return $code; }
csn
def install_required(f): """ Return an exception if the namespace is not already installed """ @wraps(f) def wrapped(self, *args, **kwargs): if self.directory.new:
raise SprinterException("Namespace %s is not yet installed!" % self.namespace) return f(self, *args, **kwargs) return wrapped
csn_ccr
Returns if the current certificate is in a valid date range
def isValid(self): """Returns if the current certificate is in a valid date range """ today = DateTime() valid_from = self.getValidFrom() valid_to = self.getValidTo() return valid_from <= today <= valid_to
csn
sets the link to the request used to give this response this will end up in response.links.self .. and in response.data.links.self for single resource objects by default this is already set using $_SERVER variables use this method to override this default behavior @see ::__construct() @param string $link @param mixed $meta_data optional, meta data as key-value pairs objects are converted in arrays, @see base::convert_object_to_array() @return void
public function set_self_link($link, $meta_data=null) { if ($meta_data) { // can not combine both raw link object and extra meta data if (is_string($link) == false) { throw new \Exception('link "self" should be a string if meta data is provided separate'); } if (is_object($meta_data)) { $meta_data = parent::convert_object_to_array($meta_data); } $link = array( 'href' => $link, 'meta' => $meta_data, ); } $this->links['self'] = $link; }
csn
Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality.
def dvc_walk( top, topdown=True, onerror=None, followlinks=False, ignore_file_handler=None, ): """ Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality. """ ignore_filter = None if topdown: from dvc.ignore import DvcIgnoreFilter ignore_filter = DvcIgnoreFilter( top, ignore_file_handler=ignore_file_handler ) for root, dirs, files in os.walk( top, topdown=topdown, onerror=onerror, followlinks=followlinks ): if ignore_filter: dirs[:], files[:] = ignore_filter(root, dirs, files) yield root, dirs, files
csn
def _convert(self, chain_id, residue_id, from_scheme, to_scheme): '''The actual 'private' conversion function.''' # There are 12 valid combinations but rather than write them all out explicitly, we will use recursion, sacrificing speed for brevity if from_scheme == 'rosetta': atom_id = self.rosetta_to_atom_sequence_maps.get(chain_id, {})[residue_id] if to_scheme == 'atom': return atom_id else: return self._convert(chain_id, atom_id, 'atom', to_scheme) if from_scheme == 'atom': if to_scheme == 'rosetta': return self.atom_to_rosetta_sequence_maps.get(chain_id, {})[residue_id] else: seqres_id = self.atom_to_seqres_sequence_maps.get(chain_id, {})[residue_id] if to_scheme == 'seqres': return seqres_id return self.convert(chain_id, seqres_id, 'seqres', to_scheme) if from_scheme == 'seqres': if to_scheme == 'uniparc': return self.seqres_to_uniparc_sequence_maps.get(chain_id, {})[residue_id]
else: atom_id = self.seqres_to_atom_sequence_maps.get(chain_id, {})[residue_id] if to_scheme == 'atom': return atom_id return self.convert(chain_id, atom_id, 'atom', to_scheme) if from_scheme == 'uniparc': seqres_id = self.uniparc_to_seqres_sequence_maps.get(chain_id, {})[residue_id] if to_scheme == 'seqres': return seqres_id else: return self._convert(chain_id, seqres_id, 'seqres', to_scheme) raise Exception("We should never reach this line.")
csn_ccr
def pre_check(self, data): """Count chars, words and sentences in the text.""" sentences = len(re.findall('[\.!?]+\W+', data)) or 1 chars = len(data) - len(re.findall('[^a-zA-Z0-9]', data))
num_words = len(re.findall('\s+', data)) data = re.split('[^a-zA-Z]+', data) return data, sentences, chars, num_words
csn_ccr
async def pull( self, from_image: str, *, auth: Optional[Union[MutableMapping, str, bytes]] = None, tag: str = None, repo: str = None, stream: bool = False ) -> Mapping: """ Similar to `docker pull`, pull an image locally Args: fromImage: name of the image to pull repo: repository name given to an image when it is imported tag: if empty when pulling an image all tags for the given image to be pulled auth: special {'auth': base64} pull private repo """ image = from_image # TODO: clean up params = {"fromImage": image} headers = {} if repo: params["repo"] = repo if tag: params["tag"] = tag if auth is not None: registry, has_registry_host, _ = image.partition("/") if not
has_registry_host: raise ValueError( "Image should have registry host " "when auth information is provided" ) # TODO: assert registry == repo? headers["X-Registry-Auth"] = compose_auth_header(auth, registry) response = await self.docker._query( "images/create", "POST", params=params, headers=headers ) return await json_stream_result(response, stream=stream)
csn_ccr
looking for the primary be equals to locateId in the result for the sql sentence. @param sqlquery @param queryParams @param locateId @return if not locate, return null;
public Block locate(String sqlquery, Collection queryParams, Object locateId) { int blockSize = getBlockLength(); Block block = null; int index = -1; int prevBlockStart = Integer.MIN_VALUE; int nextBlockStart = Integer.MIN_VALUE; int start = 0; Debug.logVerbose("[JdonFramework]try to locate a block locateId= " + locateId + " blockSize=" + blockSize, module); try { while (index == -1) { block = getBlock(sqlquery, queryParams, start, blockSize); if (block == null) break; List list = block.getList(); index = list.indexOf(locateId); if ((index >= 0) && (index < list.size())) { Debug.logVerbose("[JdonFramework]found the locateId, index= " + index, module); if ((index == 0) && (block.getStart() >= blockSize))// if is // the // first // in // this // block prevBlockStart = start - blockSize; else if (index == blockSize - 1) // // if is the last in // this block nextBlockStart = start + blockSize; break; } else { if (block.getCount() >= blockSize)// there are more block. start = start + blockSize; else // there are no more block; break; } } if (index == -1) { Debug.logVerbose("[JdonFramework] not locate the block that have the locateId= " + locateId, module); return null; // not found return null } if (prevBlockStart != Integer.MIN_VALUE) { Block prevBlock = getBlock(sqlquery, queryParams, prevBlockStart, blockSize); prevBlock.getList().addAll(block.getList()); prevBlock.setStart(prevBlock.getStart() + prevBlock.getCount()); prevBlock.setCount(prevBlock.getCount() + block.getCount()); return prevBlock; } else if (nextBlockStart != Integer.MIN_VALUE) { // if // nextBlockStart // has new // value, so we // need next // block, fetch // it. Block nextBlock = getBlock(sqlquery, queryParams, nextBlockStart, blockSize); if (nextBlock != null) { block.getList().addAll(nextBlock.getList()); block.setCount(block.getCount() + nextBlock.getCount()); } return block; } else return block; } catch (Exception e) { Debug.logError(" locate Block error" + e, module); } return block; }
csn
python check if user in group
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
cosqa
Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_note('Remember to update to the latest version.')
def add_note(self, content): """Add a note to the project. .. warning:: Requires Todoist premium. :param content: The note content. :type content: str >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = user.get_project('PyTodoist') >>> project.add_note('Remember to update to the latest version.') """ args = { 'project_id': self.id, 'content': content } _perform_command(self.owner, 'note_add', args)
csn
func (c CryptoClient) SignToString(ctx context.Context, __arg SignToStringArg) (res
string, err error) { err = c.Cli.Call(ctx, "keybase.1.crypto.signToString", []interface{}{__arg}, &res) return }
csn_ccr
attach add listen port to main server. @param string $name @param \Closure|array|PortListenerInterface $config @throws \InvalidArgumentException
public function attachPort(string $name, $config): void { if (isset($this->attachedNames[strtolower($name)])) { throw new \InvalidArgumentException("The add listen port server [$name] has been exists!"); } if (\is_array($config)) { $class = Arr::remove($config, 'listener'); if (!$class) { throw new \InvalidArgumentException("Please setting the 'listener' class for the port server: $name"); } $cb = new $class($config); if (!$cb instanceof PortListenerInterface) { throw new \InvalidArgumentException( 'The event handler must implement of ' . PortListenerInterface::class ); } } elseif ($config instanceof \Closure || $config instanceof PortListenerInterface) { $cb = $config; } else { throw new \InvalidArgumentException('The 2th argument type only allow [array|\Closure|InterfacePortListener].'); } $this->attachedNames[$name] = true; $this->attachedListeners[$name] = $cb; }
csn
// tryToConvert2DummyScan is an optimization which checks if its parent is a selection with a constant condition // that evaluates to false. If it is, there is no need for a real physical scan, a dummy scan will do.
func (p *DataSource) tryToConvert2DummyScan(prop *requiredProperty) (*physicalPlanInfo, error) { sel, isSel := p.GetParentByIndex(0).(*Selection) if !isSel { return nil, nil } for _, cond := range sel.Conditions { if con, ok := cond.(*expression.Constant); ok { result, err := expression.EvalBool(con, nil, p.ctx) if err != nil { return nil, errors.Trace(err) } if !result { dummy := &PhysicalDummyScan{} dummy.tp = "Dummy" dummy.allocator = p.allocator dummy.initIDAndContext(p.ctx) dummy.SetSchema(p.schema) info := &physicalPlanInfo{p: dummy} p.storePlanInfo(prop, info) return info, nil } } } return nil, nil }
csn
// AddElseIf add ElseIf node and returns AltIf node
func (n *If) AddElseIf(ElseIf node.Node) node.Node { if n.ElseIf == nil { n.ElseIf = make([]node.Node, 0) } n.ElseIf = append(n.ElseIf, ElseIf) return n }
csn
func ToExpression(p Path, this uuid.UUID) string { converted := strings.Replace(this.String(), "-", "_", -1) existingPath := p.Convert() if existingPath
== "" { return converted } return fmt.Sprintf("%s.%s", p.Convert(), converted) }
csn_ccr
private Session createConnection() { /* reorder locations */ List<String> locations = Lists.newArrayList(split.getReplicas()); Collections.sort(locations, new DeepPartitionLocationComparator()); Exception lastException = null; LOG.debug("createConnection: " + locations);
for (String location : locations) { try { return trySessionForLocation(location, config, false).left; } catch (Exception e) { LOG.error("Could not get connection for: {}, replicas: {}", location, locations); lastException = e; } } throw new DeepIOException(lastException); }
csn_ccr
Returns the WebGL Context object of the given Canvas @name getContextGL @memberOf me.WebGLRenderer.prototype @function @param {Canvas} canvas @param {Boolean} [transparent=true] use false to disable transparency @return {WebGLRenderingContext}
function getContextGL(canvas, transparent) { if (typeof canvas === "undefined" || canvas === null) { throw new Error("You must pass a canvas element in order to create " + "a GL context"); } if (typeof transparent !== "boolean") { transparent = true; } var attr = { alpha: transparent, antialias: this.settings.antiAlias, depth: false, stencil: true, premultipliedAlpha: transparent, failIfMajorPerformanceCaveat: this.settings.failIfMajorPerformanceCaveat }; var gl = canvas.getContext("webgl", attr) || canvas.getContext("experimental-webgl", attr); if (!gl) { throw new Error("A WebGL context could not be created."); } return gl; }
csn
Returns the audio-type of a given hash. Is no key as second parameter given, it trys first "mp3", than "m4a" and than it will return a more or less random value. {{ post.audio | audiotype }} => "my-episode.m4a"
def audio_type(hsh) if !hsh.nil? && hsh.length hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus') end end
csn
Clear all content from this map. This will disconnect from any parent map as well.
public void clear() { // TODO not currently used since EventImpl itself doesn't have a clear this.parentMap = null; if (null != this.values) { for (int i = 0; i < this.values.length; i++) { this.values[i] = null; } this.values = null; } }
csn
Start building a PUT request. @return a request builder which then can be used to create the actual request.
public <T> HttpClientRequest.Builder<T> put(final URI uri, final HttpClientResponseHandler<T> httpHandler) { return new HttpClientRequest.Builder<T>(httpClientFactory, HttpClientMethod.PUT, uri, httpHandler); }
csn
def unlock(path, locktoken) headers = {'Lock-Token' => '<'+locktoken+'>'}
path = @uri.merge(path).path res = @handler.request(:unlock, path, nil, headers.merge(@headers)) end
csn_ccr
Adds a TableOfContents File object to the last heading that was discovered. This may be used by roles or directives to insert an include file into the TableOfContents and thus all its headings. This method is explicitly bound to File objects and not other BaseEntry descendents because inline elements such as headings should also modify the internal pointers for this visitor.
public function addFileToLastHeading(TableOfContents\File $file) { $this->last_heading->addChild($file); $file->setParent($this->last_heading); }
csn
Update a commit comment @param [Hash] params @option params [String] :body Required. The contents of the comment. @example github = Github.new github.repos.comments.update 'user-name', 'repo-name', 'id', body: "Nice change" @api public
def update(*args) arguments(args, required: [:user, :repo, :id]) do assert_required REQUIRED_COMMENT_OPTIONS end patch_request("/repos/#{arguments.user}/#{arguments.repo}/comments/#{arguments.id}", arguments.params) end
csn
func (w *Window) ShouldClose() bool { ret := gl
fwbool(C.glfwWindowShouldClose(w.data)) panicError() return ret }
csn_ccr
func NewTabletInfo(tablet *topodatapb.Tablet, version Version) *TabletInfo {
return &TabletInfo{version: version, Tablet: tablet} }
csn_ccr
async def list_batches(self, request): """Fetches list of batches from validator, optionally filtered by id. Request: query: - head: The id of the block to use as the head of the chain - id: Comma separated list of batch ids to include in results Response: data: JSON array of fully expanded Batch objects head: The head used for this query (most recent if unspecified) link: The link to this exact query, including head block paging: Paging info and nav, like total resources and a next link """ paging_controls = self._get_paging_controls(request) validator_query = client_batch_pb2.ClientBatchListRequest( head_id=self._get_head_id(request), batch_ids=self._get_filter_ids(request),
sorting=self._get_sorting_message(request, "default"), paging=self._make_paging_message(paging_controls)) response = await self._query_validator( Message.CLIENT_BATCH_LIST_REQUEST, client_batch_pb2.ClientBatchListResponse, validator_query) return self._wrap_paginated_response( request=request, response=response, controls=paging_controls, data=[self._expand_batch(b) for b in response['batches']])
csn_ccr
Access the auxillary data here
def tags(self): """Access the auxillary data here""" if self._tags: return self._tags tags = {} if not tags: return {} for m in [[y.group(1),y.group(2),y.group(3)] for y in [re.match('([^:]{2,2}):([^:]):(.+)$',x) for x in self.entries.optional_fields.split("\t")]]: if m[1] == 'i': m[2] = int(m[2]) elif m[1] == 'f': m[2] = float(m[2]) tags[m[0]] = TAGDatum(m[1],m[2]) self._tags = tags return self._tags
csn
Assigns B to A.attr, yields, and then assigns A.attr back to its original value.
def assign(A, attr, B, lock=False): '''Assigns B to A.attr, yields, and then assigns A.attr back to its original value. ''' class NoAttr(object): pass context = threading.Lock if lock else null_context with context(): if not hasattr(A, attr): tmp = NoAttr else: tmp = getattr(A, attr) setattr(A, attr, B) try: yield B finally: if tmp is NoAttr: delattr(A, attr) else: setattr(A, attr, tmp)
csn
Returns list of search engines by name @return array Array of ( searchEngineName => URL )
public function getNames() { $cacheId = 'SearchEngine.getSearchEngineNames'; $cache = Cache::getTransientCache(); $nameToUrl = $cache->fetch($cacheId); if (empty($nameToUrl)) { $searchEngines = $this->getDefinitions(); $nameToUrl = array(); foreach ($searchEngines as $url => $info) { if (!isset($nameToUrl[$info['name']])) { $nameToUrl[$info['name']] = $url; } } $cache->save($cacheId, $nameToUrl); } return $nameToUrl; }
csn
Opens the socket to the host. @param int &$error_code Error-code by referenct if an error occured. @param string &$error_string Error-string by reference @return bool TRUE if socket could be opened, otherwise FALSE.
protected function openSocket(&$error_code, &$error_string) { PHPCrawlerBenchmark::reset("connecting_server"); PHPCrawlerBenchmark::start("connecting_server"); // SSL or not? if ($this->url_parts["protocol"] == "https://") $protocol_prefix = "ssl://"; else $protocol_prefix = ""; // If SSL-request, but openssl is not installed if ($protocol_prefix == "ssl://" && !extension_loaded("openssl")) { $error_code = PHPCrawlerRequestErrors::ERROR_SSL_NOT_SUPPORTED; $error_string = "Error connecting to ".$this->url_parts["protocol"].$this->url_parts["host"].": SSL/HTTPS-requests not supported, extension openssl not installed."; } // Get IP for hostname $ip_address = $this->DNSCache->getIP($this->url_parts["host"]); // since PHP 5.6 SNI_server_name is deprecated if (version_compare(PHP_VERSION, '5.6.0') >= 0) { $serverName = 'peer_name'; } else { $serverName = 'SNI_server_name'; } // Open socket if ($this->proxy != null) { $this->socket = @stream_socket_client($this->proxy["proxy_host"].":".$this->proxy["proxy_port"], $error_code, $error_str, $this->socketConnectTimeout, STREAM_CLIENT_CONNECT); } else { // If ssl -> perform Server name indication if ($this->url_parts["protocol"] == "https://") { $context = stream_context_create(array( 'ssl' => array( $serverName => $this->url_parts["host"], ), )); $this->socket = @stream_socket_client($protocol_prefix.$ip_address.":".$this->url_parts["port"], $error_code, $error_str, $this->socketConnectTimeout, STREAM_CLIENT_CONNECT, $context); } else { $this->socket = @stream_socket_client($protocol_prefix.$ip_address.":".$this->url_parts["port"], $error_code, $error_str, $this->socketConnectTimeout, STREAM_CLIENT_CONNECT); // NO $context here, memory-leak-bug in php v. 5.3.x!! } } $this->server_connect_time = PHPCrawlerBenchmark::stop("connecting_server"); // If socket not opened -> throw error if ($this->socket == false) { $this->server_connect_time = null; // If proxy not reachable if ($this->proxy != null) { $error_code = PHPCrawlerRequestErrors::ERROR_PROXY_UNREACHABLE; $error_string = "Error connecting to proxy ".$this->proxy["proxy_host"].": Host unreachable (".$error_str.")."; return false; } else { $error_code = PHPCrawlerRequestErrors::ERROR_HOST_UNREACHABLE; $error_string = "Error connecting to ".$this->url_parts["protocol"].$this->url_parts["host"].": Host unreachable (".$error_str.")."; return false; } } else { return true; } }
csn
Returns whether the container has the given key. @param string $key The key, class or interface name. @return bool
public function has(string $key) : bool { if (isset($this->items[$key])) { return true; } try { $class = new \ReflectionClass($key); } catch (\ReflectionException $e) { return false; } $classes = $this->reflectionTools->getClassHierarchy($class); foreach ($classes as $class) { if ($this->injectionPolicy->isClassInjected($class)) { $this->bind($key); // @todo allow to configure scope (singleton) with annotations return true; } } return false; }
csn
// NewCmdSubject returns the "new subject" sub command
func NewCmdSubject(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command { o := NewSubjectOptions(streams) cmd := &cobra.Command{ Use: "subject (-f FILENAME | TYPE NAME) [--user=username] [--group=groupname] [--serviceaccount=namespace:serviceaccountname] [--dry-run]", DisableFlagsInUseLine: true, Short: i18n.T("Update User, Group or ServiceAccount in a RoleBinding/ClusterRoleBinding"), Long: subjectLong, Example: subjectExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.Run(addSubjects)) }, } o.PrintFlags.AddFlags(cmd) cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "the resource to update the subjects") cmd.Flags().BoolVar(&o.All, "all", o.All, "Select all resources, including uninitialized ones, in the namespace of the specified resource types") cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") cmd.Flags().BoolVar(&o.Local, "local", o.Local, "If true, set subject will NOT contact api-server but run locally.") cmdutil.AddDryRunFlag(cmd) cmd.Flags().StringArrayVar(&o.Users, "user", o.Users, "Usernames to bind to the role") cmd.Flags().StringArrayVar(&o.Groups, "group", o.Groups, "Groups to bind to the role") cmd.Flags().StringArrayVar(&o.ServiceAccounts, "serviceaccount", o.ServiceAccounts, "Service accounts to bind to the role") cmdutil.AddIncludeUninitializedFlag(cmd) return cmd }
csn
protected JsonToken handleRegEx() throws IOException { String regex = readCString(); String
pattern = readCString(); getContext().value = Pattern.compile(regex, regexStrToFlags(pattern)); return JsonToken.VALUE_EMBEDDED_OBJECT; }
csn_ccr
def dragend(self, event): """ Handles the end of a drag action. """ x_range = [self.begin_drag.x//self.col_width, event.x//self.col_width] y_range = [self.begin_drag.y//self.row_height, event.y//self.row_height] # Check bounds for i in range(2): for ls in [x_range, y_range]:
if ls[i] < 0: ls[i] = 0 if ls[i] >= self.rows: ls[i] = self.rows-1 for x in range(min(x_range), max(x_range)+1): for y in range(min(y_range), max(y_range)+1): if x == self.begin_drag.x//self.col_width and \ y == self.begin_drag.y//self.row_height: continue self.color_square(x*self.col_width, y*self.row_height) self.begin_drag = None print(len(self.cells), "cells selected")
csn_ccr
def order_duplicate_volume(self, origin_volume_id, origin_snapshot_id=None, duplicate_size=None, duplicate_iops=None, duplicate_tier_level=None, duplicate_snapshot_size=None, hourly_billing_flag=False): """Places an order for a duplicate block volume. :param origin_volume_id: The ID of the origin volume to be duplicated :param origin_snapshot_id: Origin snapshot ID to use for duplication :param duplicate_size: Size/capacity for the duplicate volume :param duplicate_iops: The IOPS per GB for the duplicate volume :param duplicate_tier_level: Tier level for the duplicate volume :param duplicate_snapshot_size: Snapshot space size for the duplicate :param hourly_billing_flag: Billing type, monthly (False) or hourly (True), default to monthly. :return: Returns a SoftLayer_Container_Product_Order_Receipt """ block_mask = 'id,billingItem[location,hourlyFlag],snapshotCapacityGb,'\ 'storageType[keyName],capacityGb,originalVolumeSize,'\ 'provisionedIops,storageTierLevel,osType[keyName],'\ 'staasVersion,hasEncryptionAtRest' origin_volume = self.get_block_volume_details(origin_volume_id,
mask=block_mask) if isinstance(utils.lookup(origin_volume, 'osType', 'keyName'), str): os_type = origin_volume['osType']['keyName'] else: raise exceptions.SoftLayerError( "Cannot find origin volume's os-type") order = storage_utils.prepare_duplicate_order_object( self, origin_volume, duplicate_iops, duplicate_tier_level, duplicate_size, duplicate_snapshot_size, 'block', hourly_billing_flag ) order['osFormatType'] = {'keyName': os_type} if origin_snapshot_id is not None: order['duplicateOriginSnapshotId'] = origin_snapshot_id return self.client.call('Product_Order', 'placeOrder', order)
csn_ccr
function toHtmlEntities(str) { str = str || ''; return str.replace(/./gm,
function(s) { return "&#" + s.charCodeAt(0) + ";"; }); }
csn_ccr
This method convert node of form in to a Document @param node n {Node} node entry. @return Document containing doc information
public Document nodeToDom(org.w3c.dom.Node node) throws S2SException { try { javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance(); javax.xml.transform.Transformer xf = tf.newTransformer(); javax.xml.transform.dom.DOMResult dr = new javax.xml.transform.dom.DOMResult(); xf.transform(new javax.xml.transform.dom.DOMSource(node), dr); return (Document) dr.getNode(); } catch (javax.xml.transform.TransformerException ex) { throw new S2SException(ex.getMessage()); } }
csn
// OSInfo returns combined information for the operating system.
func (p *UserAgent) OSInfo() OSInfo { // Special case for iPhone weirdness os := strings.Replace(p.os, "like Mac OS X", "", 1) os = strings.Replace(os, "CPU", "", 1) os = strings.Trim(os, " ") osSplit := strings.Split(os, " ") // Special case for x64 edition of Windows if os == "Windows XP x64 Edition" { osSplit = osSplit[:len(osSplit)-2] } name, version := osName(osSplit) // Special case for names that contain a forward slash version separator. if strings.Contains(name, "/") { s := strings.Split(name, "/") name = s[0] version = s[1] } // Special case for versions that use underscores version = strings.Replace(version, "_", ".", -1) return OSInfo{ FullName: p.os, Name: name, Version: version, } }
csn
Add unscroll class to head
function addUnscrollClassName() { if (document.getElementById('unscroll-class-name')) { return; } var css = '.unscrollable { overflow-y: hidden !important; }', head = document.head || document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; style.setAttribute('id', 'unscroll-class-name'); style.appendChild(document.createTextNode(css)); head.appendChild(style); }
csn
def htmlHelp(self, helpString=None, title=None, istask=False, tag=None): """ Pop up the help in a browser window. By default, this tries to show the help for the current task. With the option arguments, it can be used to show any help string. """ # Check the help string. If it turns out to be a URL, launch that, # if not, dump it to a quick and dirty tmp html file to make it # presentable, and pass that file name as the URL. if not helpString: helpString = self.getHelpString(self.pkgName+'.'+self.taskName) if not title: title = self.taskName lwr = helpString.lower() if lwr.startswith("http:") or lwr.startswith("https:") or \ lwr.startswith("file:"): url = helpString if tag and url.find('#') < 0: url += '#'+tag # print('LAUNCHING: '+url) # DBG irafutils.launchBrowser(url, subj=title) else: # Write it to a temp HTML
file to display (fd, fname) = tempfile.mkstemp(suffix='.html', prefix='editpar_') os.close(fd) f = open(fname, 'w') if istask and self._knowTaskHelpIsHtml: f.write(helpString) else: f.write('<html><head><title>'+title+'</title></head>\n') f.write('<body><h3>'+title+'</h3>\n') f.write('<pre>\n'+helpString+'\n</pre></body></html>') f.close() irafutils.launchBrowser("file://"+fname, subj=title)
csn_ccr
func (p *Polygon) excludesNonCrossingComplementShells(o *Polygon) bool { // Special case to handle the complement of the empty or full polygons. if o.IsEmpty() { return !p.IsFull() } if o.IsFull() { return true } // Otherwise the complement of B may be obtained by inverting loop(0) and // then swapping the shell/hole status of all other loops. This implies // that the shells of the complement consist of loop 0 plus all the holes of // the original polygon. for j, l
:= range o.loops { if j > 0 && !l.IsHole() { continue } // The interior of the complement is to the right of loop 0, and to the // left of the loops that were originally holes. if p.containsNonCrossingBoundary(l, j == 0) { return false } } return true }
csn_ccr
Publishes the events so the default fields are created
private function publishEvents() { /** @var CalendarEvent|TicketExtension $event */ foreach (CalendarEvent::get() as $event) { if ($event->Tickets()->exists()) { if ($event->doPublish()) { echo "[$event->ID] Published event \n"; $this->moveFieldData($event); } else { echo "[$event->ID] Failed to publish event \n\n"; } } } }
csn
Sign all unsigned inputs with a given key. Use the given outputs to fund them. @private_key_info: either a hex private key, or a dict with 'private_keys' and 'redeem_script' defined as keys. @prev_outputs: a list of {'out_script': xxx, 'value': xxx} that are in 1-to-1 correspondence with the unsigned inputs in the tx ('value' is in satoshis) @unsigned_hex_tx: hex transaction with unsigned inputs Returns: signed hex transaction
def btc_tx_sign_all_unsigned_inputs(private_key_info, prev_outputs, unsigned_tx_hex, scriptsig_type=None, segwit=None, **blockchain_opts): """ Sign all unsigned inputs with a given key. Use the given outputs to fund them. @private_key_info: either a hex private key, or a dict with 'private_keys' and 'redeem_script' defined as keys. @prev_outputs: a list of {'out_script': xxx, 'value': xxx} that are in 1-to-1 correspondence with the unsigned inputs in the tx ('value' is in satoshis) @unsigned_hex_tx: hex transaction with unsigned inputs Returns: signed hex transaction """ if segwit is None: segwit = get_features('segwit') txobj = btc_tx_deserialize(unsigned_tx_hex) inputs = txobj['ins'] if scriptsig_type is None: scriptsig_type = btc_privkey_scriptsig_classify(private_key_info) tx_hex = unsigned_tx_hex prevout_index = 0 # import json # print '' # print 'transaction:\n{}'.format(json.dumps(btc_tx_deserialize(unsigned_tx_hex), indent=4, sort_keys=True)) # print 'prevouts:\n{}'.format(json.dumps(prev_outputs, indent=4, sort_keys=True)) # print '' for i, inp in enumerate(inputs): do_witness_script = segwit if inp.has_key('witness_script'): do_witness_script = True elif segwit: # all inputs must receive a witness script, even if it's empty inp['witness_script'] = '' if (inp['script'] and len(inp['script']) > 0) or (inp.has_key('witness_script') and len(inp['witness_script']) > 0): continue if prevout_index >= len(prev_outputs): raise ValueError("Not enough prev_outputs ({} given, {} more prev-outputs needed)".format(len(prev_outputs), len(inputs) - prevout_index)) # tx with index i signed with privkey tx_hex = btc_tx_sign_input(str(unsigned_tx_hex), i, prev_outputs[prevout_index]['out_script'], prev_outputs[prevout_index]['value'], private_key_info, segwit=do_witness_script, scriptsig_type=scriptsig_type) unsigned_tx_hex = tx_hex prevout_index += 1 return tx_hex
csn
def multiprocessing_run(cmdlines, workers=None): """Distributes passed command-line jobs using multiprocessing. - cmdlines - an iterable of command line strings Returns the sum of exit codes from each job that was run. If all goes well, this should be 0. Anything else and the calling function should act accordingly. """ # Run jobs # If workers is None or greater than the number of cores available, # it will be set to the maximum number of cores pool = multiprocessing.Pool(processes=workers) results = [pool.apply_async(subprocess.run, (str(cline), ),
{'shell': sys.platform != "win32", 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE}) for cline in cmdlines] pool.close() pool.join() return sum([r.get().returncode for r in results])
csn_ccr
Return the vector scaled to length 1
function normalize (x, y) { const s = Math.hypot(x, y); return [x / s, y / s]; }
csn
Category list postprocessing routine, responsible building an sorting of hierarchical category tree
protected function _ppBuildTree() { $aTree = []; foreach ($this->_aArray as $oCat) { $sParentId = $oCat->oxcategories__oxparentid->value; if ($sParentId != 'oxrootid') { if (isset($this->_aArray[$sParentId])) { $this->_aArray[$sParentId]->setSubCat($oCat, $oCat->getId()); } } else { $aTree[$oCat->getId()] = $oCat; } } $this->assign($aTree); }
csn
@Override public void setProtocol(String protocol) throws Exception { this.protocol = protocol; if ("rtmps".equals(protocol) || "rtmpt".equals(protocol) || "rtmpte".equals(protocol) || "rtmfp".equals(protocol)) { throw
new Exception("Unsupported protocol specified, please use the correct client for the intended protocol."); } }
csn_ccr
You are the best freelancer in the city. Everybody knows you, but what they don't know, is that you are actually offloading your work to other freelancers and and you rarely need to do any work. You're living the life! To make this process easier you need to write a method called workNeeded to figure out how much time you need to contribute to a project. Giving the amount of time in `minutes` needed to complete the project and an array of pair values representing other freelancers' time in `[Hours, Minutes]` format ie. `[[2, 33], [3, 44]]` calculate how much time **you** will need to contribute to the project (if at all) and return a string depending on the case. * If we need to contribute time to the project then return `"I need to work x hour(s) and y minute(s)"` * If we don't have to contribute any time to the project then return `"Easy Money!"`
def work_needed(project_minutes, freelancers): available_minutes = sum(hours * 60 + minutes for hours, minutes in freelancers) workload_minutes = project_minutes - available_minutes if workload_minutes <= 0: return 'Easy Money!' else: hours, minutes = divmod(workload_minutes, 60) return 'I need to work {} hour(s) and {} minute(s)'.format(hours, minutes)
apps
Iterates over the List in reverse order executing the Procedure for each element
public static <T> void reverseForEach(List<T> list, Procedure<? super T> procedure) { if (!list.isEmpty()) { ListIterate.forEach(list, list.size() - 1, 0, procedure); } }
csn
def _parse_result(result): """ Parse ``clamscan`` output into same dictionary structured used by ``pyclamd``. Input example:: /home/bystrousak/Plocha/prace/test/eicar.com: Eicar-Test-Signature FOUND Output dict:: { "/home/bystrousak/Plocha/prace/test/eicar.com": ( "FOUND", "Eicar-Test-Signature" ) } """ lines = filter(lambda x: x.strip(), result.splitlines()) # rm blank lines
if not lines: return {} out = {} for line in lines: line = line.split(":") fn = line[0].strip() line = " ".join(line[1:]) line = line.rsplit(None, 1) status = line.pop().strip() out[fn] = (status, " ".join(line).strip()) return out
csn_ccr
making pie charts in python without external libraries
def house_explosions(): """ Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html """ chart = PieChart2D(int(settings.width * 1.7), settings.height) chart.add_data([10, 10, 30, 200]) chart.set_pie_labels([ 'Budding Chemists', 'Propane issues', 'Meth Labs', 'Attempts to escape morgage', ]) chart.download('pie-house-explosions.png')
cosqa
Add a step to the workflow. Args: step (Step): a step from the steps library.
def _add_step(self, step): """Add a step to the workflow. Args: step (Step): a step from the steps library. """ self._closed() self.has_workflow_step = self.has_workflow_step or step.is_workflow self.wf_steps[step.name_in_workflow] = step
csn
Indicates whether there are any patterns here. @return boolean Whether any patterns are in this container.
public function hasPatterns() { if ($this->isReference() && $this->getProject() !== null) { return $this->getRef($this->getProject())->hasPatterns(); } if ($this->defaultPatterns->hasPatterns()) { return true; } for ($i = 0, $size = count($this->additionalPatterns); $i < $size; $i++) { $ps = $this->additionalPatterns[$i]; if ($ps->hasPatterns()) { return true; } } return false; }
csn
def get_dataset(self, dataset_key): """Retrieve an existing dataset definition This method retrieves metadata about an existing :param dataset_key: Dataset identifier, in the form of owner/id :type dataset_key: str :returns: Dataset definition, with all attributes :rtype: dict :raises RestApiException: If a server error occurs Examples -------- >>> import datadotworld as dw >>> api_client = dw.api_client() >>> intro_dataset = api_client.get_dataset( ... 'jonloyens/an-intro-to-dataworld-dataset') #
doctest: +SKIP >>> intro_dataset['title'] # doctest: +SKIP 'An Intro to data.world Dataset' """ try: return self._datasets_api.get_dataset( *(parse_dataset_key(dataset_key))).to_dict() except _swagger.rest.ApiException as e: raise RestApiError(cause=e)
csn_ccr
def read(handle, bytes): """ Read chunk from an open file descriptor """
return Zchunk(lib.zchunk_read(coerce_py_file(handle), bytes), True)
csn_ccr
function ObmService(nodeId, obmServiceFactory, obmSettings, options) { assert.object(obmSettings); assert.object(obmSettings.config); assert.string(obmSettings.service); assert.func(obmServiceFactory); assert.isMongoId(nodeId); this.params = options || {}; this.retries = this.params.retries; this.delay = this.params.delay; if (this.params.delay !== 0) { this.delay = this.params.delay || config.get('obmInitialDelay') || 500; } if (this.params.retries !== 0) {
this.retries = this.params.retries || config.get('obmRetries') || 6; } this.serviceFactory = obmServiceFactory; this.obmConfig = obmSettings.config; this.serviceType = obmSettings.service; this.nodeId = nodeId; }
csn_ccr
func (c *Client) SnapshotCreateRepository(repository string) *SnapshotCreateRepositoryService
{ return NewSnapshotCreateRepositoryService(c).Repository(repository) }
csn_ccr
public function createDisposable($amount = 1, $reward = null, array $data = [], $expires_in = null) { return
$this->create($amount, $reward, $data, $expires_in, true); }
csn_ccr
def _find_known(row): """Find variant present in known pathogenic databases. """ out = [] clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic", "uncertain_significance", "uncertain_significance", "not_provided", "benign", "likely_benign"]) if row["cosmic_ids"]
or row["cosmic_id"]: out.append("cosmic") if row["clinvar_sig"] and not row["clinvar_sig"].lower() in clinvar_no: out.append("clinvar") return out
csn_ccr
public static function type_config_form($mform, $classname = 'repository') { global $OUTPUT; $a = new stdClass; $a->callbackurl = microsoft_skydrive::callback_url()->out(false); $mform->addElement('static', null, '', get_string('oauthinfo', 'repository_skydrive', $a)); $mform->addElement('static', null, '', $OUTPUT->notification(get_string('deprecatedwarning', 'repository_skydrive', $a))); parent::type_config_form($mform); $strrequired = get_string('required'); $mform->addElement('text', 'clientid', get_string('clientid', 'repository_skydrive'));
$mform->addElement('text', 'secret', get_string('secret', 'repository_skydrive')); $mform->addRule('clientid', $strrequired, 'required', null, 'client'); $mform->addRule('secret', $strrequired, 'required', null, 'client'); $mform->setType('clientid', PARAM_RAW_TRIMMED); $mform->setType('secret', PARAM_RAW_TRIMMED); }
csn_ccr
Helper function to set Array data to a object. @param Object $output @param mixed $source @return Object
private static function populateObject($output, $source) { $source = json_decode(json_encode($source), true); foreach($source as $key => $value) { $method = self::createMethodNames($key); // Changed method_exists() to is_callable() because of the magic functions // @source: http://php.net/manual/en/function.method-exists.php if(is_callable([$output, $method])) { call_user_func([$output, $method], $value); } } return $output; }
csn
func (c *CLI) SubcommandArgs() []string
{ c.once.Do(c.init) return c.subcommandArgs }
csn_ccr
protected function displayMenu() { foreach ($this->adminGroups->getUserGroups() as
$userGroup) { $this->menuGuiFactory->create($userGroup); } }
csn_ccr
public function findAllBySku($sku) { // initialize the params $params = array(MemberNames::SKU => $sku); // load and return the URL rewrite product category relations for the passed SKU
$this->urlRewriteProductCategoriesBySkuStmt->execute($params); return $this->urlRewriteProductCategoriesBySkuStmt->fetchAll(\PDO::FETCH_ASSOC); }
csn_ccr
public static function arrayToCsvFile($filename, $data) { $fp = fopen($filename, 'w'); foreach ($data as $fields) {
fputcsv($fp, $fields); } fclose($fp); }
csn_ccr
private boolean isValueOutOfRange(final Double value) { return value == null || getMinValue() != Double.NEGATIVE_INFINITY && value < getMinValue()
|| getMaxValue() != Double.POSITIVE_INFINITY && value > getMaxValue(); }
csn_ccr
function install(definition, Component) { const Ctor = register(definition, Component); // no dependencies if (!definition.components) { return Ctor; } const components = definition.components || {}; // avoid unnecessary re-registering for next time delete definition.components;
// register components for (const name in components) { Ctor.component(name, register(components[name], Component)); install(components[name], Component); } return Ctor; }
csn_ccr
private static function getHttpResponder(HttpRequest $request) { $responder = null; $responderClassName = $request->getResponderClassName(); if (class_exists($responderClassName)) { $responder = new $responderClassName($request);
Logger::get()->debug( "Responder '$responderClassName' is ready." ); } else { throw new \Eix\Services\Net\Http\NotFoundException( "'$responderClassName' responder not found." ); } return $responder; }
csn_ccr
// WaitUntilVolumeInUse uses the Amazon EC2 API operation // DescribeVolumes to wait for a condition to be met before returning. // If the condition is not met within the max attempt window, an error will // be returned.
func (c *EC2) WaitUntilVolumeInUse(input *DescribeVolumesInput) error { return c.WaitUntilVolumeInUseWithContext(aws.BackgroundContext(), input) }
csn
public function lowerThen($column, $value, $conjunction = 'AND') {
return $this->addExpression(new Condition\Basic($column, '<=', $value, $conjunction)); }
csn_ccr
def _interp1d(self): """Interpolate in one dimension. """ lines = len(self.hrow_indices) for num, data in enumerate(self.tie_data): self.new_data[num] = np.empty((len(self.hrow_indices), len(self.hcol_indices)),
data.dtype) for cnt in range(lines): tck = splrep(self.col_indices, data[cnt, :], k=self.ky_, s=0) self.new_data[num][cnt, :] = splev( self.hcol_indices, tck, der=0)
csn_ccr
func WriteConfigFile(configFilePath string, config *Config) { var buffer bytes.Buffer if err := configTemplate.Execute(&buffer, config); err != nil {
panic(err) } cmn.MustWriteFile(configFilePath, buffer.Bytes(), 0644) }
csn_ccr
Why would we want to stop to only 50 shades of grey? Let's see to how many we can go. Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `#010101`, `#020202`, etc. (using lower case letters). ```python def shades_of_grey(n): return '''n shades of grey in an array''' ``` As a reminder, the grey color is composed by the same number of red, green and blue: `#010101`, `#aeaeae`, `#555555`, etc. Also, `#000000` and `#ffffff` are not accepted values. When n is negative, just return an empty array. If n is higher than 254, just return an array of 254 elements. Have fun
def shades_of_grey(n): if n > 254: n = 254 return ["#%02x%02x%02x" % (i,i,i) for i in range(1,n+1)]
apps
Establishes the connection to the given WebSocket Server Address.
public void connect() { readyState = ReadyState.CONNECTING; try { if (webSocketHandler == null) { webSocketHandler = new WebSocketHandlerAdapter(); } container.connectToServer(new SimpleWebSocketClientEndpoint(), ClientEndpointConfig.Builder.create().build(), websocketURI); } catch (Exception e) { readyState = ReadyState.CLOSED; // throws DeploymentException, IOException throw new RuntimeException("could not establish connection"); } }
csn
//NewSelectableAttribute creates a new SelectableAttribute with a given chooser //a boolean attribute, a constant to be used when the chooser is false, and //attribute to used when the chooser is true. If you pass nil as the chooser //this call will create a new boolean attribute to use as the chooser and //it's initial value will be false. The attribute provided must not be nil.
func NewSelectableAttribute(chooser BooleanAttribute, unselectedValue Equaler, attr Attribute) *SelectableAttribute { cattr := chooser if cattr == nil { cattr = NewBooleanSimple(false) } result := &SelectableAttribute{ chooser: cattr, unselectedValue: unselectedValue, attr: attr, } result.AttributeImpl = NewAttribute(NORMAL, nil, nil) result.cons = NewSimpleConstraint(result.value, cattr, attr) result.AttributeImpl.Attach(result.cons) return result }
csn
Creates an default titleMap list from an enum, i.e. a list of strings.
function(enm) { var titleMap = []; //canonical titleMap format is a list. enm.forEach(function(name) { titleMap.push({name: name, value: name}); }); return titleMap; }
csn
// NewMockJobRenderer creates a new mock instance
func NewMockJobRenderer(ctrl *gomock.Controller) *MockJobRenderer { mock := &MockJobRenderer{ctrl: ctrl} mock.recorder = &MockJobRendererMockRecorder{mock} return mock }
csn
private function _doCreate($subPath, $params) { $fullPath = $this->_config->merchantPath() . $subPath;
$response = $this->_http->post($fullPath, $params); return $this->_verifyGatewayResponse($response); }
csn_ccr
Creates the actual layout. Must be called after all initial components are registered. Recourses through the configuration and sets up the item tree. If called before the document is ready it adds itself as a listener to the document.ready event @returns {void}
function() { if( document.readyState === 'loading' || document.body === null ) { $(document).ready( lm.utils.fnBind( this.init, this )); return; } this._setContainer(); this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container ); this.transitionIndicator = new lm.controls.TransitionIndicator(); this.updateSize(); this._create( this.config ); this._bindEvents(); this.isInitialised = true; this.emit( 'initialised' ); }
csn
def render_layout(self, app, path, alias=None): """Write to javascript.""" self.assign_routes(app) return ReactComponent( self.layout, self.src_file,
self.component_id, props=self.build_props(), static_path=path, alias=alias)
csn_ccr
public static String concatenateAndUriEncode(Collection<?> list, String delimiter) { Collection<String> escaped = new ArrayList<String>(); if (list != null) { for (Object object : list) {
escaped.add(encode(object.toString())); } } return StringUtils.concatenate(escaped, delimiter); }
csn_ccr
Send data ULP -> stream.
async def _send(self, stream_id, pp_id, user_data, expiry=None, max_retransmits=None, ordered=True): """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fragments = math.ceil(len(user_data) / USERDATA_MAX_LENGTH) pos = 0 for fragment in range(0, fragments): chunk = DataChunk() chunk.flags = 0 if not ordered: chunk.flags = SCTP_DATA_UNORDERED if fragment == 0: chunk.flags |= SCTP_DATA_FIRST_FRAG if fragment == fragments - 1: chunk.flags |= SCTP_DATA_LAST_FRAG chunk.tsn = self._local_tsn chunk.stream_id = stream_id chunk.stream_seq = stream_seq chunk.protocol = pp_id chunk.user_data = user_data[pos:pos + USERDATA_MAX_LENGTH] # initialize counters chunk._abandoned = False chunk._acked = False chunk._book_size = len(chunk.user_data) chunk._expiry = expiry chunk._max_retransmits = max_retransmits chunk._misses = 0 chunk._retransmit = False chunk._sent_count = 0 chunk._sent_time = None pos += USERDATA_MAX_LENGTH self._local_tsn = tsn_plus_one(self._local_tsn) self._outbound_queue.append(chunk) if ordered: self._outbound_stream_seq[stream_id] = uint16_add(stream_seq, 1) # transmit outbound data if not self._t3_handle: await self._transmit()
csn
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
29

Models trained or fine-tuned on benjamintli/code-retrieval-combined