comment
stringlengths
16
255
code
stringlengths
52
3.87M
Create a new NotificationInstance @param array|Options $options Optional Arguments @return NotificationInstance Newly created NotificationInstance @throws TwilioException When an HTTP error occurs.
public function create($options = array()) { $options = new Values($options); $data = Values::of(array( 'Identity' => Serialize::map($options['identity'], function($e) { return $e; }), 'Tag' => Serialize::map($options['tag'], function($e) { return $e; }), 'Body' => $options['body'], 'Priority' => $options['priority'], 'Ttl' => $options['ttl'], 'Title' => $options['title'], 'Sound' => $options['sound'], 'Action' => $options['action'], 'Data' => Serialize::jsonObject($options['data']), 'Apn' => Serialize::jsonObject($options['apn']), 'Gcm' => Serialize::jsonObject($options['gcm']), 'Sms' => Serialize::jsonObject($options['sms']), 'FacebookMessenger' => Serialize::jsonObject($options['facebookMessenger']), 'Fcm' => Serialize::jsonObject($options['fcm']), 'Segment' => Serialize::map($options['segment'], function($e) { return $e; }), 'Alexa' => Serialize::jsonObject($options['alexa']), 'ToBinding' => Serialize::map($options['toBinding'], function($e) { return $e; }), )); $payload = $this->version->create( 'POST', $this->uri, array(), $data ); return new NotificationInstance($this->version, $payload, $this->solution['serviceSid']); }
Get fields as properties @param obj the object to get fields for @param clazzes the classes to use for reflection and properties. T @return the fields as properties
public static Properties getFieldsAsProperties(Object obj, Class<?>[] clazzes) throws Exception { Properties props = new Properties(); for (Field field : obj.getClass().getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) continue; field.setAccessible(true); Class<?> type = field.getType(); if (clazzes == null || contains(type, clazzes)) { Object val = field.get(obj); if (val != null) props.put(field.getName(), val.toString()); } } return props; }
// SetDefaultValue sets the DefaultValue field's value.
func (s *IntArrayOptions) SetDefaultValue(v int64) *IntArrayOptions { s.DefaultValue = &v return s }
Compares the content of the specified buffer to the content of this buffer. This comparison is performed byte by byte using an unsigned comparison.
@SuppressWarnings("ObjectEquality") @Override public int compareTo(Slice that) { if (this == that) { return 0; } return compareTo(0, size, that, 0, that.size); }
Resets order shipping date.
public function resetOrder() { $oOrder = oxNew(\OxidEsales\Eshop\Application\Model\Order::class); if ($oOrder->load($this->getEditObjectId())) { $oOrder->oxorder__oxsenddate = new \OxidEsales\Eshop\Core\Field("0000-00-00 00:00:00"); $oOrder->save(); $this->onOrderReset(); } }
Load options from CONFIG if it exists
def load_config (symbolise = lambda do |h| h.is_a?(Hash) ? Hash[h.map { |k, v| [k.intern, symbolise[v]] }] : h end)[YAML.load_file CONFIG] if File.readable? CONFIG rescue => e warn "Failed to load #{ CONFIG }: #{ e }" end
BELScript.g:70:1: set_annotation : 'SET' OBJECT_IDENT '=' ( quoted_value | vl= VALUE_LIST | OBJECT_IDENT ) ;
public final BELScriptParser.set_annotation_return set_annotation() throws RecognitionException { BELScriptParser.set_annotation_return retval = new BELScriptParser.set_annotation_return(); retval.start = input.LT(1); Object root_0 = null; Token vl=null; Token string_literal24=null; Token OBJECT_IDENT25=null; Token char_literal26=null; Token OBJECT_IDENT28=null; BELScriptParser.quoted_value_return quoted_value27 = null; Object vl_tree=null; Object string_literal24_tree=null; Object OBJECT_IDENT25_tree=null; Object char_literal26_tree=null; Object OBJECT_IDENT28_tree=null; paraphrases.push("in set annotation."); try { // BELScript.g:73:5: ( 'SET' OBJECT_IDENT '=' ( quoted_value | vl= VALUE_LIST | OBJECT_IDENT ) ) // BELScript.g:74:5: 'SET' OBJECT_IDENT '=' ( quoted_value | vl= VALUE_LIST | OBJECT_IDENT ) { root_0 = (Object)adaptor.nil(); string_literal24=(Token)match(input,24,FOLLOW_24_in_set_annotation277); string_literal24_tree = (Object)adaptor.create(string_literal24); adaptor.addChild(root_0, string_literal24_tree); OBJECT_IDENT25=(Token)match(input,OBJECT_IDENT,FOLLOW_OBJECT_IDENT_in_set_annotation279); OBJECT_IDENT25_tree = (Object)adaptor.create(OBJECT_IDENT25); adaptor.addChild(root_0, OBJECT_IDENT25_tree); char_literal26=(Token)match(input,25,FOLLOW_25_in_set_annotation281); char_literal26_tree = (Object)adaptor.create(char_literal26); adaptor.addChild(root_0, char_literal26_tree); // BELScript.g:74:28: ( quoted_value | vl= VALUE_LIST | OBJECT_IDENT ) int alt5=3; switch ( input.LA(1) ) { case QUOTED_VALUE: { alt5=1; } break; case VALUE_LIST: { alt5=2; } break; case OBJECT_IDENT: { alt5=3; } break; default: NoViableAltException nvae = new NoViableAltException("", 5, 0, input); throw nvae; } switch (alt5) { case 1 : // BELScript.g:74:29: quoted_value { pushFollow(FOLLOW_quoted_value_in_set_annotation284); quoted_value27=quoted_value(); state._fsp--; adaptor.addChild(root_0, quoted_value27.getTree()); } break; case 2 : // BELScript.g:74:44: vl= VALUE_LIST { vl=(Token)match(input,VALUE_LIST,FOLLOW_VALUE_LIST_in_set_annotation290); vl_tree = (Object)adaptor.create(vl); adaptor.addChild(root_0, vl_tree); } break; case 3 : // BELScript.g:74:60: OBJECT_IDENT { OBJECT_IDENT28=(Token)match(input,OBJECT_IDENT,FOLLOW_OBJECT_IDENT_in_set_annotation294); OBJECT_IDENT28_tree = (Object)adaptor.create(OBJECT_IDENT28); adaptor.addChild(root_0, OBJECT_IDENT28_tree); } break; } // https://github.com/OpenBEL/openbel-framework/issues/14 if (vl != null) vl.setText(vl.getText().replace("\\\\", "\\")); } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); paraphrases.pop(); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; }
Indicates whether the document has a vote from particular voter object. @param [Mongoid::Document] voted_by object from which the vote was done @return [Boolean]
def voted_by?(voted_by) !!votes.find_by(voted_by_id: voted_by.id) rescue NoMethodError, Mongoid::Errors::DocumentNotFound false end
Register Providers
function registerProviders () { Object.keys(settings.providers).forEach(function (id) { var providerConf = settings.providers[id] var provider = providers[id] ? providers[id] : providerConf var strategy = protocols.initialize(id, provider, providerConf) strategies[id] = strategy }) }
Adds a job to @jobs array @param (Parser::Schedule) :schedule is object of Parser::Schedule class @param (Parser::Command) :command is object of Parser::Command class
def add_job(opts={}) @jobs << Job.new( Parser::Schedule.new(opts[:schedule]), Parser::Command.new(opts[:command])) end
--- RegistryClientV2 Create a new Docker Registry V2 client for a particular repository. @param opts.insecure {Boolean} Optional. Default false. Set to true to *not* fail on an invalid or self-signed server certificate. ... TODO: lots more to document
function RegistryClientV2(opts) { var self = this; assert.object(opts, 'opts'); // One of `opts.name` or `opts.repo`. assert.ok((opts.name || opts.repo) && !(opts.name && opts.repo), 'exactly one of opts.name or opts.repo must be given'); if (opts.name) { assert.string(opts.name, 'opts.name'); } else { assert.object(opts.repo, 'opts.repo'); } assert.optionalObject(opts.log, 'opts.log'); assert.optionalString(opts.username, 'opts.username'); if (opts.username) { assert.string(opts.password, 'opts.password required if username given'); } else { assert.optionalString(opts.password, 'opts.password'); } assert.optionalString(opts.token, 'opts.token'); // for Bearer auth assert.optionalBool(opts.insecure, 'opts.insecure'); assert.optionalString(opts.scheme, 'opts.scheme'); assert.optionalBool(opts.acceptManifestLists, 'opts.acceptManifestLists'); assert.optionalNumber(opts.maxSchemaVersion, 'opts.maxSchemaVersion'); // TODO: options to control the trust db for CA verification // TODO add passing through other restify options: userAgent, ... // Restify/Node HTTP client options. assert.optionalBool(opts.agent, 'opts.agent'); assert.optionalString(opts.userAgent, 'opts.userAgent'); this.log = _createLogger(opts.log); this.insecure = Boolean(opts.insecure); if (opts.name) { this.repo = common.parseRepo(opts.name); } else { this.repo = common.deepObjCopy(opts.repo); } if (opts.scheme) { this.repo.index.scheme = opts.scheme; } else if (!this.repo.index.scheme && common.isLocalhost(this.repo.index.name)) { // Per docker.git:registry/config.go#NewServiceConfig we special // case localhost to allow HTTP. Note that this lib doesn't do // the "try HTTPS, then fallback to HTTP if allowed" thing that // Docker-docker does, we'll just prefer HTTP for localhost. this.repo.index.scheme = 'http'; } this.acceptManifestLists = opts.acceptManifestLists || false; this.maxSchemaVersion = opts.maxSchemaVersion || 1; this.username = opts.username; this.password = opts.password; this._loggedIn = false; this._loggedInScope = null; // Keeps track of the login type. this._authInfo = null; this._headers = {}; _setAuthHeaderFromAuthInfo(this._headers, { token: opts.token, username: opts.username, password: opts.password }); // XXX relevant for v2? //this._cookieJar = new tough.CookieJar(); if (this.repo.index.official) { // v1 this._url = DEFAULT_V2_REGISTRY; } else { this._url = common.urlFromIndex(this.repo.index); } this.log.trace({url: this._url}, 'RegistryClientV2 url'); this._commonHttpClientOpts = { log: this.log, agent: opts.agent, proxy: opts.proxy, rejectUnauthorized: !this.insecure, userAgent: opts.userAgent || common.DEFAULT_USERAGENT }; this._clientsToClose = []; Object.defineProperty(this, '_api', { get: function () { if (self.__api === undefined) { self.__api = new DockerJsonClient(common.objMerge({ url: self._url }, self._commonHttpClientOpts)); self._clientsToClose.push(self.__api); } return this.__api; } }); Object.defineProperty(this, '_httpapi', { get: function () { if (self.__httpapi === undefined) { self.__httpapi = new restifyClients.HttpClient(common.objMerge({ url: self._url }, self._commonHttpClientOpts)); self._clientsToClose.push(self.__httpapi); } return this.__httpapi; } }); }
Executes given SQL statement. @param string $queryString @return mysqli_result|bool @throws DriverException
public function runQuery($queryString){ $this->affectedRows = false; $result = $this->resource->query($queryString, $this->unbuffered ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT); $error = preg_replace('~You have an error in your SQL syntax; check the manual that corresponds to your \w+ server version for the right syntax to use~i', 'Syntax error', $this->resource->error); if($error && $result === false) throw new DriverException($error, $this->resource->errno, $queryString); $this->affectedRows = $this->resource->affected_rows; return $result; }
Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation.
def weld_str_lower(array): obj_id, weld_obj = create_weld_object(array) weld_template = """map( {array}, |e: vec[i8]| result( for(e, appender[i8], |c: appender[i8], j: i64, f: i8| if(f > 64c && f < 91c, merge(c, f + 32c), merge(c, f)) ) ) )""" weld_obj.weld_code = weld_template.format(array=obj_id) return weld_obj
Set the config. @param array $config @param string $section @param string $table @return array
public function setConfig($config, $section, $table) { if (!empty($section)) { foreach ($config as $key => $value) { $config[$key] = str_replace('_table_', ucfirst($table), str_replace('_section_', ucfirst($section), str_replace('_sectionLowerCase_', strtolower($section), $value))); } } else { foreach ($config as $key => $value) { $config[$key] = str_replace('_table_', ucfirst($table), $value); } } return $config; }
Gets the splits from Stash for the given table.
public Collection<String> getSplits(String table) throws StashNotAvailableException, TableNotStashedException { try { return FluentIterable.from(_stashReader.getSplits(table)) .transform(Functions.toStringFunction()) .toList(); } catch (TableNotStashedException e) { throw propagateTableNotStashed(e); } }
getParentMenu 0 = unpublish 1 = publish
public static function getParentMenu($publish=null, $parent=null, $type=null) { $criteria=new CDbCriteria; if($publish != null) $criteria->compare('t.publish',$publish); if($parent != null) $criteria->compare('t.parent_id',$parent); $model = self::model()->findAll($criteria); if($type == null) { $items = array(); if($model != null) { foreach($model as $key => $val) { $items[$val->id] = $val->title->message; } return $items; } else { return false; } } else return $model; }
Marshall the given parameter object.
public void marshall(TagResourceRequest tagResourceRequest, ProtocolMarshaller protocolMarshaller) { if (tagResourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tagResourceRequest.getResource(), RESOURCE_BINDING); protocolMarshaller.marshall(tagResourceRequest.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Monitor the original element for changes and update select2 accordingly abstract
function () { this.opts.element.bind("change.select2", this.bind(function (e) { if (this.opts.element.data("select2-change-triggered") !== true) { this.initSelection(); } })); }
Async resolve a files path using nodes module resolution. @param {string} dir - the directory to look in. @param {string} file - the file to find. @return {Promise<string>}
function resolveFile (dir, file) { return new Promise((resolve, reject) => { resolver.resolve({}, dir, file, (err, result) => { if (err) reject(err) else resolve(result) }) }) }
Indent selected text :param cursor: QTextCursor
def indent_selection(self, cursor): doc = self.editor.document() tab_len = self.editor.tab_length cursor.beginEditBlock() nb_lines = len(cursor.selection().toPlainText().splitlines()) c = self.editor.textCursor() if c.atBlockStart() and c.position() == c.selectionEnd(): nb_lines += 1 block = doc.findBlock(cursor.selectionStart()) i = 0 # indent every lines while i < nb_lines: nb_space_to_add = tab_len cursor = QtGui.QTextCursor(block) cursor.movePosition(cursor.StartOfLine, cursor.MoveAnchor) if self.editor.use_spaces_instead_of_tabs: for _ in range(nb_space_to_add): cursor.insertText(" ") else: cursor.insertText('\t') block = block.next() i += 1 cursor.endEditBlock()
Unload all the CSS dependencies of a template. This function does not trigger a DOM update. CSS style elements are only removed if not needed during the next CSS insertion. @param {aria.templates.TemplateCtxt} tplCtxt template context
function (tplCtxt) { this.$assert(169, tplCtxt.$TemplateCtxt); var unload = tplCtxt.getCSSDependencies(); var tplClasspath = tplCtxt.tplClasspath; this.unloadClassPathDependencies(tplClasspath, unload); this.$raiseEvent({ name : "dependenciesUnloaded", templateClasspath : tplClasspath }); }
// Echo returns the same message
func Echo(ctx *cli.Context) command.Command { usage := "echo [text]" desc := "Returns the [text]" return command.NewCommand("echo", usage, desc, func(args ...string) ([]byte, error) { if len(args) < 2 { return []byte("echo what?"), nil } return []byte(strings.Join(args[1:], " ")), nil }) }
Function get source and destination alphabet and return convert function @param {string|Array} srcAlphabet @param {string|Array} dstAlphabet @returns {function(number|Array)}
function anyBase(srcAlphabet, dstAlphabet) { var converter = new Converter(srcAlphabet, dstAlphabet); /** * Convert function * * @param {string|Array} number * * @return {string|Array} number */ return function (number) { return converter.convert(number); } }
Return the number of cookies for the given domain.
def count_cookies(self, domain): '''''' cookies = self.cookie_jar._cookies if domain in cookies: return sum( [len(cookie) for cookie in cookies[domain].values()] ) else: return 0
// TagAttr returns the lower-cased key and unescaped value of the next unparsed // attribute for the current tag token and whether there are more attributes. // The contents of the returned slices may change on the next call to Next.
func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) { if z.nAttrReturned < len(z.attr) { switch z.tt { case StartTagToken, SelfClosingTagToken: x := z.attr[z.nAttrReturned] z.nAttrReturned++ key = z.buf[x[0].start:x[0].end] val = z.buf[x[1].start:x[1].end] return lower(key), unescape(convertNewlines(val), true), z.nAttrReturned < len(z.attr) } } return nil, nil, false }
Is a screenshot desired, based on the command and the test result.
public boolean requireScreenshot(final ExtendedSeleniumCommand command, boolean result) { return (!command.isAssertCommand() && !command.isVerifyCommand() && !command.isWaitForCommand() && screenshotPolicy == ScreenshotPolicy.STEP) || (!result && (screenshotPolicy == ScreenshotPolicy.FAILURE || (command.isAssertCommand() && screenshotPolicy == ScreenshotPolicy.ASSERTION))); }
Copy a directory from one location to another. @param string $directory @param string $destination @param int $options @return bool
public function copyDirectory( string $directory, string $destination, $options = null ): bool { if( !$this->isDirectory( $directory ) ) { return false; } $options = $options ?: FilesystemIterator::SKIP_DOTS; // If the destination directory does not actually exist, we will go ahead and // create it recursively, which just gets the destination prepared to copy // the files over. Once we make the directory we'll proceed the copying. if( !$this->isDirectory( $destination ) ) { $this->makeDirectory( $destination, 0777, true ); } $items = new FilesystemIterator( $directory, $options ); foreach( $items as $item ) { // As we spin through items, we will check to see if the current file is actually // a directory or a file. When it is actually a directory we will need to call // back into this function recursively to keep copying these nested folders. $target = $destination . '/' . $item->getBasename(); if( $item->isDir() ) { $path = $item->getPathname(); if( !$this->copyDirectory( $path, $target, $options ) ) { return false; } } // If the current items is just a regular file, we will just copy this to the new // location and keep looping. If for some reason the copy fails we'll bail out // and return false, so the developer is aware that the copy process failed. else { if( !$this->copy( $item->getPathname(), $target ) ) { return false; } } } return true; }
Get the format module to use for optimizing the image.
def _get_format_module(image_format): """""" format_module = None nag_about_gifs = False if detect_format.is_format_selected(image_format, Settings.to_png_formats, png.PROGRAMS): format_module = png elif detect_format.is_format_selected(image_format, jpeg.FORMATS, jpeg.PROGRAMS): format_module = jpeg elif detect_format.is_format_selected(image_format, gif.FORMATS, gif.PROGRAMS): # this captures still GIFs too if not caught above format_module = gif nag_about_gifs = True return format_module, nag_about_gifs
Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True
def _padleft(width, s, has_invisible=True): iwidth = width + len(s) - len(_strip_invisible(s)) if has_invisible else width fmt = "{0:>%ds}" % iwidth return fmt.format(s)
Authenticate with token bytes. @param tokenBytes @return The authenticated subject.
@Override public Subject authenticate(@Sensitive byte[] tokenBytes) throws AuthenticationException { AuthenticationData authenticationData = createAuthenticationData(tokenBytes); return authenticationService.authenticate(jaasEntryName, authenticationData, null); }
Displays a form to create a new Page entity. @Route("/new", name="manage_page_new") @Template()
public function newAction() { $entity = new Page(); $form = $this->createForm(new PageType(), $entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); }
// Input/output error
func isSysErrIO(err error) bool { if err == syscall.EIO { return true } pathErr, ok := err.(*os.PathError) return ok && pathErr.Err == syscall.EIO }
The perpendicular distance squared from a point to a line pt - point in question l0 - one point on the line l1 - another point on the line
def distance2_to_line(pt, l0, l1): ''' ''' pt = np.atleast_1d(pt) l0 = np.atleast_1d(l0) l1 = np.atleast_1d(l1) reshape = pt.ndim == 1 if reshape: pt.shape = l0.shape = l1.shape = (1, pt.shape[0]) result = (((l0[:,0] - l1[:,0]) * (l0[:,1] - pt[:,1]) - (l0[:,0] - pt[:,0]) * (l0[:,1] - l1[:,1]))**2 / np.sum((l1-l0)**2, 1)) if reshape: result = result[0] return result
all fields are required by default unless otherwise stated
def build_fields if @data.key?(:fields) @data[:fields].each do |k,v| v[:required] = true unless v.key?(:required) end else {city: {label:'City', required: true}, region: {label: 'Province', required: false}, postcode: {label: 'Post Code', required: false} } end end
Runs the callback for the given request @param DispatcherInterface|array $dispatcher @param null|string $path @param null|string $method @return mixed @throws \LogicException @throws \Throwable
public function dispatch($dispatcher = null, $path = null, $method = null) { if (!$dispatcher) { $dispatcher = new Dispatcher; } elseif (\is_array($dispatcher)) { $dispatcher = new Dispatcher($dispatcher); } if (!$dispatcher instanceof DispatcherInterface) { throw new \InvalidArgumentException( 'The first argument is must an array OR an object instanceof the DispatcherInterface' ); } if (!$dispatcher->hasRouter()) { $dispatcher->setRouter($this); } return $dispatcher->dispatchUri($path, $method); }
%prog freebayes prefix ref.fa *.bam Call SNPs using freebayes.
def freebayes(args): p = OptionParser(freebayes.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth [default: %default]") p.add_option("--minqual", default=20, type="int", help="Minimum quality [default: %default]") opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) prefix, ref = args[0:2] bams = args[2:] cmd = "bamaddrg -R {0}" cmd += " " + " ".join("-b {0}".format(x) for x in bams) fmd = "freebayes --stdin -C {0} -f {1}".format(opts.mindepth, ref) seqids = list(Fasta(ref).iterkeys_ordered()) for s in seqids: outfile = prefix + ".{0}.vcf".format(s) print(cmd.format(s), "|", fmd + " -r {0} -v {1}".format(s, outfile))
Check if the extension is valid for loading, i.e has a class and is withing version constraints. @param Composer $composer @param string|null $class @param string|null $constraint @return bool
private static function parseValid(Composer $composer, $class, $constraint) { if ($constraint === null) { return false; } $provides = $composer->getPackage()->getProvides(); $boltVersion = isset($provides['bolt/bolt']) ? $provides['bolt/bolt'] : new Link('__root__', 'bolt/bolt', new Constraint('=', '0.0.0')); return $class && Semver::satisfies($boltVersion->getPrettyConstraint(), $constraint); }
Resize and return the image passing the new height and width @param height @param width @return
public BufferedImage getBufferedImage(int width, int height) { // using the new approach of Java 2D API BufferedImage buf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D) buf.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(image, 0, 0, width, height, null); g2d.dispose(); return (buf); }
Take a node and return allowed attributes and check values
private function wash_attribs($node) { $result = ''; $washed = array(); foreach ($node->attributes as $name => $attr) { $key = strtolower($name); $value = $attr->nodeValue; if ($key == 'style' && ($style = $this->wash_style($value))) { // replace double quotes to prevent syntax error and XSS issues (#1490227) $result .= ' style="' . str_replace('"', '&quot;', $style) . '"'; } else if (isset($this->_html_attribs[$key])) { $value = trim($value); $out = null; // in SVG to/from attribs may contain anything, including URIs if ($key == 'to' || $key == 'from') { $key = strtolower($node->getAttribute('attributeName')); if ($key && !isset($this->_html_attribs[$key])) { $key = null; } } if ($this->is_image_attribute($node->nodeName, $key)) { $out = $this->wash_uri($value, true); } else if ($this->is_link_attribute($node->nodeName, $key)) { if (!preg_match('!^(javascript|vbscript|data:text)!i', $value) && preg_match('!^([a-z][a-z0-9.+-]+:|//|#).+!i', $value) ) { $out = $value; } } else if ($this->is_funciri_attribute($node->nodeName, $key)) { if (preg_match('/^[a-z:]*url\(/i', $val)) { if (preg_match('/^([a-z:]*url)\(\s*[\'"]?([^\'"\)]*)[\'"]?\s*\)/iu', $value, $match)) { if ($url = $this->wash_uri($match[2])) { $result .= ' ' . $attr->nodeName . '="' . $match[1] . '(' . htmlspecialchars($url, ENT_QUOTES) . ')' . substr($val, strlen($match[0])) . '"'; continue; } } else { $out = $value; } } else { $out = $value; } } else if ($key) { $out = $value; } if ($out !== null && $out !== '') { $result .= ' ' . $attr->nodeName . '="' . htmlspecialchars($out, ENT_QUOTES) . '"'; } else if ($value) { $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES); } } else { $washed[] = htmlspecialchars($attr->nodeName, ENT_QUOTES); } } if (!empty($washed) && $this->config['show_washed']) { $result .= ' x-washed="' . implode(' ', $washed) . '"'; } return $result; }
A helper method to allow the dynamic evaluation of groovy expressions using this scripts binding as the variable scope @param expression is the Groovy script expression to evaluate
public Object evaluate(String expression) throws CompilationFailedException { GroovyShell shell = new GroovyShell(getClass().getClassLoader(), binding); return shell.evaluate(expression); }
Use a VirtualConnection rather than a InboundVirtualConnection for discrimination
public int discriminate(VirtualConnection vc, Object discrimData, ConnectionLink prevChannelLink) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "discriminate: " + vc); } ConnectionLink nextChannelLink = nextChannel.getConnectionLink(vc); prevChannelLink.setApplicationCallback(nextChannelLink); nextChannelLink.setDeviceLink(prevChannelLink); return DiscriminationProcess.SUCCESS; }
Print a percent complete value. @param value Double instance @return percent complete value
public static final String printPercent(Double value) { return value == null ? null : Double.toString(value.doubleValue() / 100.0); }
Get the ActiveWindow name based on its class short name. @return string
public function getName() { if ($this->_name === null) { $this->_name = ((new \ReflectionClass($this))->getShortName()); } return $this->_name; }
A 2-by-2 matrix. Stored in column-major order.
function Mat22(a, b, c, d) { if (typeof a === 'object' && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === 'number') { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d) } else { this.ex = Vec2.zero(); this.ey = Vec2.zero() } }
// Skip skips a json object and positions to relatively the next json object
func (iter *Iterator) Skip() { c := iter.nextToken() switch c { case '"': iter.skipString() case 'n': iter.skipThreeBytes('u', 'l', 'l') // null case 't': iter.skipThreeBytes('r', 'u', 'e') // true case 'f': iter.skipFourBytes('a', 'l', 's', 'e') // false case '0': iter.unreadByte() iter.ReadFloat32() case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': iter.skipNumber() case '[': iter.skipArray() case '{': iter.skipObject() default: iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) return } }
// DescribeLiveStreamRecordIndexFile 查询单个录制索引文件 // // https://help.aliyun.com/document_detail/35237.html?spm=5176.doc35236.6.230.XnsJuD
func (l *Live) DescribeLiveStreamRecordIndexFile(streamName, recordID string, resp interface{}) (err error) { req := l.cloneRequest(DescribeLiveStreamRecordIndexFileAction) if global.EmptyString == req.AppName || global.EmptyString == streamName { return errors.New(" appName|streamName should not to be empty") } req.SetArgs("StreamName", streamName) if recordID != global.EmptyString { req.SetArgs("RecordId", recordID) } err = l.rpc.Query(req, resp) return }
/ Functions ------------------------------------------------------------------
function main(){ var argv = yargs .boolean( "a" ) .boolean( "r" ) .boolean( "s" ) .boolean( "c" ) .boolean( "h" ) .boolean( "v" ) .argv; var options = { all: argv.a || argv.all || false, recursive: argv.r || argv.recursive || false, sort: argv.s || argv.sort || false, }; if ( argv.v || argv.version ){ return printAndExitOk( getVersion() ); } if ( argv.h || argv.help ){ return printAndExitOk( getHelp() ); } if ( !argv._ || !argv._.length ){ return printAndExitError( getHelp() ); } if ( argv.p || argv.parts ){ options.parts = ( argv.p || argv.parts ).split( "," ); } if( argv.i || argv["include-path"] ){ options.includePath = ( argv.i || argv["include-path"] ).split( path.delimiter ); } var cat = argv.c || argv.cat; var fmt = argv.f || argv.format; if ( cat && !options.parts ){ return printAndExitError( "Please specify which parts should be concatenated with the -p option." ); } if ( cat && fmt ){ return printAndExitError( "Please choose either concatenating parts (-c) or outputing components (-f)." ); } var components = mpc.apply( this, [ options ].concat( argv._ )); if ( cat ){ return catParts( components, options.parts ); } switch( fmt ){ case "json": console.log( JSON.stringify( components )); break; case "csv": default: return printCsv( components ); } }
Applies sorting on Iterator. @param array $fields @return $this
public function order($fields) { $data = $this->get(); // prepare arguments for array_multisort() $args = []; foreach ($fields as list($field, $desc)) { $args[] = array_column($data, $field); $args[] = $desc ? SORT_DESC : SORT_ASC; //$args[] = SORT_STRING; // SORT_STRING | SORT_NUMERIC | SORT_REGULAR } $args[] = &$data; // call sorting call_user_func_array('array_multisort', $args); // put data back in generator $this->generator = new \ArrayIterator(array_pop($args)); return $this; }
Wraps around module loading for unexpected additions
def detect_additions(options={}, &block) Util.detect(options, &block).tap do |detected| @commands.concat detected[:methods].map(&:to_s) end end
https://tools.ietf.org/html/rfc7946#section-3.1.5
function MultiLineString(multiLineString) { crs(multiLineString); bbox(multiLineString); if (!requiredProperty(multiLineString, 'coordinates', 'array')) { positionArray(multiLineString.coordinates, 'Line', 2); } }
// SetDescription sets the clients description.
func (c *Client) SetDescription(description string) error { return c.ClientUpdate(NewArg(ClientDescription, description)) }
get time from mavlink ATTITUDE
def mavlink_packet(self, m): '''''' if m.get_type() == 'GLOBAL_POSITION_INT': if abs(m.lat) < 1000 and abs(m.lon) < 1000: return self.vehicle_pos = VehiclePos(m)
calculate total size (include witness data.)
def size 80 + Bitcoin.pack_var_int(transactions.size).bytesize + transactions.inject(0){|sum, tx| sum + (tx.witness? ? tx.serialize_witness_format.bytesize : tx.serialize_old_format.bytesize)} end
Launches a automated backup routine for the given course @param stdClass $course @param int $starttime @param int $userid @return bool
public static function launch_automated_backup($course, $starttime, $userid) { $outcome = self::BACKUP_STATUS_OK; $config = get_config('backup'); $dir = $config->backup_auto_destination; $storage = (int)$config->backup_auto_storage; $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid); try { // Set the default filename. $format = $bc->get_format(); $type = $bc->get_type(); $id = $bc->get_id(); $users = $bc->get_plan()->get_setting('users')->get_value(); $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value(); $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised)); $bc->set_status(backup::STATUS_AWAITING); $bc->execute_plan(); $results = $bc->get_results(); $outcome = self::outcome_from_results($results); $file = $results['backup_destination']; // May be empty if file already moved to target location. // If we need to copy the backup file to an external dir and it is not writable, change status to error. // This is a feature to prevent moodledata to be filled up and break a site when the admin misconfigured // the automated backups storage type and destination directory. if ($storage !== 0 && (empty($dir) || !file_exists($dir) || !is_dir($dir) || !is_writable($dir))) { $bc->log('Specified backup directory is not writable - ', backup::LOG_ERROR, $dir); $dir = null; $outcome = self::BACKUP_STATUS_ERROR; } // Copy file only if there was no error. if ($file && !empty($dir) && $storage !== 0 && $outcome != self::BACKUP_STATUS_ERROR) { $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname); if (!$file->copy_content_to($dir.'/'.$filename)) { $bc->log('Attempt to copy backup file to the specified directory failed - ', backup::LOG_ERROR, $dir); $outcome = self::BACKUP_STATUS_ERROR; } if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) { if (!$file->delete()) { $outcome = self::BACKUP_STATUS_WARNING; $bc->log('Attempt to delete the backup file from course automated backup area failed - ', backup::LOG_WARNING, $file->get_filename()); } } } } catch (moodle_exception $e) { $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header. $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem. $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information. $outcome = self::BACKUP_STATUS_ERROR; } // Delete the backup file immediately if something went wrong. if ($outcome === self::BACKUP_STATUS_ERROR) { // Delete the file from file area if exists. if (!empty($file)) { $file->delete(); } // Delete file from external storage if exists. if ($storage !== 0 && !empty($filename) && file_exists($dir.'/'.$filename)) { @unlink($dir.'/'.$filename); } } $bc->destroy(); unset($bc); return $outcome; }
A Helper to materialize primitive data types
public void materializeHelper(Materializer maker) throws IOException { if (!materialized) { ReaderWriterProfiler.start(ReaderWriterProfiler.Counter.DECODING_TIME); try { maker.materialize(treeReader, currentRow); materialized = true; writableCreated = false; nextIsNull = false; nextIsNullSet = true; } catch (ValueNotPresentException e) { // Is the value null? // materialized = true; writableCreated = true; // We have effectively created a writable nextIsNull = true; nextIsNullSet = true; throw new IOException("Cannot materialize primitive: value not present"); } ReaderWriterProfiler.end(ReaderWriterProfiler.Counter.DECODING_TIME); } else if (nextIsNull) { throw new IOException("Cannot materialize primitive: value not present."); } }
Connects this object to the specified source project.
def load(self, project: typing.Union[projects.Project, None]): """""" self._project = project
Rewrite the error dictionary, so that its keys correspond to the model fields.
def _post_clean(self): super(NgModelFormMixin, self)._post_clean() if self._errors and self.prefix: self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
// To adds a route to the router with the given HTTP methods, route path, and handlers. // Multiple HTTP methods should be separated by commas (without any surrounding spaces).
func (rg *RouteGroup) To(methods, path string, handlers ...Handler) *Route { mm := strings.Split(methods, ",") if len(mm) == 1 { return rg.add(methods, path, handlers) } r := rg.newRoute(methods, path) for _, method := range mm { r.routes = append(r.routes, rg.add(method, path, handlers)) } return r }
Gets the command line interface text of the class. @param aClass the class @param requiredType the class type @return the command line interface text of the class
public static String classToCLIString(Class<?> aClass, Class<?> requiredType) { String className = aClass.getName(); String packageName = requiredType.getPackage().getName(); if (className.startsWith(packageName)) { // cut off package name className = className.substring(packageName.length() + 1, className.length()); } /*else if (Task.class.isAssignableFrom(aClass)) { packageName = Task.class.getPackage().getName(); if (className.startsWith(packageName)) { // cut off task package name className = className.substring(packageName.length() + 1, className.length()); } }*/ return className; }
NOTE: uncertain future
long[] toLongArray() { // create array through an aligned copy BitVector copy = alignedCopy(); long[] longs = copy.bits; int length = longs.length; if (length == 0) return longs; // reverse the array for (int i = 0, mid = length >> 1, j = length - 1; i < mid; i++, j--) { long t = longs[i]; longs[i] = longs[j]; longs[j] = t; } // mask off top bits in case copy was produced via clone final long mask = -1L >>> (ADDRESS_SIZE - copy.finish & ADDRESS_MASK); longs[0] &= mask; // return the result return longs; }
Updates a job trigger. See https://cloud.google.com/dlp/docs/creating-job-triggers to learn more. @param \Google\Cloud\Dlp\V2\UpdateJobTriggerRequest $argument input argument @param array $metadata metadata @param array $options call options
public function UpdateJobTrigger(\Google\Cloud\Dlp\V2\UpdateJobTriggerRequest $argument, $metadata = [], $options = []) { return $this->_simpleRequest('/google.privacy.dlp.v2.DlpService/UpdateJobTrigger', $argument, ['\Google\Cloud\Dlp\V2\JobTrigger', 'decode'], $metadata, $options); }
Go through a Contribution and validate each table
def validate_contribution(the_con): passing = True for dtype in list(the_con.tables.keys()): print("validating {}".format(dtype)) fail = validate_table(the_con, dtype) if fail: passing = False print('--')
// CloseStream closes the associated stream
func (c *Call) CloseStream() error { if !c.Stream { return errors.New("rpc: cannot close non-stream request") } <-c.sent c.client.sending.Lock() defer c.client.sending.Unlock() c.client.mutex.Lock() if c.client.shutdown { c.client.mutex.Unlock() return ErrShutdown } c.client.mutex.Unlock() c.client.request.ServiceMethod = "CloseStream" c.client.request.Seq = c.seq return c.client.codec.WriteRequest(&c.client.request, struct{}{}) }
Get the list of movies on an accounts watchlist. @param sessionId sessionId @param accountId accountId @param page page @param sortBy sortBy @param language language @return The watchlist of the user @throws MovieDbException exception
public ResultList<TVBasic> getWatchListTV(String sessionId, int accountId, Integer page, String sortBy, String language) throws MovieDbException { return tmdbAccount.getWatchListTV(sessionId, accountId, page, sortBy, language); }
Retrieves divident history
def get_dividendhistory(self, symbol, startDate, endDate, items=None): startDate, endDate = self.__get_time_range(startDate, endDate) response = self.select('yahoo.finance.dividendhistory', items).where(['symbol', '=', symbol], ['startDate', '=', startDate], ['endDate', '=', endDate]) return response
Initializes a CMS context for the authentication data contained in a call context.<p> @param context the call context @return the initialized CMS context
protected CmsObject getCmsObject(CmsCmisCallContext context) { try { if (context.getUsername() == null) { // user name can be null CmsObject cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest()); cms.getRequestContext().setCurrentProject(m_adminCms.getRequestContext().getCurrentProject()); return cms; } else { CmsObject cms = OpenCms.initCmsObject(m_adminCms); CmsProject projectBeforeLogin = cms.getRequestContext().getCurrentProject(); cms.loginUser(context.getUsername(), context.getPassword()); cms.getRequestContext().setCurrentProject(projectBeforeLogin); return cms; } } catch (CmsException e) { throw new CmisPermissionDeniedException(e.getLocalizedMessage(), e); } }
Convert an enumeration to a Set. @param self an enumeration @return a Set @since 1.8.0
public static <T> Set<T> toSet(Enumeration<T> self) { Set<T> answer = new HashSet<T>(); while (self.hasMoreElements()) { answer.add(self.nextElement()); } return answer; }
(For testing) Insert images to the ViSearch App with custom parameters. @param imageList the list of Images to insert. @param customParams custom parameters @return an insert transaction
@Override public InsertTrans insert(List<Image> imageList, Map<String, String> customParams) { return dataOperations.insert(imageList, customParams); }
helper function to bump a statistic
def _increment(self, what, host): ''' ''' self.processed[host] = 1 prev = (getattr(self, what)).get(host, 0) getattr(self, what)[host] = prev+1
Fetch the next row of a query result set, returning a single sequence, or ``None`` when no more data is available.
def fetchone(self): if self._state == self._STATE_NONE: raise Exception("No query yet") if not self._data: return None else: self._rownumber += 1 return self._data.pop(0)
// GetConnection returns single connection
func (s *Server) GetConnection(connID string) Connection { conn, ok := s.getConnection(connID) if !ok { return nil } return conn }
Gets the Certificate RabbitMQ API client. Returns: CertificateRabbitMQ:
def certificate_rabbitmq(self): if not self.__certificate_rabbitmq: self.__certificate_rabbitmq = CertificateRabbitMQ(self.__connection) return self.__certificate_rabbitmq
Returns the data associated to the given object. If the given object is not in the storage, or has no associated data, NULL is returned. @param object $object The object. @return mixed The stored data.
public function get($object) { $hash = spl_object_hash($object); if (isset($this->data[$hash])) { return $this->data[$hash]; } return null; }
Short description of method validate @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string schema @return boolean
public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $content = $this->getContent(); if (!empty($content)) { try { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $this->valid = $dom->loadXML($content); if ($this->valid && !empty($schema)) { $this->valid = $dom->schemaValidate($schema); } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch(DOMException $de) { $this->addError($de); } } helpers_TimeOutHelper::reset(); return (bool) $this->valid; }
// Unmarshal accepts a byte slice as input and writes the // data to the value pointed to by v.
func Unmarshal(bs []byte, v interface{}) error { root, err := parse(bs) if err != nil { return err } return DecodeObject(v, root) }
// LBInterfaceInit initialises the load balancing interface for a Seesaw Node.
func (ncc *SeesawNCC) LBInterfaceInit(iface *ncctypes.LBInterface, out *int) error { netIface, err := iface.Interface() if err != nil { return fmt.Errorf("Failed to get network interface: %v", err) } nodeIface, err := net.InterfaceByName(iface.NodeInterface) if err != nil { return fmt.Errorf("Failed to get node interface: %v", err) } if iface.RoutingTableID < 1 || iface.RoutingTableID > 250 { return fmt.Errorf("Invalid routing table ID: %d", iface.RoutingTableID) } vmac, err := net.ParseMAC(vrrpMAC) if err != nil { return fmt.Errorf("Failed to parse VRRP MAC %q: %v", vrrpMAC, err) } // The last byte of the VRRP MAC is determined by the VRID. vmac[len(vmac)-1] = iface.VRID netIface.HardwareAddr = vmac log.Infof("Initialising load balancing interface %s - VRID %d (VMAC %s)", iface.Name, iface.VRID, vmac) // Ensure interface is down and set VMAC address. if err := ifaceFastDown(netIface); err != nil { return fmt.Errorf("Failed to down interface: %v", err) } if err := ifaceSetMAC(netIface); err != nil { return fmt.Errorf("Failed to set MAC: %v", err) } // Remove VLAN interfaces associated with the load balancing interface. if err := ifaceFlushVLANs(netIface); err != nil { return fmt.Errorf("Failed to flush VLAN interfaces: %v", err) } // Configure sysctls for load balancing. if err := sysctlInitLB(nodeIface, netIface); err != nil { return fmt.Errorf("Failed to initialise sysctls: %v", err) } // Flush existing IP addresses and add cluster VIPs. if err := ifaceFlushIPAddr(netIface); err != nil { return fmt.Errorf("Failed to flush IP addresses: %v", err) } if iface.ClusterVIP.IPv4Addr != nil { if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv4Addr); err != nil { return fmt.Errorf("Failed to add IPv4 cluster VIP: %v", err) } } if iface.ClusterVIP.IPv6Addr != nil { if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv6Addr); err != nil { return fmt.Errorf("Failed to add IPv6 cluster VIP: %v", err) } } // Initialise iptables rules. if err := iptablesInit(iface.ClusterVIP); err != nil { return err } // Setup dummy interface. dummyIface, err := net.InterfaceByName(iface.DummyInterface) if err != nil { return fmt.Errorf("Failed to get dummy interface: %v", err) } if err := ifaceFastDown(dummyIface); err != nil { return fmt.Errorf("Failed to down dummy interface: %v", err) } if err := ifaceFlushIPAddr(dummyIface); err != nil { return fmt.Errorf("Failed to flush dummy interface: %v", err) } if err := ifaceUp(dummyIface); err != nil { return fmt.Errorf("Failed to up dummy interface: %v", err) } return nil }
Добавить Миграцию в базу @param Migration $migration
public function insert(Migration $migration) { $sql = sprintf("INSERT INTO {$this->tableName} (name, data) VALUES ('%s', '%s')", $this->adapter->escape($migration->getName()), $this->adapter->escape($migration->getSql()) ); $this->getAdapter()->execute($sql); }
// Parse parses the given string into the correct sentence type.
func Parse(raw string) (Sentence, error) { s, err := parseSentence(raw) if err != nil { return nil, err } if strings.HasPrefix(s.Raw, SentenceStart) { switch s.Type { case TypeRMC: return newRMC(s) case TypeGGA: return newGGA(s) case TypeGSA: return newGSA(s) case TypeGLL: return newGLL(s) case TypeVTG: return newVTG(s) case TypeZDA: return newZDA(s) case TypePGRME: return newPGRME(s) case TypeGSV: return newGSV(s) case TypeHDT: return newHDT(s) case TypeGNS: return newGNS(s) case TypeTHS: return newTHS(s) } } if strings.HasPrefix(s.Raw, SentenceStartEncapsulated) { switch s.Type { case TypeVDM, TypeVDO: return newVDMVDO(s) } } return nil, fmt.Errorf("nmea: sentence prefix '%s' not supported", s.Prefix()) }
Retrieve a collection of File objects representing the files stored inside a bucket. @param array $options @throws \Exception @throws GuzzleException @return array
public function listFiles(array $options) { // if FileName is set, we only attempt to retrieve information about that single file. $fileName = !empty($options['FileName']) ? $options['FileName'] : null; $nextFileName = null; $maxFileCount = 1000; $prefix = isset($options['Prefix']) ? $options['Prefix'] : ''; $delimiter = isset($options['Delimiter']) ? $options['Delimiter'] : null; $files = []; if (!isset($options['BucketId']) && isset($options['BucketName'])) { $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']); } if ($fileName) { $nextFileName = $fileName; $maxFileCount = 1; } $this->authorizeAccount(); // B2 returns, at most, 1000 files per "page". Loop through the pages and compile an array of File objects. while (true) { $response = $this->generateAuthenticatedClient([ 'bucketId' => $options['BucketId'], 'startFileName' => $nextFileName, 'maxFileCount' => $maxFileCount, 'prefix' => $prefix, 'delimiter' => $delimiter, ])->request('POST', '/b2_list_file_names'); foreach ($response['files'] as $file) { // if we have a file name set, only retrieve information if the file name matches if (!$fileName || ($fileName === $file['fileName'])) { $files[] = new File($file['fileId'], $file['fileName'], null, $file['size']); } } if ($fileName || $response['nextFileName'] === null) { // We've got all the files - break out of loop. break; } $nextFileName = $response['nextFileName']; } return $files; }
Configures the #CDATA of an element. @param Project $project the project this element belongs to @param object the element to configure @param string $text the element's #CDATA
public static function addText($project, $target, $text = null) { if ($text === null || strlen(trim($text)) === 0) { return; } $ih = IntrospectionHelper::getHelper(get_class($target)); $text = $project->replaceProperties($text); $ih->addText($project, $target, $text); }
read_full reads exactly `size` bytes from reader. returns `size` bytes. :param data: Input stream to read from. :param size: Number of bytes to read from `data`. :return: Returns :bytes:`part_data`
def read_full(data, size): default_read_size = 32768 # 32KiB per read operation. chunk = io.BytesIO() chunk_size = 0 while chunk_size < size: read_size = default_read_size if (size - chunk_size) < default_read_size: read_size = size - chunk_size current_data = data.read(read_size) if not current_data or len(current_data) == 0: break chunk.write(current_data) chunk_size+= len(current_data) return chunk.getvalue()
Make sure a clause is valid and does not contain SQL injection attempts. @param string $clause The string clause to validate. @return bool True if the clause is valid.
public static function isValidClause($clause) { $output = rtrim($clause, ' ;'); $output = preg_replace("/\\\\'.*?\\\\'/", '{mask}', $output); $output = preg_replace('/\\".*?\\"/', '{mask}', $output); $output = preg_replace("/'.*?'/", '{mask}', $output); $output = preg_replace('/".*?"/', '{mask}', $output); return strpos($output, ';') === false && strpos(strtolower($output), 'union') === false; }
Returns the float value for the specified name. If the name does not exist or the value for the name can not be interpreted as a float, the defaultValue is returned. @param name @param defaultValue @return name value or defaultValue
public float getFloat(String name, float defaultValue) { try { String value = getString(name, null); if (!StringUtils.isNullOrEmpty(value)) { return Float.parseFloat(value.trim()); } } catch (NumberFormatException e) { log.warn("Failed to parse float for " + name + USING_DEFAULT_OF + defaultValue); } return defaultValue; }
Get the panel group starting element. @return ContentModel|null
protected function getPanelGroup(): ?ContentModel { $group = ContentModel::findOneBy( [ 'tl_content.ptable=?', 'tl_content.pid=?', '(tl_content.type = ? OR tl_content.type = ?)', 'tl_content.sorting < ?', ], [ $this->get('ptable'), $this->get('pid'), 'bs_panel_group_start', 'bs_panel_group_end', $this->get('sorting'), ], [ 'order' => 'tl_content.sorting DESC', ] ); if ($group && $group->type === 'bs_panel_group_start') { return $group; } return null; }
Run a command [cmd, arg1, arg2, ...]. Returns the output (stdout + stderr). Raises CommandFailed in cases of error.
def run(command, encoding=None, decode=True, cwd=None): if not encoding: encoding = locale.getpreferredencoding() try: with open(os.devnull, 'rb') as devnull: pipe = subprocess.Popen(command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) except OSError as e: raise Failure("could not run %s: %s" % (command, e)) output = pipe.communicate()[0] if decode: output = output.decode(encoding) status = pipe.wait() if status != 0: raise CommandFailed(command, status, output) return output
Handles received version data. :param data: Version string to parse :type data: string
def _handle_version(self, data): _, version_string = data.split(':') version_parts = version_string.split(',') self.serial_number = version_parts[0] self.version_number = version_parts[1] self.version_flags = version_parts[2]
/* Render pagination buttons @param $items @param int $page @param int $perPage @param $path @param array $componentOptions
public function pagination($items, $page = 1, $perPage = 25, $path = '', array $componentOptions = []) { $items = $items instanceof Collection ? $items : Collection::make($items); $paginator = (new LengthAwarePaginator($items, $items->count(), (int) $perPage, (int) $page)) ->withPath($path); return $paginator->render('bootstrap::render.pagination', $componentOptions); }
Returns the canonical instance of the {@link WorkQueue} to be used in running concurrent tasks, ensuring the <i>at least</i> the specified number of threads are available.
public static WorkQueue getWorkQueue(int numThreads) { if (singleton == null) { synchronized (WorkQueue.class) { if (singleton == null) singleton = new WorkQueue(numThreads); } } while (singleton.availableThreads() < numThreads) { singleton.addThread(); } return singleton; }
find a ModuleItem
public static ModuleItem findModuleItem(String[] path) { if (disabled) return null; if (path == null || path[0].equals(APPSERVER_MODULE)) { return moduleRoot; } return moduleRoot.find(path, 0); }
Initialize library, must be called once before other functions are called.
def begin(self): resp = ws.ws2811_init(self._leds) if resp != 0: str_resp = ws.ws2811_get_return_t_str(resp) raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, str_resp))
Returns the info for a Template
def get_template_info(self, obj): client = self.get_client() client_uid = api.get_uid(client) if client else "" profile = obj.getAnalysisProfile() profile_uid = api.get_uid(profile) if profile else "" profile_title = profile.Title() if profile else "" sample_type = obj.getSampleType() sample_type_uid = api.get_uid(sample_type) if sample_type else "" sample_type_title = sample_type.Title() if sample_type else "" sample_point = obj.getSamplePoint() sample_point_uid = api.get_uid(sample_point) if sample_point else "" sample_point_title = sample_point.Title() if sample_point else "" service_uids = [] analyses_partitions = {} analyses = obj.getAnalyses() for record in analyses: service_uid = record.get("service_uid") service_uids.append(service_uid) analyses_partitions[service_uid] = record.get("partition") info = self.get_base_info(obj) info.update({ "analyses_partitions": analyses_partitions, "analysis_profile_title": profile_title, "analysis_profile_uid": profile_uid, "client_uid": client_uid, "composite": obj.getComposite(), "partitions": obj.getPartitions(), "remarks": obj.getRemarks(), "sample_point_title": sample_point_title, "sample_point_uid": sample_point_uid, "sample_type_title": sample_type_title, "sample_type_uid": sample_type_uid, "service_uids": service_uids, }) return info
Retrieve the given property, if it does indeed exist
public function getProperty(PHPStanClassReflection $reflection, string $property) : PHPStanPropertyReflection { $native = $reflection->getNativeReflection(); if($native->hasMethod("getter_".$property)) return $this->getUnderscoreGetter($reflection, $property); return null; }
Convert a generator into a function that prints all yielded elements >>> @print_yielded ... def x(): ... yield 3; yield None >>> x() 3 None
def print_yielded(func): print_all = functools.partial(map, print) print_results = compose(more_itertools.recipes.consume, print_all, func) return functools.wraps(func)(print_results)
Set yaxis limits Parameters ---------- low : number high : number index : int, optional Returns ------- Chart
def ylim(self, low, high): self.chart['yAxis'][0]['min'] = low self.chart['yAxis'][0]['max'] = high return self
// SetOutputs sets the Outputs field's value.
func (s *AutomationExecution) SetOutputs(v map[string][]*string) *AutomationExecution { s.Outputs = v return s }
Remove read file descriptor from the event loop.
def remove_reader(self, fd): " " fd = fd_to_int(fd) if fd in self._read_fds: del self._read_fds[fd] self.selector.unregister(fd)
Lazy-load the primary keys.
def pks(self): """""" if self._primary_keys is None: self._primary_keys = list( self.queryset.values_list('pk', flat=True)) return self._primary_keys
Implements a deep neural network for classification. params is a list of (weights, bias) tuples. inputs is an (N x D) matrix. returns normalized class log-probabilities.
def neural_net_predict(params, inputs): """""" for W, b in params: outputs = np.dot(inputs, W) + b inputs = np.tanh(outputs) return outputs - logsumexp(outputs, axis=1, keepdims=True)
// GetKey returns key in section by given name.
func (s *Section) GetKey(name string) (*Key, error) { if s.f.BlockMode { s.f.lock.RLock() } if s.f.options.Insensitive { name = strings.ToLower(name) } key := s.keys[name] if s.f.BlockMode { s.f.lock.RUnlock() } if key == nil { // Check if it is a child-section. sname := s.name for { if i := strings.LastIndex(sname, "."); i > -1 { sname = sname[:i] sec, err := s.f.GetSection(sname) if err != nil { continue } return sec.GetKey(name) } break } return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) } return key, nil }
X.509 certificate signing helper function. @param object $key @param \phpseclib\File\X509 $subject @param string $signatureAlgorithm @access public @return mixed
function _sign($key, $signatureAlgorithm) { if ($key instanceof RSA) { switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $key->setSignatureMode(RSA::SIGNATURE_PKCS1); $this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject)); return $this->currentCert; } } return false; }