comment
stringlengths
16
255
code
stringlengths
52
3.87M
Gets/sets the schema instance. @param object $schema The schema instance to set or none to get it. @return mixed The schema instance on get.
public static function definition($schema = null) { if (func_num_args()) { if (is_string($schema)) { static::$_definition = $schema; } elseif($schema) { static::$_definitions[static::class] = $schema; } else { unset(static::$_definitions[static::class]); } return; } $self = static::class; if (isset(static::$_definitions[$self])) { return static::$_definitions[$self]; } $conventions = static::conventions(); $config = [ 'connection' => static::$_connection, 'conventions' => $conventions, 'class' => $self, 'locked' => Document::class !== $self ]; $config += ['source' => $conventions->apply('source', $self)]; $class = static::$_definition; $schema = static::$_definitions[$self] = new $class($config); static::_define($schema); return $schema; }
Read messages from a file-like object until stream is exhausted.
def read_messages(fobj, magic_table): """""" messages = [] while True: magic = read_magic(fobj) if not magic: break func = magic_table.get(magic) if func is not None: messages.append(func(fobj)) else: log.error('Unknown magic: ' + str(' '.join('{0:02x}'.format(b) for b in bytearray(magic)))) return messages
// Log formats using the default formats for its operands and logs the resulting // string. // Spaces are always added between operands and a newline is appended.
func Log(a ...interface{}) { format := "" for range a { format += "%v " } format = format[:len(format)-1] Logger(format, a...) }
// Next returns the current token and advances cursor to next one
func (m *LexTokenPager) Next() lex.Token { m.lexNext() m.cursor++ if m.cursor+1 > len(m.tokens) { //u.Warnf("Next() CRAP? increment cursor: %v of %v %v", m.cursor, len(m.tokens)) return eoft } return m.tokens[m.cursor-1] }
Return <dimension> xml string. @return string
public function getDimensionXml() { return sprintf(SheetXml::DIMENSION_XML, $this->cellBuilder->getCellId($this->maxColumnCount - 1, $this->rowIndex - 1) ); }
/* ========================================================================== Initialize the "longest match" routines for a new file
function lm_init() { var j; // Initialize the hash table. */ for (j = 0; j < HASH_SIZE; j++) { // head2(j, NIL); prev[WSIZE + j] = 0; } // prev will be initialized on the fly */ // Set the default configuration parameters: max_lazy_match = configuration_table[compr_level].max_lazy; good_match = configuration_table[compr_level].good_length; if (!FULL_SEARCH) { nice_match = configuration_table[compr_level].nice_length; } max_chain_length = configuration_table[compr_level].max_chain; strstart = 0; block_start = 0; lookahead = read_buff(window, 0, 2 * WSIZE); if (lookahead <= 0) { eofile = true; lookahead = 0; return; } eofile = false; // Make sure that we always have enough lookahead. This is important // if input comes from a device such as a tty. while (lookahead < MIN_LOOKAHEAD && !eofile) { fill_window(); } // If lookahead < MIN_MATCH, ins_h is garbage, but this is // not important since only literal bytes will be emitted. ins_h = 0; for (j = 0; j < MIN_MATCH - 1; j++) { // UPDATE_HASH(ins_h, window[j]); ins_h = ((ins_h << H_SHIFT) ^ (window[j] & 0xff)) & HASH_MASK; } }
rel determines the relationship to another IPv6Net. Returns: * 1 if this IPv6Net is the supernet of other * 0 if the two are equal * -1 if this IPv6Net is a subnet of other * nil if the networks are unrelated
def rel(other) if (!other.kind_of?(IPv6Net)) raise ArgumentError, "Expected an IPv6Net object for 'other' but got a #{other.class}." end # when networks are equal then we can look exlusively at the netmask if (self.network.addr == other.network.addr) return self.netmask.cmp(other.netmask) end # when networks are not equal we can use hostmask to test if they are # related and which is the supernet vs the subnet hostmask = self.netmask.mask ^ NetAddr::F128 otherHostmask = other.netmask.mask ^ NetAddr::F128 if (self.network.addr|hostmask == other.network.addr|hostmask) return 1 elsif (self.network.addr|otherHostmask == other.network.addr|otherHostmask) return -1 end return nil end
Add options for command line and config file.
def add_options(cls, parser): """""" parser.add_option( '--putty-select', metavar='errors', default='', help='putty select list', ) parser.add_option( '--putty-ignore', metavar='errors', default='', help='putty ignore list', ) parser.add_option( '--putty-no-auto-ignore', action='store_false', dest='putty_auto_ignore', default=False, help=(' (default) do not auto ignore lines matching ' '# flake8: disable=<code>,<code>'), ) parser.add_option( '--putty-auto-ignore', action='store_true', dest='putty_auto_ignore', default=False, help=('auto ignore lines matching ' '# flake8: disable=<code>,<code>'), ) parser.config_options.append('putty-select') parser.config_options.append('putty-ignore') parser.config_options.append('putty-auto-ignore')
// GetDriver returns a logging driver by its name. // If the driver is empty, it looks for the local driver.
func getPlugin(name string, mode int) (Creator, error) { p, err := pluginGetter.Get(name, extName, mode) if err != nil { return nil, fmt.Errorf("error looking up logging plugin %s: %v", name, err) } client, err := makePluginClient(p) if err != nil { return nil, err } return makePluginCreator(name, client, p.ScopedPath), nil }
autogrow when entering logic
function () { var t = this; t.$ed.removeClass('autogrow-on-enter'); var oldHeight = t.$ed[0].clientHeight; t.$ed.height('auto'); var totalHeight = t.$ed[0].scrollHeight; t.$ed.addClass('autogrow-on-enter'); if (oldHeight !== totalHeight) { t.$ed.height(oldHeight); setTimeout(function () { t.$ed.css({height: totalHeight}); t.$c.trigger('tbwresize'); }, 0); } }
Adds the given group if this constraint is in the Default group. @param string $group
public function addImplicitGroupName($group) { if (\in_array(self::DEFAULT_GROUP, $this->groups) && !\in_array($group, $this->groups)) { $this->groups[] = $group; } }
Parse an OAuth authorization header into a list of 2-tuples
def parse_authorization_header(authorization_header): """""" auth_scheme = 'OAuth '.lower() if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): items = parse_http_list(authorization_header[len(auth_scheme):]) try: return list(parse_keqv_list(items).items()) except (IndexError, ValueError): pass raise ValueError('Malformed authorization header')
Returns true of self and other are approximately equal.
def Equals(self, other): return (self._approxEq(self.x, other.x) and self._approxEq(self.y, other.y) and self._approxEq(self.z, other.z))
addPsr4 @param string|array $class @param string $path @return $this
public function addPsr4($class, $path = null) { if (is_array($class)) { foreach ($class as $ns => $path) { $this->psr4->addNamespace($ns, $path); } } else { $this->psr4->addNamespace($class, $path); } return $this; }
Given output of dmsetup ls this will return themajor:minor (block name) of the device deviceName
def getMajorMinor(deviceName, dmsetupLs): startingIndex = string.rindex(dmsetupLs, deviceName) + len(deviceName) endingIndex = string.index(dmsetupLs[startingIndex:], "\n") + startingIndex # trim the preceding tab and ()'s newStr = dmsetupLs[startingIndex + 2: endingIndex - 1] return newStr
create a new Identifiers for a new Node, with this Identifiers as the parent.
def branch(self, node, **kwargs): """""" return _Identifiers(self.compiler, node, self, **kwargs)
Set the {@link CompressionCodec} to be used to compress job outputs. @param conf the {@link JobConf} to modify @param codecClass the {@link CompressionCodec} to be used to compress the job outputs
public static void setOutputCompressorClass(JobConf conf, Class<? extends CompressionCodec> codecClass) { setCompressOutput(conf, true); conf.setClass("mapred.output.compression.codec", codecClass, CompressionCodec.class); }
Factory to create new KeenIOClient instance. @param array $config @returns \KeenIO\Client\KeenIOClient
public static function factory($config = array()) { $default = array( 'masterKey' => null, 'writeKey' => null, 'readKey' => null, 'projectId' => null, 'organizationKey' => null, 'organizationId' => null, 'version' => '3.0', 'headers' => array( 'Keen-Sdk' => 'php-' . self::VERSION ) ); // Create client configuration $config = self::parseConfig($config, $default); $file = 'keen-io-' . str_replace('.', '_', $config['version']) . '.php'; // Create the new Keen IO Client with our Configuration return new self( new Client($config), new Description(include __DIR__ . "/Resources/{$file}"), null, function ($arg) { return json_decode($arg->getBody(), true); }, null, $config ); }
Get the locator @return Locator @throws Exception\DomainException if unable to find locator
protected function getLocator() { if ($this->locator) { return $this->locator; } $controller = $this->getController(); if (!$controller instanceof ServiceLocatorAwareInterface) { throw new \Exception('ServiceBroker plugin requires controller implements ServiceLocatorAwareInterface'); } $locator = $controller->getServiceLocator(); if (!$locator instanceof ServiceLocatorInterface) { throw new \Exception('ServiceBroker plugin requires controller implements ServiceLocatorInterface'); } $this->locator = $locator; return $this->locator; }
// SetStreams sets the Streams field's value.
func (s *ListStreamsOutput) SetStreams(v []*StreamSummary) *ListStreamsOutput { s.Streams = v return s }
Search by users or channels on all server.
def directory(self, query, **kwargs): """""" if isinstance(query, dict): query = str(query).replace("'", '"') return self.__call_api_get('directory', query=query, kwargs=kwargs)
If the article has meta language set in the source, use that @return string
private function getMetaLanguage(): string { $lang = ''; $el = $this->article()->getDoc()->find('html[lang]'); if ($el->count()) { $lang = $el->first()->attr('lang'); } if (empty($lang)) { $selectors = [ 'html > head > meta[http-equiv=content-language]', 'html > head > meta[name=lang]', ]; foreach ($selectors as $selector) { $el = $this->article()->getDoc()->find($selector); if ($el->count()) { $lang = $el->first()->attr('content'); break; } } } if (preg_match('@^[A-Za-z]{2}$@', $lang)) { return strtolower($lang); } return ''; }
determines if the region specified by `box` is clear of all other `boxes`
function validate(boxes, box) { var a = box for (var i = 0; i < boxes.length; i++) { var b = boxes[i] if (intersects(a, b)) { return false } } return true }
sendExecuteQuery Execute a prepared statement. The optional SQL parameter is for debugging purposes only. @param string $identifier @param array $parameters @param string $sql @return ResultHandler|array
public function sendExecuteQuery($identifier, array $parameters = [], $sql = '') { $ret = pg_send_execute($this->getHandler(), $identifier, $parameters); return $this ->testQuery($ret, sprintf("Prepared query '%s'.", $identifier)) ->getQueryResult(sprintf("EXECUTE ===\n%s\n ===\nparameters = {%s}", $sql, join(', ', $parameters))) ; }
write a sequence of bytes. First writes the number of bytes as an int, then the bytes themselves. @throws java.io.IOException If there is IO error.
public BinaryEncoder writeBytes(byte[] bytes) throws IOException { writeLong(bytes.length); output.write(bytes, 0, bytes.length); return this; }
// openCache initializes the cache from row ids persisted to disk.
func (f *fragment) openCache() error { // Determine cache type from field name. switch f.CacheType { case CacheTypeRanked: f.cache = NewRankCache(f.CacheSize) case CacheTypeLRU: f.cache = newLRUCache(f.CacheSize) case CacheTypeNone: f.cache = globalNopCache return nil default: return ErrInvalidCacheType } // Read cache data from disk. path := f.cachePath() buf, err := ioutil.ReadFile(path) if os.IsNotExist(err) { return nil } else if err != nil { return fmt.Errorf("open cache: %s", err) } // Unmarshal cache data. var pb internal.Cache if err := proto.Unmarshal(buf, &pb); err != nil { f.Logger.Printf("error unmarshaling cache data, skipping: path=%s, err=%s", path, err) return nil } // Read in all rows by ID. // This will cause them to be added to the cache. for _, id := range pb.IDs { n := f.storage.CountRange(id*ShardWidth, (id+1)*ShardWidth) f.cache.BulkAdd(id, n) } f.cache.Invalidate() return nil }
Write message to session @param $message @param string $from @param bool $is_error
private function writeSession($message, $from = '', $is_error = false){ if( session_id() ){ $key = $is_error ? $this->error_key : $this->message_key; // Initialize if( !isset($_SESSION[$key]) || !is_array($_SESSION[$key]) ){ $_SESSION[$key] = []; } // Add message $_SESSION[$key][] = ( empty($from) ? '' : sprintf('<strong>[%s]</strong> ', $from) ).$message; } }
Append a marker for skipped units internal to a string. @param sb the string builder to which to append the text
public void appendSkippedUnit(StringBuffer sb) { if (dr.skippedUnitMarker != null) { sb.append(dr.skippedUnitMarker); } }
// NewRequest creates a new swagger http client request
func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) { return &request{ pathPattern: pathPattern, method: method, writer: writer, header: make(http.Header), query: make(url.Values), timeout: DefaultTimeout, }, nil }
// Prints the body of the response
func (F *Frisby) PrintBody() *Frisby { str, err := F.Resp.Text() if err != nil { F.AddError(err.Error()) return F } fmt.Println(str) return F }
Expand list or dict data into multiple rows :param expr: list / dict sequence / scalar :return:
def explode(expr, *args, **kwargs): if not isinstance(expr, Column): expr = to_collection(expr)[expr.name] if isinstance(expr, SequenceExpr): dtype = expr.data_type else: dtype = expr.value_type func_name = 'EXPLODE' if args and isinstance(args[0], (list, tuple, set)): names = list(args[0]) else: names = args pos = kwargs.get('pos', False) if isinstance(expr, ListSequenceExpr): if pos: func_name = 'POSEXPLODE' typos = [df_types.int64, dtype.value_type] if not names: names = [expr.name + '_pos', expr.name] if len(names) == 1: names = [names[0] + '_pos', names[0]] if len(names) != 2: raise ValueError("The length of parameter 'names' should be exactly 1.") else: typos = [dtype.value_type] if not names: names = [expr.name] if len(names) != 1: raise ValueError("The length of parameter 'names' should be exactly 1.") elif isinstance(expr, DictSequenceExpr): if pos: raise ValueError('Cannot support explosion with pos on dicts.') typos = [dtype.key_type, dtype.value_type] if not names: names = [expr.name + '_key', expr.name + '_value'] if len(names) != 2: raise ValueError("The length of parameter 'names' should be exactly 2.") else: raise ValueError('Cannot explode expression with type %s' % type(expr).__name__) schema = Schema.from_lists(names, typos) return RowAppliedCollectionExpr(_input=expr.input, _func=func_name, _schema=schema, _fields=[expr], _keep_nulls=kwargs.get('keep_nulls', False))
Samples a set of m integers without replacement from the range [0,...,n-1]. @param m The number of integers to return. @param n The number of integers from which to sample. @return The sample as an unsorted integer array.
public static int[] sampleWithoutReplacement(int m, int n) { // This implements a modified form of the genshuf() function from // Programming Pearls pg. 129. // TODO: Design a faster method that only generates min(m, n-m) integers. int[] array = getIndexArray(n); for (int i=0; i<m; i++) { int j = Prng.nextInt(n - i) + i; // Swap array[i] and array[j] int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } return Arrays.copyOf(array, m); }
Updates the port monitor configuration of a logical interconnect. Args: resource: Port monitor configuration. Returns: dict: Port monitor configuration.
def update_port_monitor(self, resource, timeout=-1): data = resource.copy() if 'type' not in data: data['type'] = 'port-monitor' uri = "{}{}".format(self.data["uri"], self.PORT_MONITOR_PATH) return self._helper.update(data, uri=uri, timeout=timeout)
Get the translation for the given key. @param string $key @param array $replace @param string $locale @param bool $fallback @return string
public function get($key, array $replace = array(), $locale = null, $fallback = true) { list($namespace, $group, $item) = $this->parseKey($key); // Here we will get the locale that should be used for the language line. If one // was not passed, we will use the default locales which was given to us when // the translator was instantiated. Then, we can load the lines and return. foreach ($this->parseLocale($locale) as $locale) { $this->load($namespace, $group, $locale); $line = $this->getLine( $namespace, $group, $locale, $item, $replace ); // If we cannot find the translation group in the database nor as a file // an entry in the database will be added to the translations. // Keep in mind that a file cannot be used from that point. if(!self::isNamespaced($namespace) && is_null($line)) { // Database stuff $this->database->addTranslation($locale, $group, $key); } if ( ! is_null($line)) break; } // If the line doesn't exist, we will return back the key which was requested as // that will be quick to spot in the UI if language keys are wrong or missing // from the application's language files. Otherwise we can return the line. if ( ! isset($line)) return $key; return $line; }
Helper to read a given `name` mosaic property name. @param string $name Mosaic property name. @return integer|boolean
public function getProperty($name) { $propertiesNames = [ "divisibility" => 0, "initialSupply" => 1, "supplyMutable" => 2, "transferable" => 3, ]; if (! array_key_exists($name, $propertiesNames)) { throw new InvalidArgumentException("Mosaic property name '" . $name ."' is invalid. Must be one of 'divisibility', " . "'initialSupply', 'supplyMutable' or 'transferable'."); } // sort properties lexicographically (see toDTO() overload) $sorted = $this->sortBy("name"); $index = $propertiesNames[$name]; $prop = $sorted->get($index); if ($prop instanceof MosaicProperty) { return $prop->value; } return $prop["value"]; }
// DecodeMsg implements msgp.Decodable
func (z *Session) DecodeMsg(dc *msgp.Reader) (err error) { var field []byte _ = field var isz uint32 isz, err = dc.ReadMapHeader() if err != nil { return } for isz > 0 { isz-- field, err = dc.ReadMapKeyPtr() if err != nil { return } switch msgp.UnsafeString(field) { case "v": var msz uint32 msz, err = dc.ReadMapHeader() if err != nil { return } if z.Values == nil && msz > 0 { z.Values = make(map[string]interface{}, msz) } else if len(z.Values) > 0 { for key, _ := range z.Values { delete(z.Values, key) } } for msz > 0 { msz-- var xvk string var bzg interface{} xvk, err = dc.ReadString() if err != nil { return } bzg, err = dc.ReadIntf() if err != nil { return } z.Values[xvk] = bzg } default: err = dc.Skip() if err != nil { return } } } return }
Fill in the current step's summary and update the state to show the current step has ended.
def end_step(self, lineno, timestamp=None, result_code=None): """""" self.state = self.STATES['step_finished'] step_errors = self.sub_parser.get_artifact() step_error_count = len(step_errors) if step_error_count > settings.PARSER_MAX_STEP_ERROR_LINES: step_errors = step_errors[:settings.PARSER_MAX_STEP_ERROR_LINES] self.artifact["errors_truncated"] = True self.current_step.update({ "finished": timestamp, "finished_linenumber": lineno, # Whilst the result code is present on both the start and end buildbot-style step # markers, for Taskcluster logs the start marker line lies about the result, since # the log output is unbuffered, so Taskcluster does not know the real result at # that point. As such, we only set the result when ending a step. "result": self.RESULT_DICT.get(result_code, "unknown"), "errors": step_errors }) # reset the sub_parser for the next step self.sub_parser.clear()
fastfood command line interface.
def main(argv=None): """""" # pylint: disable=missing-docstring import argparse import traceback class HelpfulParser(argparse.ArgumentParser): def error(self, message, print_help=False): if 'too few arguments' in message: sys.argv.insert(0, os.path.basename(sys.argv.pop(0))) message = ("%s. Try getting help with `%s -h`" % (message, " ".join(sys.argv))) if print_help: self.print_help() sys.stderr.write('\nerror: %s\n' % message) sys.exit(2) parser = HelpfulParser( prog=NAMESPACE, description=__doc__.splitlines()[0], epilog="\n".join(__doc__.splitlines()[1:]), formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) version_string = 'version %s' % fastfood.__version__ parser.description = '%s ( %s )' % (parser.description, version_string) # version_group = subparsers.add_group() version_group = parser.add_argument_group( title='version info', description='Use these arguments to get version info.') vers_arg = version_group.add_argument( '-V', '--version', action='version', help="Return the current fastfood version.", version='%s %s' % (parser.prog, version_string)) class LatestVersionAction(vers_arg.__class__): def __call__(self, prsr, *args, **kw): info = _release_info() vers = info['info']['version'] release = info['releases'][vers][0] uploaded = datetime.strptime( release['upload_time'], '%Y-%m-%dT%H:%M:%S') sym = EXCLAIM if vers != fastfood.__version__ else CHECK message = u"{} fastfood version {} uploaded {}\n" message = message.format(sym, vers, uploaded.ctime()) prsr.exit(message=message) version_group.add_argument( '-L', '--latest', action=LatestVersionAction, help="Lookup the latest relase from PyPI.") verbose = parser.add_mutually_exclusive_group() verbose.add_argument('-v', dest='loglevel', action='store_const', const=logging.INFO, help="Set log-level to INFO.") verbose.add_argument('-vv', dest='loglevel', action='store_const', const=logging.DEBUG, help="Set log-level to DEBUG.") parser.set_defaults(loglevel=logging.WARNING) home = os.getenv('HOME') or os.path.expanduser('~') or os.getcwd() parser.add_argument( '--template-pack', help='template pack location', default=getenv( 'template_pack', os.path.join(home, '.fastfood'))) parser.add_argument( '--cookbooks', help='cookbooks directory', default=getenv( 'cookbooks', os.path.join(home, 'cookbooks'))) subparsers = parser.add_subparsers( dest='_subparsers', title='fastfood commands', description='operations...', help='...') # # `fastfood list` # list_parser = subparsers.add_parser( 'list', help='List available stencils', formatter_class=argparse.ArgumentDefaultsHelpFormatter) list_parser.add_argument('stencil_set', nargs='?', help="Stencil set to list stencils from") list_parser.set_defaults(func=_fastfood_list) # # `fastfood show <stencil_set>` # show_parser = subparsers.add_parser( 'show', help='Show stencil set information', formatter_class=argparse.ArgumentDefaultsHelpFormatter) show_parser.add_argument('stencil_set', help="Stencil set to list stencils from") show_parser.set_defaults(func=_fastfood_show) # # `fastfood build` # build_parser = subparsers.add_parser( 'build', help='Create or update a cookbook using a config', formatter_class=argparse.ArgumentDefaultsHelpFormatter) build_parser.add_argument('config_file', help="JSON config file") build_parser.add_argument('--force', '-f', action='store_true', default=False, help="Overwrite existing files.") build_parser.set_defaults(func=_fastfood_build) setattr(_LOCAL, 'argparser', parser) if not argv: argv = None args = parser.parse_args(args=argv) if hasattr(args, 'options'): args.options = {k: v for k, v in args.options} logging.basicConfig(level=args.loglevel) try: args.func(args) except exc.FastfoodError as err: title = exc.get_friendly_title(err) print('%s %s: %s' % (RED_X, title, str(err)), file=sys.stderr) sys.stderr.flush() sys.exit(1) except Exception as err: print('%s Unexpected error. Please report this traceback.' % INTERROBANG, file=sys.stderr) traceback.print_exc() # todo: tracack in -v or -vv mode? sys.stderr.flush() sys.exit(1) except KeyboardInterrupt: sys.exit("\nStahp")
По умолчанию длина 32 символа, если количество символов не передано в параметре $length
public static function randomUid($length = 16) { if(!isset($length) || intval($length) <= 8 ){ $length = 16; } if (function_exists('random_bytes')) { return bin2hex(random_bytes($length)); } if (function_exists('mcrypt_create_iv')) { return bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)); } if (function_exists('openssl_random_pseudo_bytes')) { return bin2hex(openssl_random_pseudo_bytes($length)); } }
Aggregate cross-validation results.
def _agg_cv_result(raw_results, eval_train_metric=False): """""" cvmap = collections.defaultdict(list) metric_type = {} for one_result in raw_results: for one_line in one_result: if eval_train_metric: key = "{} {}".format(one_line[0], one_line[1]) else: key = one_line[1] metric_type[key] = one_line[3] cvmap[key].append(one_line[2]) return [('cv_agg', k, np.mean(v), metric_type[k], np.std(v)) for k, v in cvmap.items()]
Deactivates your account. @param string $reason @param string $explanation @return bool
public function deactivate($reason = 'other', $explanation = '') { $userId = $this->id(); if ($userId === null) { return false; } $request = [ 'user_id' => $userId, 'reason' => $reason, 'explanation' => $explanation, ]; return $this->post(UrlBuilder::RESOURCE_DEACTIVATE_ACCOUNT, $request); }
Copy the content to host system clipboard. This is only supported on Mac for now.
function copyToClipBoard(content) { switch (process.platform) { case 'darwin': var child = spawn('pbcopy', []); child.stdin.end(new Buffer(content, 'utf8')); return true; default: return false; } }
Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None
def create_dir(self, jbfile): try: jbfile.create_directory() except os.error: self.statusbar.showMessage('Could not create path: %s' % jbfile.get_path())
Export the page data for the mustache template. @param renderer_base $output renderer to be used to render the page elements. @return stdClass
public function export_for_template(renderer_base $output) { $data = (object)[]; $data->hasonbehalfagreements = false; $data->pluginbaseurl = (new moodle_url('/admin/tool/policy'))->out(false); $data->returnurl = $this->returnurl; // Get the list of policies and versions that current user is able to see // and the respective acceptance records for the selected user. $policies = api::get_policies_with_acceptances($this->userid); $versionids = []; $canviewfullnames = has_capability('moodle/site:viewfullnames', \context_system::instance()); foreach ($policies as $policy) { foreach ($policy->versions as $version) { $versionids[$version->id] = $version->id; unset($version->summary); unset($version->content); $version->iscurrent = ($version->status == policy_version::STATUS_ACTIVE); $version->isoptional = ($version->optional == policy_version::AGREEMENT_OPTIONAL); $version->name = $version->name; $version->revision = $version->revision; $returnurl = new moodle_url('/admin/tool/policy/user.php', ['userid' => $this->userid]); $version->viewurl = (new moodle_url('/admin/tool/policy/view.php', [ 'policyid' => $policy->id, 'versionid' => $version->id, 'returnurl' => $returnurl->out(false), ]))->out(false); if ($version->acceptance !== null) { $acceptance = $version->acceptance; $version->timeaccepted = userdate($acceptance->timemodified, get_string('strftimedatetime')); $onbehalf = $acceptance->usermodified && $acceptance->usermodified != $this->userid; if ($version->acceptance->status == 1) { $version->agreement = new user_agreement($this->userid, [$version->id], [], $returnurl, [$version->id => $version->name], $onbehalf); } else { $version->agreement = new user_agreement($this->userid, [], [$version->id], $returnurl, [$version->id => $version->name], $onbehalf); } if ($onbehalf) { $usermodified = (object)['id' => $acceptance->usermodified]; username_load_fields_from_object($usermodified, $acceptance, 'mod'); $profileurl = new \moodle_url('/user/profile.php', array('id' => $usermodified->id)); $version->acceptedby = \html_writer::link($profileurl, fullname($usermodified, $canviewfullnames || has_capability('moodle/site:viewfullnames', \context_user::instance($acceptance->usermodified)))); $data->hasonbehalfagreements = true; } $version->note = format_text($acceptance->note); } else if ($version->iscurrent) { $version->agreement = new user_agreement($this->userid, [], [], $returnurl, [$version->id => $version->name]); } if (isset($version->agreement)) { $version->agreement = $version->agreement->export_for_template($output); } } if ($policy->versions[0]->status != policy_version::STATUS_ACTIVE) { // Add an empty "currentversion" on top. $policy->versions = [0 => (object)[]] + $policy->versions; } $policy->versioncount = count($policy->versions); $policy->versions = array_values($policy->versions); $policy->versions[0]->isfirst = 1; $policy->versions[0]->hasarchived = (count($policy->versions) > 1); } $data->policies = array_values($policies); $data->canrevoke = \tool_policy\api::can_revoke_policies(array_keys($versionids), $this->userid); return $data; }
getLoaderConfig @return mixed
protected function getLoaderConfig() { return [ LoaderInterface::FROM_STRING => false, LoaderInterface::SIMPLEXML => false, LoaderInterface::DOM_CLASS => __NAMESPACE__.'\\Dom\DOMDocument', LoaderInterface::SIMPLEXML_CLASS => __NAMESPACE__.'\\SimpleXMLElement' ]; }
Subclasses may override this method.
def _set_scale(self, value): sx, sxy, syx, sy, ox, oy = self.transformation sx, sy = value self.transformation = (sx, sxy, syx, sy, ox, oy)
// _NET_WM_USER_TIME set
func WmUserTimeWindowSet(xu *xgbutil.XUtil, win xproto.Window, timeWin xproto.Window) error { return xprop.ChangeProp32(xu, win, "_NET_WM_USER_TIME_WINDOW", "CARDINAL", uint(timeWin)) }
help [COMMAND] List available commands with no arguments, or detailed help when a command is provided.
def do_help(self, line): # We provide a help function so that we can trim the leading spaces # from the docstrings. The builtin help function doesn't do that. if not line: cmd.Cmd.do_help(self, line) self.print(EXIT_STR) return parser = self.create_argparser(line) if parser: parser.print_help() return try: doc = getattr(self, 'do_' + line).__doc__ if doc: self.print("%s" % trim(doc)) return except AttributeError: pass self.print(str(self.nohelp % (line,)))
Apply effect on picture @param Picture $picture
public function apply(Picture $picture) { // GD VERSION IS BETTER AND IS PREFERRED if($picture->isGd() || $picture->gdAvailable()) { $resource = $picture->getResource($picture::WORKER_GD); imagefilter($resource, IMG_FILTER_EDGEDETECT); $picture->setResource($resource); } else { $resource = $picture->getResource($picture::WORKER_IMAGICK); $resource->convolveImage(array( -1,-1,-1,-1,8,-1,-1,-1,-1 )); $resource->thresholdImage(1); } }
// NewStreamLogger produces a fully configured Sender that writes // un-formatted log messages to an io.Writer (or conforming subset).
func NewStreamLogger(name string, ws WriteStringer, l LevelInfo) (Sender, error) { return setup(MakeStreamLogger(ws), name, l) }
Forward on messages from the bus to all IRC connections.
def consume(self, msg): log.debug("Got message %r" % msg) topic, body = msg.get('topic'), msg.get('body') for client in self.irc_clients: if not client.factory.filters or ( client.factory.filters and self.apply_filters(client.factory.filters, topic, body) ): raw_msg = self.prettify( topic=topic, msg=body, pretty=client.factory.pretty, terse=client.factory.terse, short=client.factory.short, ) send = getattr(client, self.hub.config['irc_method'], 'notice') send(client.factory.channel, raw_msg.encode('utf-8')) backlog = self.incoming.qsize() if backlog and (backlog % 20) == 0: warning = "* backlogged by %i messages" % backlog log.warning(warning) send(client.factory.channel, warning.encode('utf-8'))
Parse a git repository with all it's commits and load it into elasticsearch using `client`. If the index doesn't exist it will be created.
def load_repo(client, path=None, index='git'): path = dirname(dirname(abspath(__file__))) if path is None else path repo_name = basename(path) repo = git.Repo(path) create_git_index(client, index) # we let the streaming bulk continuously process the commits as they come # in - since the `parse_commits` function is a generator this will avoid # loading all the commits into memory for ok, result in streaming_bulk( client, parse_commits(repo.refs.master.commit, repo_name), index=index, doc_type='doc', chunk_size=50 # keep the batch sizes small for appearances only ): action, result = result.popitem() doc_id = '/%s/doc/%s' % (index, result['_id']) # process the information from ES whether the document has been # successfully indexed if not ok: print('Failed to %s document %s: %r' % (action, doc_id, result)) else: print(doc_id)
// GetTopBlock returns the top-most block in this directory block tree.
func (dd *DirData) GetTopBlock(ctx context.Context, rtype BlockReqType) ( *DirBlock, error) { topBlock, _, err := dd.getter( ctx, dd.tree.kmd, dd.rootBlockPointer(), dd.tree.file, rtype) if err != nil { return nil, err } return topBlock, nil }
// Validate checks the field values on JwtHeader with the rules defined in the // proto definition for this message. If any rules are violated, an error is returned.
func (m *JwtHeader) Validate() error { if m == nil { return nil } if len(m.GetName()) < 1 { return JwtHeaderValidationError{ field: "Name", reason: "value length must be at least 1 bytes", } } // no validation rules for ValuePrefix return nil }
Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None
def execute_request_handler(self): self._response_timeout_handler = self.loop.call_later( self.response_timeout, self.response_timeout_callback ) self._last_request_time = time() self._request_handler_task = self.loop.create_task( self.request_handler( self.request, self.write_response, self.stream_response ) )
// SetSortBy sets the SortBy field's value.
func (s *GetFaceSearchInput) SetSortBy(v string) *GetFaceSearchInput { s.SortBy = &v return s }
Decodes HTML entities to produce a string containing only valid Unicode scalar values.
public static String decodeHtml(String s) { int firstAmp = s.indexOf('&'); int safeLimit = longestPrefixOfGoodCodeunits(s); if ((firstAmp & safeLimit) < 0) { return s; } StringBuilder sb; { int n = s.length(); sb = new StringBuilder(n); int pos = 0; int amp = firstAmp; while (amp >= 0) { long endAndCodepoint = HtmlEntities.decodeEntityAt(s, amp, n); int end = (int) (endAndCodepoint >>> 32); int codepoint = (int) endAndCodepoint; sb.append(s, pos, amp).appendCodePoint(codepoint); pos = end; amp = s.indexOf('&', end); } sb.append(s, pos, n); } stripBannedCodeunits( sb, firstAmp < 0 ? safeLimit : safeLimit < 0 ? firstAmp : Math.min(firstAmp, safeLimit)); return sb.toString(); }
// BasicAuth returns basic auth handler.
func BasicAuth(username, password string) http.HandlerFunc { // Inspired by https://github.com/codegangsta/martini-contrib/blob/master/auth/ return func(res http.ResponseWriter, req *http.Request) { if !secureCompare(req.Header.Get("Authorization"), "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)), ) { res.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"", ) http.Error(res, "Not Authorized", http.StatusUnauthorized) } } }
We have errors in the form. If ajax, return them as json. Otherwise, proceed as normal.
def form_invalid(self, form): if self.request.is_ajax(): return self.render_json_response(self.get_error_result(form)) return super(AjaxFormMixin, self).form_invalid(form)
Find blocks that are 1D overlapping, returns cliques of block ids that are in conflict
def get_1D_overlap(eclusters, depth=1): overlap_set = set() active = set() ends = [] for i, (chr, left, right) in enumerate(eclusters): ends.append((chr, left, 0, i)) # 0/1 for left/right-ness ends.append((chr, right, 1, i)) ends.sort() chr_last = "" for chr, pos, left_right, i in ends: if chr != chr_last: active.clear() if left_right == 0: active.add(i) else: active.remove(i) if len(active) > depth: overlap_set.add(tuple(sorted(active))) chr_last = chr return overlap_set
Converts pixel coordinates in given zoom level of pyramid to EPSG:900913 @return
public double[] PixelsToMeters( double px, double py, int zoom ) { double res = Resolution(zoom); double mx = px * res - originShift; double my = py * res - originShift; return new double[]{mx, my}; }
Method evaluateDiscriminator Used to determine whether a supplied fully qualified discriminator matches a supplied wildcarded discriminator expression. @param fullTopic @param wildcardTopic @return @throws SIDiscriminatorSyntaxException
public boolean evaluateDiscriminator( String fullTopic, String wildcardTopic) throws SIDiscriminatorSyntaxException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "evaluateDiscriminator", new Object[] { fullTopic, wildcardTopic }); boolean discriminatorMatches = evaluateDiscriminator(fullTopic, wildcardTopic, null); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "evaluateDiscriminator", Boolean.valueOf(discriminatorMatches)); return discriminatorMatches; }
Run the migrations. @return void
public function up() { Schema::create('acl_users_status', function (Blueprint $table) { $table->unsignedInteger('user_id')->index(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->enum('access_panel',['yes', 'no'])->default('no'); $table->enum('status',['active', 'inactive'])->default('active'); $table->primary('user_id'); }); }
Find PHPMD @return string @throws BuildException
protected function loadDependencies() { if (!empty($this->pharLocation)) { include_once 'phar://' . $this->pharLocation . '/vendor/autoload.php'; } $className = '\PHPMD\PHPMD'; if (!class_exists($className)) { @include_once 'PHP/PMD.php'; $className = "PHP_PMD"; $this->newVersion = false; } if (!class_exists($className)) { throw new BuildException( 'PHPMDTask depends on PHPMD being installed and on include_path or listed in pharLocation.', $this->getLocation() ); } if ($this->newVersion) { $minPriority = \PHPMD\AbstractRule::LOWEST_PRIORITY; include_once 'phing/tasks/ext/phpmd/PHPMDRendererRemoveFromCache.php'; } else { include_once 'PHP/PMD/AbstractRule.php'; $minPriority = PHP_PMD_AbstractRule::LOWEST_PRIORITY; } if (!$this->minimumPriority) { $this->minimumPriority = $minPriority; } return $className; }
Normalize menu @param array $assigned @param array $menus @param Closure $callback @param integer $parent @return array
private static function normalizeMenu(&$assigned, &$menus, $callback, $parent = null) { $result = []; $order = []; foreach ($assigned as $id) { $menu = $menus[$id]; $item = [ 'id'=> $menu['id'], 'name' => $menu['name'], 'route' => static::parseRoute($menu['route'])[0], 'parent_id' => $menu['parent'] ]; $result[] = $item; $order[] = $menu['order']; } if ($result != []) { array_multisort($order, $result); } return $result; }
Add a new variable. @param sName The name (=local part) of the variable @param aValue The value to be used. @return {@link EChange}
@Nonnull public EChange addUniqueVariable (@Nonnull final String sName, @Nonnull final Object aValue) { ValueEnforcer.notNull (sName, "Name"); ValueEnforcer.notNull (aValue, "Value"); if (m_aMap.containsKey (sName)) return EChange.UNCHANGED; m_aMap.put (sName, aValue); return EChange.CHANGED; }
Builds an instance of T using the selected constructor getting the constructor parameters from the {@link CommandLine}. Note: this method will also automatically call {@link #applyCommandLineOptions(CommandLine, T)} on the constructed object.
private T buildInstance(CommandLine cli) { String[] constructorArgs = new String[this.constructor.getParameterTypes().length]; for (Option option : cli.getOptions()) { if (this.constructoArgumentsMap.containsKey(option.getOpt())) { int idx = this.constructoArgumentsMap.get(option.getOpt()); constructorArgs[idx] = option.getValue(); } } T embeddedGobblin; try { embeddedGobblin = this.constructor.newInstance((Object[]) constructorArgs); return embeddedGobblin; } catch (IllegalAccessException | InvocationTargetException | InstantiationException exc) { throw new RuntimeException("Could not instantiate " + this.klazz.getName(), exc); } }
Default text function will either print 'None selected' in case no option is selected or a list of the selected options up to a length of 3 selected options. @param {jQuery} options @param {jQuery} select @returns {String}
function(options, select) { if (options.length === 0) { return this.nonSelectedText; } else if (this.allSelectedText && options.length === $('option', $(select)).length && $('option', $(select)).length !== 1 && this.multiple) { if (this.selectAllNumber) { return this.allSelectedText + ' (' + options.length + ')'; } else { return this.allSelectedText; } } else if (options.length > this.numberDisplayed) { return options.length + ' ' + this.nSelectedText; } else { var selected = ''; var delimiter = this.delimiterText; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text(); selected += label + delimiter; }); return selected.substr(0, selected.length - 2); } }
XHR: uses CORS to make requests
function(method, url, headers, data, callback) { var r = new XMLHttpRequest(); var error = this.error; // Binary? var binary = false; if (method === 'blob') { binary = method; method = 'GET'; } method = method.toUpperCase(); // Xhr.responseType 'json' is not supported in any of the vendors yet. r.onload = function(e) { var json = r.response; try { json = JSON.parse(r.responseText); } catch (_e) { if (r.status === 401) { json = error('access_denied', r.statusText); } } var headers = headersToJSON(r.getAllResponseHeaders()); headers.statusCode = r.status; callback(json || (method === 'GET' ? error('empty_response', 'Could not get resource') : {}), headers); }; r.onerror = function(e) { var json = r.responseText; try { json = JSON.parse(r.responseText); } catch (_e) {} callback(json || error('access_denied', 'Could not get resource')); }; var x; // Should we add the query to the URL? if (method === 'GET' || method === 'DELETE') { data = null; } else if (data && typeof (data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)) { // Loop through and add formData var f = new FormData(); for (x in data) if (data.hasOwnProperty(x)) { if (data[x] instanceof HTMLInputElement) { if ('files' in data[x] && data[x].files.length > 0) { f.append(x, data[x].files[0]); } } else if (data[x] instanceof Blob) { f.append(x, data[x], data.name); } else { f.append(x, data[x]); } } data = f; } // Open the path, async r.open(method, url, true); if (binary) { if ('responseType' in r) { r.responseType = binary; } else { r.overrideMimeType('text/plain; charset=x-user-defined'); } } // Set any bespoke headers if (headers) { for (x in headers) { r.setRequestHeader(x, headers[x]); } } r.send(data); return r; // Headers are returned as a string function headersToJSON(s) { var r = {}; var reg = /([a-z\-]+):\s?(.*);?/gi; var m; while ((m = reg.exec(s))) { r[m[1]] = m[2]; } return r; } }
Closes the current application and also close webdriver session.
def close_application(self): """""" self._debug('Closing application with session id %s' % self._current_application().session_id) self._cache.close()
All HTTP Errors will extend from this object
function HttpError(message, options) { // handle constructor call without 'new' if (!(this instanceof HttpError)) { return new HttpError(message, options); } HttpError.super_.call(this); Error.captureStackTrace(this, this.constructor); this.name = 'HttpError'; this.message = message; this.status = 500; options = options || {}; if (options.code) { this.code = options.code; } if (options.errors) { this.errors = options.errors; } if (options.headers) { this.headers = options.headers; } if (options.cause) { this.cause = options.cause; } }
Set default jobs @param mixed $callback @param mixed $params
public function doTheJob($callback, $params = array()) { if (!$callback instanceof CallbackHandler) { $callback = new CallbackHandler($callback); } if (!is_array($params)) { $params = array($params); } $this->callback = $callback; $this->callbackParam = $params; return $this; }
// pmsQueryBuilder returns the same pointer passed as first argument, with new specified options setted
func pmsQueryBuilder(query *igor.Database, options PmsOptions) *igor.Database { query = query.Limit(int(AtMostPms(uint64(options.N)))).Order("pmid DESC") if options.Older != 0 && options.Newer != 0 { query = query.Where("pmid BETWEEN ? AND ?", options.Newer, options.Older) } else if options.Older != 0 { query = query.Where("pmid < ?", options.Older) } else if options.Newer != 0 { query = query.Where("pmid > ?", options.Newer) } return query }
Generate a single list of items packed. @return PackedItemList
protected function getPackedItemList(): PackedItemList { $packedItemList = new PackedItemList(); foreach ($this->layers as $layer) { foreach ($layer->getItems() as $packedItem) { $packedItemList->insert($packedItem); } } return $packedItemList; }
/* (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ExoContainer container = getContainer(); SessionProviderService providerService = (SessionProviderService)container.getComponentInstanceOfType(SessionProviderService.class); ConversationRegistry stateRegistry = (ConversationRegistry)container.getComponentInstanceOfType(ConversationRegistry.class); HttpServletRequest httpRequest = (HttpServletRequest)request; ConversationState state = ConversationState.getCurrent(); SessionProvider provider = null; // NOTE not create new HTTP session, if session is not created yet // this means some settings is incorrect, see web.xml for filter // org.exoplatform.services.security.web.SetCurrentIdentityFilter HttpSession httpSession = httpRequest.getSession(false); if (state == null) { if (LOG.isDebugEnabled()) { LOG.debug("Current conversation state is not set"); } if (httpSession != null) { StateKey stateKey = new HttpSessionStateKey(httpSession); // initialize thread local SessionProvider state = stateRegistry.getState(stateKey); if (state != null) { provider = new SessionProvider(state); } else if (LOG.isDebugEnabled()) { LOG.debug("WARN: Conversation State is null, id " + httpSession.getId()); } } } else { provider = new SessionProvider(state); } if (provider == null) { if (LOG.isDebugEnabled()) { LOG.debug("Create SessionProvider for anonymous."); } provider = SessionProvider.createAnonimProvider(); } try { if (ConversationState.getCurrent() != null) { ConversationState.getCurrent().setAttribute(SessionProvider.SESSION_PROVIDER, provider); } providerService.setSessionProvider(null, provider); chain.doFilter(request, response); } finally { if (ConversationState.getCurrent() != null) { try { ConversationState.getCurrent().removeAttribute(SessionProvider.SESSION_PROVIDER); } catch (Exception e) { LOG.warn("An error occured while removing the session provider from the conversation state", e); } } if (providerService.getSessionProvider(null) != null) { try { // remove SessionProvider providerService.removeSessionProvider(null); } catch (Exception e) { LOG.warn("An error occured while cleaning the ThreadLocal", e); } } } }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XbasePackage.XASSIGNMENT__ASSIGNABLE: setAssignable((XExpression)newValue); return; case XbasePackage.XASSIGNMENT__VALUE: setValue((XExpression)newValue); return; case XbasePackage.XASSIGNMENT__EXPLICIT_STATIC: setExplicitStatic((Boolean)newValue); return; case XbasePackage.XASSIGNMENT__STATIC_WITH_DECLARING_TYPE: setStaticWithDeclaringType((Boolean)newValue); return; } super.eSet(featureID, newValue); }
<code>optional .alluxio.grpc.file.FileSystemHeartbeatPOptions options = 3;</code>
public alluxio.grpc.FileSystemHeartbeatPOptionsOrBuilder getOptionsOrBuilder() { return options_ == null ? alluxio.grpc.FileSystemHeartbeatPOptions.getDefaultInstance() : options_; }
Builds a method's API endpoint. @param {Object} config The host and port parameters to use. @param {String} path The path to the serverside method. @return {String} The endpoint to request.
function buildEndpoint(config, path) { var host = config.host; var port = config.port; if (!host) throw new Error('No host is specified in proxied method config'); var base = host + (port ? ':' + port : ''); var fullpath = '/isomorphine/' + path; var endpoint = base + fullpath; debug('Built endpoint: ' + endpoint); return endpoint; }
Builder for array of Template from Active Record model @param EmailTemplateTranslation[] $models @return array
public static function buildTemplates($models) { $result = []; foreach($models as $model) { $result[] = self::buildTemplate($model); } return $result; }
Inserts data into this table and returns ID. @access public @param array $data associative array of data to store @param bool $stripTags Flag: strip HTML Tags from values @return int ID of inserted row
public function insert( $data = array(), $stripTags = TRUE ){ $columns = array(); $values = array(); foreach( $this->columns as $column ){ // iterate Columns if( !isset( $data[$column] ) ) // no Data given for Column continue; $value = $data[$column]; if( $stripTags ) $value = strip_tags( $value ); $columns[$column] = $column; $values[$column] = $this->secureValue( $value ); } if( $this->isFocused() ){ // add focused indices to data foreach( $this->focusedIndices as $index => $value ){ // iterate focused indices if( isset( $columns[$index] ) ) // Column is already set continue; if( $index == $this->primaryKey ) // skip primary key continue; $columns[$index] = $index; // add key $values[$index] = $this->secureValue( $value ); // add value } } $columns = $this->getColumnEnumeration( $columns ); // get enumeration of masked column names $values = implode( ', ', array_values( $values ) ); $query = 'INSERT INTO '.$this->getTableName().' ('.$columns.') VALUES ('.$values.')'; $this->dbc->exec( $query ); return $this->dbc->lastInsertId(); }
Renders the batch tool
public function renderBatchTool() { wp_enqueue_style('ilab-media-importer-css', ILAB_PUB_CSS_URL.'/ilab-media-importer.min.css'); $data = BatchManager::instance()->stats($this->batchIdentifier()); $postData = $this->getImportBatch(1); $data['posts'] = $postData['posts']; $data['pages'] = $postData['pages']; $background = EnvironmentOptions::Option('ilab-media-s3-batch-background-processing', null, true); if (!$background) { $data['total'] = $postData['total']; } else { if($data['total'] == 0) { $data['total'] = $postData['total']; } } if ($postData['shouldRun']) { $data['status'] = 'running'; } else { $data['status'] = ($data['running']) ? 'running' : 'idle'; } $data['shouldRun'] = $postData['shouldRun']; $data['enabled'] = $this->enabled(); $data['title'] = $this->title(); $data['instructions'] = View::render_view($this->instructionView(), ['background' => $background]); $data['fromSelection'] = $postData['fromSelection']; $data['disabledText'] = 'enable Storage'; $data['commandLine'] = null; $data['commandTitle'] = 'Run Tool'; $data['cancelCommandTitle'] = 'Cancel Tool'; $data['cancelAction'] = $this->cancelActionName(); $data['startAction'] = $this->startActionName(); $data['manualAction'] = $this->manualActionName(); $data['progressAction'] = $this->progressActionName(); $data['nextBatchAction'] = $this->nextBatchActionName(); $data['background'] = $background; $data = $this->filterRenderData($data); echo View::render_view('importer/importer.php', $data); }
Parse an S3 URL and extract the bucket and key. @param string $url @return array
public function parseUrl($url) { $region = $this->getConfig('region'); $bucket = $this->getConfig('bucket'); $key = $url; if (strpos($url, 'amazonaws.com') !== false) { // s3<region>.amazonaws.com/<bucket> if (preg_match('/^https?:\/\/s3(.+?)?\.amazonaws\.com\/(.+?)\/(.+?)$/i', $url, $matches)) { $region = $matches[1] ?: $region; $bucket = $matches[2]; $key = $matches[3]; // <bucket>.s3<region>.amazonaws.com } else if (preg_match('/^https?:\/\/(.+?)\.s3(.+?)?\.amazonaws\.com\/(.+?)$/i', $url, $matches)) { $bucket = $matches[1]; $region = $matches[2] ?: $region; $key = $matches[3]; } } return array( 'bucket' => $bucket, 'key' => trim($key, '/'), 'region' => trim($region, '-') ); }
Return the given element, searching by ID @param string $callerClass The class of the object to be returned @param int $id The id of the element @param boolean $cache See {@link get_one()} @return DataObject The element
public function byId($callerClass, $id, $cache = true, $requiredPerm = 'View') { $id = (int) $id; $item = DataObject::get_by_id($callerClass, $id, $cache); if ($item && $item->hasExtension('Restrictable') && $item->checkPerm($requiredPerm)) { return $item; } if ($item && !$item->hasExtension('Restrictable') && $item->canView()) { return $item; } }
Decodes the lemma induced type into the lemma and sets it as value of the Span type. @param tokens the tokens in the sentence @param preds the predicted spans
public static void decodeLemmasToSpans(final String[] tokens, final Span[] preds) { for (final Span span : preds) { String lemma = decodeShortestEditScript( span.getCoveredText(tokens).toLowerCase(), span.getType()); // System.err.println("-> DEBUG: " + toks[i].toLowerCase() + " " + // preds[i] + " " + lemma); if (lemma.length() == 0) { lemma = "_"; } span.setType(lemma); } }
Get all rows with data from table @param string $tbl - table name @param string $where - for where clause @return array fetched data
public static function getRows($tbl, $where = ''): array { $res = []; $sql = self::getInstance()->sql_query('SELECT * FROM `' . self::sql_prepare($tbl) . '`' . ($where ? ' WHERE ' . $where : '')); while ($q = $sql->fetch(PDO::FETCH_ASSOC)) { $res[] = $q; } return $res; }
Gets the file bound to the FileDescription (returns null if not file in persistent memory). @access public @author Jerome Bogaerts, <jerome@taotesting.com> @return File
public function getFile() { if (is_null($this->file)) { $referencer = $this->getServiceLocator()->get(FileReferenceSerializer::SERVICE_ID); $this->file = $referencer->unserialize($this->getFileSerial()); } return $this->file; }
Create a new buffer with the input contents. @param data {Array|String} The buffer's data. @param enc {String} Encoding, used if data is a string.
function bufferFrom(data, enc) { if (typeof Buffer.from == 'function') { return Buffer.from(data, enc); } else { return new Buffer(data, enc); } }
Sends data to logstash.
function send(socket, host, port, loggingObject) { var buffer = new Buffer(JSON.stringify(loggingObject)); socket.send(buffer, 0, buffer.length, port, host, function(err, bytes) { if (err) { console.error('log4js-logstash-appender (%s:%p) - %s', host, port, util.inspect(err)); } }); }
// Register registers common flags with the given flag.FlagSet.
func (f *CommonFlags) Register(flags *flag.FlagSet, params *Parameters) { f.authFlags.Register(flags, params.AuthOptions) flags.BoolVar(&f.tsv, "tsv", false, "Whether to emit data in tsv instead of human-readable format.") }
Return an iterable of the listeners which have been added to this batch processor.
def getReliableListeners(self): for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self): yield rellist.listener
An interactive way to restore the colormap contrast settings after a warp operation.
def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True): if self.cancmap and (event.state == 'down'): self.restore_contrast(viewer, msg=msg) return True
Renders a template and writes the output directly to the response. <p>This method commits the response.</p> @param templateName @param model
public void render(String templateName, Map<String, Object> model) { send(renderToString(templateName, model)); }
Retorna o path até uma rota nomeada, trocando seus parametros caso necessário @param $routeName string @param $params array @return string
public function pathFor($routeName, $params = array()) { if ($rota = $this->getRoute($routeName)) { $pattern = $rota->getPattern(); $qtdParams = count($rota->getParamNames()); $withOptions = preg_match('/\[:options\]/', $pattern); if ($qtdParams > 0 && count($params) == 0) { throw new \RuntimeException('A rota '.$routeName.' requer '.$qtdParams.' parametro(s)!'); } if ($withOptions && count($params) > 0) { $pattern = str_replace('[:options]', '', $pattern); $pattern .= implode('/', $params); } elseif (count($params) > 0) { foreach ($params as $key => $value) { $pattern = str_replace(':'.$key, $value, $pattern); } } return $this->request->getRoot().$pattern; } }
Send the "304 Not Modified" response. This response can be used when the file timestamp is the same as what the browser is sending up. @param ctx The channel context to write the response to.
public static void sendNotModified(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED); setDateHeader(response); // close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
// RemoveInstancesFromInstanceGroup removes the given instances from the instance group.
func (gce *Cloud) RemoveInstancesFromInstanceGroup(name string, zone string, instanceNames []string) error { if len(instanceNames) == 0 { return nil } instances := []*compute.InstanceReference{} for _, ins := range instanceNames { instanceLink := makeHostURL(gce.projectID, zone, ins) instances = append(instances, &compute.InstanceReference{Instance: instanceLink}) } op, err := gce.service.InstanceGroups.RemoveInstances( gce.projectID, zone, name, &compute.InstanceGroupsRemoveInstancesRequest{ Instances: instances, }).Do() if err != nil { if isHTTPErrorCode(err, http.StatusNotFound) { return nil } return err } return gce.waitForZoneOp(op, zone) }
This is information about the system on which we are running.
public static String getSysInfo() { String info = sysInfo.get(); if (info == null) { info = String.format(Locale.ENGLISH, SYS_INFO, System.getProperty("os.name", "unknown")); sysInfo.compareAndSet(null, info); } return info; }
/*[deutsch] <p>Liefert einen Operator, der eine beliebige Entit&auml;t auf das Elementmaximum setzt. </p> @param <T> generic type of target entity @param element associated chronological element @return operator @since 3.5/4.3
public static <T extends ChronoEntity<T>> ChronoOperator<T> maximized(ChronoElement<?> element) { return new StdOperator<>(MAX_MODE, element); }
// updateDeploymentWithAlloc is used to update the deployment state associated // with the given allocation. The passed alloc may be updated if the deployment // status has changed to capture the modify index at which it has changed.
func (s *StateStore) updateDeploymentWithAlloc(index uint64, alloc, existing *structs.Allocation, txn *memdb.Txn) error { // Nothing to do if the allocation is not associated with a deployment if alloc.DeploymentID == "" { return nil } // Get the deployment ws := memdb.NewWatchSet() deployment, err := s.deploymentByIDImpl(ws, alloc.DeploymentID, txn) if err != nil { return err } if deployment == nil { return nil } // Retrieve the deployment state object _, ok := deployment.TaskGroups[alloc.TaskGroup] if !ok { // If the task group isn't part of the deployment, the task group wasn't // part of a rolling update so nothing to do return nil } // Do not modify in-place. Instead keep track of what must be done placed := 0 healthy := 0 unhealthy := 0 // If there was no existing allocation, this is a placement and we increment // the placement existingHealthSet := existing != nil && existing.DeploymentStatus.HasHealth() allocHealthSet := alloc.DeploymentStatus.HasHealth() if existing == nil || existing.DeploymentID != alloc.DeploymentID { placed++ } else if !existingHealthSet && allocHealthSet { if *alloc.DeploymentStatus.Healthy { healthy++ } else { unhealthy++ } } else if existingHealthSet && allocHealthSet { // See if it has gone from healthy to unhealthy if *existing.DeploymentStatus.Healthy && !*alloc.DeploymentStatus.Healthy { healthy-- unhealthy++ } } // Nothing to do if placed == 0 && healthy == 0 && unhealthy == 0 { return nil } // Update the allocation's deployment status modify index if alloc.DeploymentStatus != nil && healthy+unhealthy != 0 { alloc.DeploymentStatus.ModifyIndex = index } // Create a copy of the deployment object deploymentCopy := deployment.Copy() deploymentCopy.ModifyIndex = index state := deploymentCopy.TaskGroups[alloc.TaskGroup] state.PlacedAllocs += placed state.HealthyAllocs += healthy state.UnhealthyAllocs += unhealthy // Update the progress deadline if pd := state.ProgressDeadline; pd != 0 { // If we are the first placed allocation for the deployment start the progress deadline. if placed != 0 && state.RequireProgressBy.IsZero() { // Use modify time instead of create time because we may in-place // update the allocation to be part of a new deployment. state.RequireProgressBy = time.Unix(0, alloc.ModifyTime).Add(pd) } else if healthy != 0 { if d := alloc.DeploymentStatus.Timestamp.Add(pd); d.After(state.RequireProgressBy) { state.RequireProgressBy = d } } } // Upsert the deployment if err := s.upsertDeploymentImpl(index, deploymentCopy, txn); err != nil { return err } return nil }
生成一个空的查询. @return \wulaphp\db\sql\Query
protected function emptyQuery() { $q = new Query(); $q->resultSets = []; $q->resultSet = []; $q->performed = true; $q->countperformed = true; return $q; }
Returns set (possibly multiple) types of refereences to the given resource @param path the path to a publication resource @return an immutable {@link EnumSet} containing the types of references to {@code path}.
public Set<Type> getTypes(String path) { LinkedList<Type> types = new LinkedList<>(); for (Reference reference : references) { if (Preconditions.checkNotNull(path).equals(reference.refResource)) { types.add(reference.type); } } return Sets.immutableEnumSet(types); }