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(subpat...
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.re...
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: workDa...
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, InternalExcept...
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_measure...
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; ...
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]); ...
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=...
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(ta...
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("gi...
// 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 mix...
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 = p...
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 ...
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_i...
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...
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: ...
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) respons...
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 blo...
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') >>> p...
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 = use...
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, 'list...
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...
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; ...
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; } ...
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...
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 Res...
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...
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] ...
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: ...
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(); ...
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 = ""; ...
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->getClassHi...
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]", DisableFl...
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)...
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 \ ...
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=F...
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") orde...
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 ...
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" { osS...
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'); ...
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 o...
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>...
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 ...
:= 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->...
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 i...
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 'r...
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 shou...
{'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]->s...
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...
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) ...
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": ( ...
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', ...
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->addi...
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 :rtyp...
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 RestApi...
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.r...
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", "likel...
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->...
$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->s...
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 // ...
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...
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(...
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 initi...
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, } re...
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.Transiti...
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 fra...
csn
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
30

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