query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
public void decreaseFontSize() { // move INTO range if we have just moved OUT of upper virtual if (inRange() || (atMax() && atUpperBoundary())) { currentFontIndex--; } else if (atMin()) {
lowerVirtualCount--; } else if (atMax() && inUpper()) { upperVirtualCount--; } }
csn_ccr
python see if file contains a line
def is_line_in_file(filename: str, line: str) -> bool: """ Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match) """ assert "\n" not in line with open(filename, "r") as file: for fileline in file: ...
cosqa
def invert build(precision: precision, deg: (deg + 180) % 360,
suffix: SUFFIX_INVERSIONS.fetch(suffix, suffix)) end
csn_ccr
Performs a query on one of the connection in this Pool. @return {comb.Promise} A promise to called back with a connection.
function () { var ret = new Promise(), conn; if (this.count > this.__maxObjects) { this.__deferredQueue.enqueue(ret); } else { //todo override getObject to make async so creating a connetion can execute setup sql conn = this.getObject()...
csn
Get the use statement to replace it with @return string
private function getUseStatement(): string { switch ($this->idTraitFqn) { case IdFieldTrait::class: $useStatement = 'use DSM\Fields\Traits\PrimaryKey\IdFieldTrait;'; break; case NonBinaryUuidFieldTrait::class: $useStatement = 'use DSM\F...
csn
Initialize the captcha extension to the given app object.
def init_app(self, app): """ Initialize the captcha extension to the given app object. """ self.enabled = app.config.get("CAPTCHA_ENABLE", True) self.digits = app.config.get("CAPTCHA_LENGTH", 4) self.max = 10**self.digits self.image_generator = ImageCaptcha() ...
csn
def for_compiler(self, compiler, platform): """Return a Linker object which is intended to be compatible with the given `compiler`.""" return (self.linker # TODO(#6143): describe why the compiler needs to be first on the PATH!
.sequence(compiler, exclude_list_fields=['extra_args', 'path_entries']) .prepend_field('path_entries', compiler.path_entries) .copy(exe_filename=compiler.exe_filename))
csn_ccr
on Unbind events on the things.
function() { var i, thingName, names = arguments; for ( i = 0, namesCount = names.length; i < namesCount; i += 1 ) { thingName = names[i] if ( thingName in STATE.methods ) { delete STATE.methods[thingName...
csn
protected function regenerateKeyCache() { if(is_array($this->__data)) { $i=0; $this->__keycache = array(); $this->__keycacheindex = array(); foreach($this->__data as $key => $value) { $this->__keycache[$key] = $i; ...
} } else { $this->__keycache = null; $this->__keycacheindex = null; } $this->__keycacheinvalid = false; }
csn_ccr
Add a servlet instance. @param name the servlet's name @param servlet the servlet instance @return a {@link javax.servlet.ServletRegistration.Dynamic} instance allowing for further configuration
public ServletRegistration.Dynamic addServlet(String name, Servlet servlet) { final ServletHolder holder = new NonblockingServletHolder(requireNonNull(servlet)); holder.setName(name); handler.getServletHandler().addServlet(holder); final ServletRegistration.Dynamic registration = holder...
csn
def _generate_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb...
for cur_alpha in model._dual_coef_[i]: svm.coefficients.alpha.append(cur_alpha) for cur_src_vector in model.support_vectors_: cur_dest_vector = svm.denseSupportVectors.vectors.add() for i in cur_src_vector: cur_dest_vector.values.append(i) return spec
csn_ccr
Creates a custom field array @param \ShopgateAddress | \ShopgateCustomer $object todo-sg: refactor this method into Shopgate\Extended\Customer own class @return array
public function getCustomFields($object) { $customFields = []; foreach ($object->getCustomFields() as $field) { $customFields[$field->getInternalFieldName()] = $field->getValue(); } return $customFields; }
csn
Handler for validate the response body. @param string $responseBody Content body of the response @return string
private function responseHandler($responseBody) { if ('json' === $this->outputFormat) { return $this->validateJsonResponse($responseBody); } return $this->validateXmlResponse($responseBody); }
csn
def getRemoteName(self, remote): """ Returns the name of the remote object if found in node registry. :param remote: the remote object """ if remote.name not in self.registry: find = [name for name,
ha in self.registry.items() if ha == remote.ha] assert len(find) == 1 return find[0] return remote.name
csn_ccr
python add path to modle
def _load_mod_ui_libraries(self, path): """ :param Path path: """ path = path / Path('mod') sys.path.append(str(path))
cosqa
Returns the file path from a given cache key, creating the relevant directory structure if necessary. @param string $key @return string
protected function getFilePathFromKey($key) { $key = basename($key); $badChars = ['-', '.', '_', '\\', '*', '\"', '?', '[', ']', ':', ';', '|', '=', ',']; $key = str_replace($badChars, '/', $key); while (strpos($key, '//') !== false) { $key = str_replace('//', '/', $key);...
csn
def list_tokens(self): """ ADMIN ONLY. Returns a dict containing tokens, endpoints, user info, and role metadata. """ resp, resp_body = self.method_get("tokens/%s"
% self.token, admin=True) if resp.status_code in (401, 403): raise exc.AuthorizationFailure("You must be an admin to make this " "call.") return resp_body.get("access")
csn_ccr
divide data into equal segments in python
def consecutive(data, stepsize=1): """Converts array into chunks with consecutive elements of given step size. http://stackoverflow.com/questions/7352684/how-to-find-the-groups-of-consecutive-elements-from-an-array-in-numpy """ return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)
cosqa
func (e *Signer) signConfigMap() { origCM := e.getConfigMap() if origCM == nil { return } var needUpdate = false newCM := origCM.DeepCopy() // First capture the config we are signing content, ok := newCM.Data[bootstrapapi.KubeConfigKey] if !ok { klog.V(3).Infof("No %s key in %s/%s ConfigMap", bootstrapa...
// Check to see if this signature is changed or new. oldSig, _ := sigs[tokenID] if sig != oldSig { needUpdate = true } delete(sigs, tokenID) newCM.Data[bootstrapapi.JWSSignatureKeyPrefix+tokenID] = sig } // If we have signatures left over we know that some signatures were // removed. We now need to...
csn_ccr
Create tag record by tag_name
def create_tag(tag_name, kind='z'): ''' Create tag record by tag_name ''' cur_recs = TabTag.select().where( (TabTag.name == tag_name) & (TabTag.kind == kind) ) if cur_recs.count(): uid = cur_recs.get().uid # TabTag.delete()...
csn
// initialize from a pre defined entry point
func (r *runtimeVerbose) Init(from string) { if r.hasInit { return } r.hasInit = true r.IsWindows = strings.Index(from, "\\") > -1 r.Gopath = r.determineGoPath(from) r.MainFile = from r.VerboseEnv = os.Getenv("VERBOSE") r.initVerboseRegexp() }
csn
URI getUrlAttribute(org.w3c.dom.Node attribute) throws InvalidInputException { String s = getStringAttribute(attribute); if (s == null) { return null; } try { return new URI(s); } catch (URISyntaxException e) {
throw new InvalidInputException("Invalid input: " + attribute.getLocalName() + " must be a URI value not \"" + s + "\""); } }
csn_ccr
function (identifier) { var path; if (identifier) { path = this.constructPath(constants.CHANNELS, identifier); return this.Core.DELETE(path); } else {
return this.rejectRequest('Bad Request: A channel identifier is required.'); } }
csn_ccr
// Out returns a Stepper that traverses all edges out of the Stepper's input verticies.
func Out(p []byte) *Stepper { return &Stepper{OPS, SPO, SPO, Triple{nil, p, nil, nil}, nil, make([]func(Path), 0, 0), nil} }
csn
func EncodeAuth(a *AuthConfig) string { authStr := a.Username + ":" + a.Password msg := []byte(authStr) encoded := make([]byte,
base64.StdEncoding.EncodedLen(len(msg))) base64.StdEncoding.Encode(encoded, msg) return string(encoded) }
csn_ccr
public function getBookId( $url ) { return get_blog_id_from_url(
wp_parse_url( $url, PHP_URL_HOST ), trailingslashit( wp_parse_url( $url, PHP_URL_PATH ) ) ); }
csn_ccr
Remove items in a buffer from the entity manager @param array $buffer
private function clearTokenBuffer(array $buffer) { foreach ($buffer as $bufferItem) { // Clear out associated access token if ($bufferItem instanceof AccessToken) { // We have to use this method of retrieving the entity because the refresh token // is ...
csn
protected function loadItemsForCurrentPage() { $items = $this->adapter->getItems($this->getOffset(), $this->itemsCountPerPage, $this->sort); if (!($items instanceof \Traversable)) {
$this->items = new \ArrayIterator($items); } else { $this->items = $items; } }
csn_ccr
Returns the prefixed table tags for a set of tables and rows. @param array $tables The tables to be tagged @param array $rows A multidimensional array containing the rows per table @return array
private function getTableTags($tables, $rows) { $tags = []; $type = $this->reflector->getType(); foreach ($tables as $table) { $isSpecific = (isset($rows[$table]) && !empty($rows[$table])); // These types of queries require a specific tag if (($type === ...
csn
function visit() { if (this.isBlacklisted()) return false; if (this.opts.shouldSkip && this.opts.shouldSkip(this)) return false; this.call("enter"); if (this.shouldSkip) { return this.shouldStop; } var node = this.node; var opts = this.opts; if (node) { if (Array.isArray(node)) { // tr...
for (var i = 0; i < node.length; i++) { _index2["default"].node(node[i], opts, this.scope, this.state, this, this.skipKeys); } } else { _index2["default"].node(node, opts, this.scope, this.state, this, this.skipKeys); this.call("exit"); } } return this.shouldStop; }
csn_ccr
// ExtractProperties returns a flat list of properties from a tree of steps. // If multiple step nodes have a property of the same name, the last one in the // preorder traversal wins.
func ExtractProperties(s *Step) (*structpb.Struct, error) { finals := map[string]json.RawMessage{} var extract func(s *Step) extract = func(s *Step) { for _, p := range s.Property { finals[p.Name] = json.RawMessage(p.Value) } for _, substep := range s.GetSubstep() { if ss := substep.GetStep(); ss != nil...
csn
def set_throttle(self, name): """ Assign to throttle group. """ if name.lower() == "null": name = "NULL" if name.lower() == "none": name = '' if name not in self._engine.known_throttle_names: if self._engine._rpc.throttle.up.max(xmlrpc.NOHASH,...
active = self.is_active if active: self._engine.LOG.debug("Torrent #%s stopped for throttling" % (self._fields["hash"],)) self.stop() self._make_it_so("setting throttle %r on" % (name,), ["throttle_name.set"], name) if active: self._engine.LOG.debug("Torrent...
csn_ccr
Applies the given functor to all elements in the input set. @param set the set to which the functor will be applied. @param state an state variable, that will be used as the return vale for the iteration. @param functor a function to be applied to all elements in the set. @return the state object after the processing.
public static final <S, E> S forEach(Set<E> set, S state, Fx<S, E> functor) { return new FunctionalSet<S, E>(set).forEach(state, functor); }
csn
def setter(self, can_set=None): """ Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set` :param can_set: boolean to change to it, and None to toggle :type can_set: Optional[bool] :return: self, so this can be used as a decorator like a `property` :...
""" if can_set is None: self._setter = not self._setter else: self._setter = bool(can_set) # For use as decorator return self
csn_ccr
def serialize(ad_objects, output_format='json', indent=2, attributes_only=False): """Serialize the object to the specified format :param ad_objects list: A list of ADObjects to serialize :param output_format str: The output format, json or yaml. Defaults to json :param indent int: The number of spaces...
# the first object in the list if attributes_only: ad_objects = [key for key in sorted(ad_objects[0].keys())] if output_format == 'json': return json.dumps(ad_objects, indent=indent, ensure_ascii=False, sort_keys=True) elif output_format == 'yaml': return yaml.dump(sorted(ad_ob...
csn_ccr
def parse_inline(self, text): """Parses text into inline elements. RawText is not considered in parsing but created as a wrapper of holes that don't match any other elements. :param text: the text to be parsed. :returns: a list of inline elements.
""" element_list = self._build_inline_element_list() return inline_parser.parse( text, element_list, fallback=self.inline_elements['RawText'] )
csn_ccr
// Convert_v1beta1_Policy_To_abac_Policy is an autogenerated conversion function.
func Convert_v1beta1_Policy_To_abac_Policy(in *Policy, out *abac.Policy, s conversion.Scope) error { return autoConvert_v1beta1_Policy_To_abac_Policy(in, out, s) }
csn
Ensure that OrientDB only considers desirable query start points in query planning.
def expose_ideal_query_execution_start_points(compound_match_query, location_types, coerced_locations): """Ensure that OrientDB only considers desirable query start points in query planning.""" new_queries = [] for match_query in compound_match_query.match_quer...
csn
Return directory list
def list(self, remote='.', extra=False, remove_relative_paths=False): """ Return directory list """ if extra: self.tmp_output = [] self.conn.dir(remote, self._collector) directory_list = split_file_info(self.tmp_output) else: directory_list = self....
csn
function delete($path) { $this->_path = $this->translate_uri($path); $this->header_unset(); $this->create_basic_request('DELETE'); /* $this->header_add('Content-Length: 0'); */ $this->header_add(''); $this->send_request(); $this->get_respond(); $response =...
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($this->_parser)), xml_get_current_line_number($this->_parser))); } print "<br>"; // Free resources ...
csn_ccr
public static Deferred<TSMeta> parseFromColumn(final TSDB tsdb, final KeyValue column, final boolean load_uidmetas) { if (column.value() == null || column.value().length < 1) { throw new IllegalArgumentException("Empty column value"); } final TSMeta parsed_meta = JSON.parseToObject(column.valu...
= UniqueId.uidToString(column.key()); } Deferred<TSMeta> meta = getFromStorage(tsdb, UniqueId.stringToUid(parsed_meta.tsuid)); if (!load_uidmetas) { return meta; } return meta.addCallbackDeferring(new LoadUIDs(tsdb, parsed_meta.tsuid)); }
csn_ccr
Replies the list of the symbolic names of the bundle dependencies. @return the bundle symbolic names of the dependencies.
public final Set<String> getBundleDependencies() { final Set<String> bundles = new TreeSet<>(); updateBundleList(bundles); return bundles; }
csn
def _get_metadata(field, expr, metadata_expr, no_metadata_rule): """Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'a...
The deltas or metadata table to use. """ if isinstance(metadata_expr, bz.Expr) or metadata_expr is None: return metadata_expr try: return expr._child['_'.join(((expr._name or ''), field))] except (ValueError, AttributeError): if no_metadata_rule == 'raise': ra...
csn_ccr
def _finalize_upload(self): """ Finalizes the upload on the API server. """ from sevenbridges.models.file import File try: response = self._api.post( self._URL['upload_complete'].format(upload_id=self._upload_id) ).json() self._...
self._status = TransferState.COMPLETED except SbgError as e: self._status = TransferState.FAILED raise SbgError( 'Failed to complete upload! Reason: {}'.format(e.message) )
csn_ccr
def execute_command_no_results(self, sock_info, generator): """Execute write commands with OP_MSG and w=0 WriteConcern, ordered. """ full_result = { "writeErrors": [], "writeConcernErrors": [], "nInserted": 0, "nUpserted": 0, "nMatched"...
when the application # specified unacknowledged writeConcern. write_concern = WriteConcern() op_id = _randint() try: self._execute_command( generator, write_concern, None, sock_info, op_id, False, full_result) except OperationFailure: ...
csn_ccr
static int compareLexical(BitStore a, BitStore b) { int aSize = a.size(); int bSize = b.size(); int diff = a.size() - b.size(); ListIterator<Integer> as = a.ones().positions(aSize); ListIterator<Integer> bs = b.ones().positions(bSize); while (true) { boolean ap = as.hasPrevious(); boolean bp = bs.hasP...
= as.previous(); int bi = bs.previous() + diff; if (ai == bi) continue; return ai > bi ? 1 : -1; } else { return bp ? -1 : 1; } } }
csn_ccr
tests whether host is in blacklist
function(host, whitelist, next) { var blacklist = this.options.blacklist; helper.resolveHost(host, function(err, aRecords, resolvedHost) { var inBlacklist = false; if (!err) { if (whitelist) { if (_.intersection(aRecords, whitelist).length ) { next(err, [], aRecords); ...
csn
def set_base_prompt(self, *args, **kwargs): """Remove the > when navigating into the different config level.""" cur_base_prompt = super(AlcatelSrosSSH, self).set_base_prompt(*args, **kwargs) match = re.search(r"(.*)(>.*)*#", cur_base_prompt)
if match: # strip off >... from base_prompt self.base_prompt = match.group(1) return self.base_prompt
csn_ccr
List all synchronized directories.
def ls(): ''' List all synchronized directories. ''' heading, body = cli_syncthing_adapter.ls() if heading: click.echo(heading) if body: click.echo(body.strip())
csn
Returns the ordering or ``None`` as uppercase string.
def get_ordering(self): """Returns the ordering or ``None`` as uppercase string.""" _, ordering = self.token_next_by(t=T.Keyword.Order) return ordering.normalized if ordering else None
csn
function (cb) { sails.log.verbose('Loading app Gulpfile...'); // Start task depending on environment
if(sails.config.environment === 'production'){ return this.runTask('prod', cb); } this.runTask('default', cb); }
csn_ccr
protected void closeDrawerDelayed() { if (mCloseOnClick && mDrawerLayout != null) { if (mDelayOnDrawerClose > -1) { new Handler().postDelayed(new Runnable() { @Override public void run() { mDrawerLayout.closeDrawers(); ...
mRecyclerView.smoothScrollToPosition(0); } } }, mDelayOnDrawerClose); } else { mDrawerLayout.closeDrawers(); } } }
csn_ccr
Gets the page's member groups @param Page $page @return Membergroup[] Returns the member groups assigned to the page
static function PageMembergroups(Page $page) { if (!$page->Exists()) { return array(); } $sql = Access::SqlBuilder(); $tblPmg = PageMembergroup::Schema()->Table(); $tblMg = Membergroup::Schema()->Table(); $join = $sql->Join($tblPmg); $joinC...
csn
protected function extractQueryString($path) { if (($queryPosition = strpos($path, '?')) !== false) { return [ substr($path, 0, $queryPosition),
substr($path, $queryPosition), ]; } return [$path, '']; }
csn_ccr
Using the method to create Loose config's Archive entry config @param looseConfig @param looseFile @param bootProps @return @throws IOException
public static ArchiveEntryConfig createLooseArchiveEntryConfig(LooseConfig looseConfig, File looseFile, BootstrapConfig bootProps, String archiveEntryPrefix, boolean isUsr) throws IOException { File usrRoot = bootProps.getUserRoot(); int...
csn
private function getNewOffset(): int { while ( $this->offsetExists(
$this->indexOffset ) ) { $this->indexOffset++; } return $this->indexOffset; }
csn_ccr
func (fbh *FileBackupHandle) EndBackup(ctx context.Context) error { if fbh.readOnly {
return fmt.Errorf("EndBackup cannot be called on read-only backup") } return nil }
csn_ccr
Asynchronous decrement. @param key key to decrement @param by the amount to decrement the value by @param def the default value (if the counter does not exist) @param exp the expiration of this object @return a future with the decremented value, or -1 if the decrement failed. @throws IllegalStateException in the rare ...
@Override public OperationFuture<Long> asyncDecr(String key, int by, long def, int exp) { return asyncMutate(Mutator.decr, key, by, def, exp); }
csn
Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiDeleteError instances for each object that had a delete error.
def remove_objects(self, bucket_name, objects_iter): """ Removes multiple objects from a bucket. :param bucket_name: Bucket from which to remove objects :param objects_iter: A list, tuple or iterator that provides objects names to delete. :return: An iterator of MultiD...
csn
Read a close frame.
private void readClose(FrameIn fIs) throws IOException { if (_state.isClosed()) { return; } _state = _state.closePeer(); int code = fIs.readClose(); StringBuilder sb = new StringBuilder(); fIs.readText(sb); if (_service != null) { WebSocketClose codeWs = WebSocketCloses...
csn
def get_module_item_sequence(self, course_id, asset_id=None, asset_type=None): """ Get module item sequence. Given an asset in a course, find the ModuleItem it belongs to, and also the previous and next Module Items in the course sequence. """ path = {} d...
params["asset_type"] = asset_type # OPTIONAL - asset_id """The id of the asset (or the url in the case of a Page)""" if asset_id is not None: params["asset_id"] = asset_id self.logger.debug("GET /api/v1/courses/{course_id}/module_item_sequence with query...
csn_ccr
@Override public String getString(Object value) { try { return DATE_TIME_FORMAT.format(value); } catch (IllegalArgumentException ignore) {
// There's not much that can be done. } return StringValues.TO_STRING.getString(value); }
csn_ccr
public static Bitmap decodeStream(InputStream stream, boolean closeStream) { return AsyncBitmapTexture.decodeStream(stream, AsyncBitmapTexture.glMaxTextureSize,
AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream); }
csn_ccr
private function _writePrintSettings($objWriter) { $objWriter->startElement('c:printSettings'); $objWriter->startElement('c:headerFooter'); $objWriter->endElement(); $objWriter->startElement('c:pageMargins'); $objWriter->writeAttribute('footer', 0.3); $objWriter->writeAttribute('header', 0.3); ...
$objWriter->writeAttribute('t', 0.75); $objWriter->writeAttribute('b', 0.75); $objWriter->endElement(); $objWriter->startElement('c:pageSetup'); $objWriter->writeAttribute('orientation', "portrait"); $objWriter->endElement(); $objWriter->endElement(); }
csn_ccr
// SetRollback sets the flag indicating that the transaction must be rolled back. // The call is a no-op if the session is not in a transaction.
func (session *SafeSession) SetRollback() { if session == nil || session.Session == nil || !session.Session.InTransaction { return } session.mu.Lock() defer session.mu.Unlock() session.mustRollback = true }
csn
Use this API to fetch auditnslogpolicy_systemglobal_binding resources of given name .
public static auditnslogpolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{ auditnslogpolicy_systemglobal_binding obj = new auditnslogpolicy_systemglobal_binding(); obj.set_name(name); auditnslogpolicy_systemglobal_binding response[] = (auditnslogpolicy_systemglobal_binding[]) ...
csn
func (d *Decoder) decodeScalefactorSelectionInformation2() error { for sb := 0; sb < 32; sb++ { for ch := 0; ch < d.nChannels; ch++ { if d.allocation[ch][sb] != 0 { scfsi, err := d.stream.readBits(2)
if err != nil { return err } d.scfsi2[ch][sb] = scfsi } } } return nil }
csn_ccr
// BinPath returns the path of the executable binary file.
func (k *InstalledKite) BinPath() string { return filepath.Join(k.Domain, k.User, k.Repo, k.Version, "bin", strings.TrimSuffix(k.Repo, ".kite")) }
csn
remove comments in json file using python
def parse_json(filename): """ Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or /* ... */ """ # Regular expression for comments comment_re = re.compile( '(^)?[^\S\n]*...
cosqa
Return our corresponding evdev device object
def evdev_device(self): """ Return our corresponding evdev device object """ devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: if device.name == self.evdev_device_name: return device raise Exception("%s: ...
csn
Retrieve the websites's social presence. @throws \Exception If the given context does not have access to config. @return array
public function socialNetworks() { if ($this->socialNetworks) { return $this->socialNetworks; } $socials = json_decode($this->cmsConfig()['social_medias'], true); $configMeta = $this->configModel()->p('social_medias')->structureMetadata(); foreach ($socials as $...
csn
def weld_arrays_to_vec_of_struct(arrays, weld_types): """Create a vector of structs from multiple vectors. Parameters ---------- arrays : list of (numpy.ndarray or WeldObject) Arrays to put in a struct. weld_types : list of WeldType The Weld types of the arrays in the same order. ...
|b: appender[{res_types}], i: i64, e: {input_types}| merge(b, {to_merge}) ) )""" weld_obj.weld_code = weld_template.format(arrays=arrays, input_types=input_types, res_types=res_types, ...
csn_ccr
// SetMoveToColdStorageAfterDays sets the MoveToColdStorageAfterDays field's value.
func (s *Lifecycle) SetMoveToColdStorageAfterDays(v int64) *Lifecycle { s.MoveToColdStorageAfterDays = &v return s }
csn
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer { $buffer = new Writer(); $buffer->writeUInt8($this->type); $buffer->writeUInt32($this->timestamp); $buffer->writeHex($this->senderPublicKey); $skipRecipientId = $this->type === Typ...
$buffer->writeString($this->asset['delegate']['username']); } if (Types::VOTE === $this->type) { $buffer->writeString(implode('', $this->asset['votes'])); } if (Types::MULTI_SIGNATURE_REGISTRATION === $this->type) { $buffer->writeUInt8($this->asset['multisig...
csn_ccr
function padRight(str, max, chr) { str = str != null ? str : '' str = String(str) var length = max - wcwidth(str)
if (length <= 0) return str return str + repeatString(chr || ' ', length) }
csn_ccr
method for verify extension file @return boolean true - file is image, false - file not image
private function verifyExtensionFile() { $supported_image = array( 'gif', 'jpg', 'jpeg', 'png' ); $fileName = $_SERVER['HTTP_X_FILE_NAME']; $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (in_array($ext, $suppor...
csn
public void document_id_DELETE(String id) throws IOException { String qPath
= "/me/document/{id}"; StringBuilder sb = path(qPath, id); exec(qPath, "DELETE", sb.toString(), null); }
csn_ccr
Process a collection of ingested sources to make source tables.
def source_schema(self, sources=None, tables=None, clean=False): """Process a collection of ingested sources to make source tables. """ sources = self._resolve_sources(sources, tables, None, predicate=lambda s: s.is_processable) for source in sources: ...
csn
Get a raw value from any type of steam id @param $id @param $type @param $matches
private function getRawValue($id, $type, $matches) { switch ($type) { case 'ID32': $this->rawValue = bcmul($matches[2], '2', 0); $this->rawValue = bcadd($this->rawValue, $matches[1], 0); $this->formatted->{self::$ID32} = $id; brea...
csn
@Override public void onNewRouteProgress(Location location, RouteProgress routeProgress) {
notificationProvider.updateNavigationNotification(routeProgress); eventDispatcher.onProgressChange(location, routeProgress); }
csn_ccr
// EnableJournaling creates a JournalManager and attaches it to // this config. journalRoot must be non-empty. Errors returned are // non-fatal.
func (c *ConfigLocal) EnableJournaling( ctx context.Context, journalRoot string, bws TLFJournalBackgroundWorkStatus) error { jManager, err := GetJournalManager(c) if err == nil { // Journaling shouldn't be enabled twice for the same // config. return errors.New("trying to enable journaling twice") } if c.d...
csn
function checkThresholds(metrics, thresholds) { if (!elv(thresholds)) return; const target = metrics[thresholds.target]; for (let i = 0; i < metrics.length; i++) { if (i === thresholds.target) continue; const other = metrics[i];
assertThreshold(target.avg, other.avg, thresholds.avg); assertThreshold(target.max, other.max, thresholds.max); assertThreshold(target.min, other.min, thresholds.min); } }
csn_ccr
def timestamp_to_local_time_str( timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"): """Convert epoch timestamp to a localized datetime string. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone
The timezone of the desired local time. fmt : str The format of the output string. Returns ------- str The localized datetime string. """ localized_d = timestamp_to_local_time(timestamp, timezone_name) localized_datetime_str = localized_d.format_datetime(fmt) retu...
csn_ccr
def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self.pattern = wait self.env = env self.args = args
# wait is a function, supersedes the default behavior if callable(wait): self.wait = lambda lines: wait()
csn_ccr
def set(self, name, value, **kw): """Set the attribute to the given value. The keyword arguments represent the other attribute values to integrate constraints to other values. """ # check write permission sm = getSecurityManager() permission = permissions.Manage...
raise Unauthorized("Not allowed to modify the Plone portal") # set the attribute if not hasattr(self.context, name): return False self.context[name] = value return True
csn_ccr
// If this is called in a threaded context, it MUST be synchronized
func (w *FileLogWriter) intRotate() error { // Close any log file that may be open if w.file != nil { fmt.Fprint(w.file, FormatLogRecord(w.trailer, &LogRecord{Created: time.Now()})) w.file.Close() } // If we are keeping log files, move it to the next available number if w.rotate { _, err := os.Lstat(w.filen...
csn
public function input($name, $options = array()) { $options += array( "type" => "text", "id" => $this->id($name), "name" => $this->name($name), "error" => true, "class" => "", "value" => "", "label" => null ); ...
} $fieldHasErrors = true; $options['class'] .= " error "; } } unset($options["error"]); $label = ""; if (!is_null($options['label'])) { $labelOptions = array( "for" => $options["id"], "class" => ...
csn_ccr
@SuppressWarnings("unchecked") public T dictionary(String dictionaryName) { Assert.notNull(applicationContext, "Citrus application context
is not initialized!"); DataDictionary dictionary = applicationContext.getBean(dictionaryName, DataDictionary.class); getAction().setDataDictionary(dictionary); return self; }
csn_ccr
// HasRight checks if an AccessKey has a certain right
func (k *AccessKey) HasRight(right Right) bool { for _, r := range k.Rights { if r == right { return true } } return false }
csn
public function isEnabled($storeId) { return $this->scopeConfig->isSetFlag(
self::XML_PATH_DDG_TRANSACTIONAL_ENABLED, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId ); }
csn_ccr
public static <T> Collection<T> collect(Iterable<T> stream) { LinkedList<T> collection = new LinkedList<>(); for (T e : stream) {
collection.add(e); } return collection; }
csn_ccr
protected ComponentModel getOrCreateComponentModel() { ComponentModel model = getComponentModel(); if (locked && model == sharedModel) { UIContext effectiveContext = UIContextHolder.getCurrent(); if (effectiveContext != null) { model = newComponentModel();
model.setSharedModel(sharedModel); effectiveContext.setModel(this, model); initialiseComponentModel(); } } return model; }
csn_ccr
func (va *ValidationAuthorityImpl) validate( ctx context.Context, identifier core.AcmeIdentifier, challenge core.Challenge, authz core.Authorization, ) ([]core.ValidationRecord, *probs.ProblemDetails) { // If the identifier is a wildcard domain we need to validate the base // domain by removing the "*." wildcard...
= strings.TrimPrefix(identifier.Value, "*.") } // va.checkCAA accepts wildcard identifiers and handles them appropriately so // we can dispatch `checkCAA` with the provided `identifier` instead of // `baseIdentifier` ch := make(chan *probs.ProblemDetails, 1) go func() { params := &caaParams{ accountURIID: ...
csn_ccr
Return the text internal @param $type @param $tag @return null
public function text($type, $tag) { $this->deprecate('text'); if (isset($this->text[$type])) return $this->text[$type]->get($tag); return null; }
csn
Browse Todos. @param AnCommandContext $context
protected function _actionBrowse($context) { if (!$context->query) { $context->query = $this->getRepository()->getQuery(); } $query = $context->query; $query->order('open', 'DESC'); if ($this->sort == 'priority') { $query->order('priority', 'DESC'); ...
csn
private GraduateStudents getGraduateStudents( OtherPersonnelDto otherPersonnel) { GraduateStudents graduate = GraduateStudents.Factory.newInstance(); if (otherPersonnel != null) { graduate.setNumberOfPersonnel(otherPersonnel.getNumberPersonnel()); graduate.setProject...
graduate.setAcademicMonths(sectBCompType.getAcademicMonths().bigDecimalValue()); graduate.setCalendarMonths(sectBCompType.getCalendarMonths().bigDecimalValue()); graduate.setFundsRequested(sectBCompType.getFundsRequested().bigDecimalValue()); graduate.setSummerMonths(sectBCompTyp...
csn_ccr
func WorkspaceFor(source string) (*Workspace, error) { gopaths := envOr("GOPATH", build.Default.GOPATH) // We use absolute paths so that in particular on Windows the case gets normalized sourcePath, err := filepath.Abs(source) if err != nil { sourcePath = source } if os.Getenv("GO111MODULE") != "on" { // GOPATH...
nil } } } if os.Getenv("GO111MODULE") != "off" { // Module mode root, _ := findModuleRoot(sourcePath, "", false) if root != "" { return &Workspace{ gopath: gopaths, isModuleMode: true, Path: root, }, nil } } return nil, fmt.Errorf(`Go source file "%s" not in Go workspace,...
csn_ccr
Retrieve the number of valid ezxmltext occurences @return int
public function xmlTextContentObjectAttributeCount() { if ( $this->xmlAttrCount === null ) { $this->xmlAttrCount = eZContentObjectAttribute::fetchListByClassID( $this->xmlClassAttributeIds(), false, null, false, true ); } return $this->xmlAttrCount; }
csn
func (w *Waveform) setScale(x uint, y uint) error { // X scale cannot be zero if x == 0 { return errScaleXZero } // Y scale cannot be zero if y ==
0 { return errScaleYZero } w.scaleX = x w.scaleY = y return nil }
csn_ccr
public void setArduinoEnabled(boolean enable) { Buffer buffer = new Buffer(); buffer.writeByte(enable ? 1 : 0);
sendMessage(BeanMessageID.CC_POWER_ARDUINO, buffer); }
csn_ccr