comment
stringlengths
16
255
code
stringlengths
52
3.87M
Process the directory of JSON files using the collected pattern ids @param string[] $coveredIds
public function process(array $coveredIds) : void { $this->setCoveredPatternIds($coveredIds); $finder = new Finder(); $finder->files(); $finder->name('*.json'); $finder->ignoreDotFiles(true); $finder->ignoreVCS(true); $finder->sortByName(); $finder->ignoreUnreadableDirs(); $finder->in($this->resourceDir); foreach ($finder as $file) { /* @var \Symfony\Component\Finder\SplFileInfo $file */ /** @var string $patternFileName */ $patternFileName = mb_substr($file->getPathname(), (int) mb_strpos($file->getPathname(), 'resources/')); if (!isset($this->coveredIds[$patternFileName])) { $this->coveredIds[$patternFileName] = []; } $this->coverage[$patternFileName] = $this->processFile( $patternFileName, $file->getContents(), $this->coveredIds[$patternFileName] ); } }
Gets the rdns String name :param rdns: RDNS object :type rdns: cryptography.x509.RelativeDistinguishedName :return: RDNS name
def get_rdns_name(rdns): name = '' for rdn in rdns: for attr in rdn._attributes: if len(name) > 0: name = name + ',' if attr.oid in OID_NAMES: name = name + OID_NAMES[attr.oid] else: name = name + attr.oid._name name = name + '=' + attr.value return name
// MountHealthController "mounts" a Health resource controller on the given service.
func MountHealthController(service *goa.Service, ctrl HealthController) { initService(service) var h goa.Handler service.Mux.Handle("OPTIONS", "/cellar/_ah/health", ctrl.MuxHandler("preflight", handleHealthOrigin(cors.HandlePreflight()), nil)) h = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error { // Check if there was an error loading the request if err := goa.ContextError(ctx); err != nil { return err } // Build the context rctx, err := NewHealthHealthContext(ctx, req, service) if err != nil { return err } return ctrl.Health(rctx) } h = handleHealthOrigin(h) service.Mux.Handle("GET", "/cellar/_ah/health", ctrl.MuxHandler("health", h, nil)) service.LogInfo("mount", "ctrl", "Health", "action", "Health", "route", "GET /cellar/_ah/health") }
// SendAudioWithKeyboardHide send a audio with explicit Keyboard Hide.
func (bot TgBot) SendAudioWithKeyboardHide(cid int, audio string, duration *int, performer *string, title *string, rmi *int, rm ReplyKeyboardHide) ResultWithMessage { var rkm ReplyMarkupInt = rm return bot.SendAudio(cid, audio, duration, performer, title, rmi, &rkm) }
<p> set data-* attribute </p> <pre> Div div = new Div(); div.setData(&quot;foo&quot;, &quot;bar&quot;); // you get &lt;div data-foo=&quot;bar&quot;&gt;&lt;/div&gt; </pre> @param key data-"key"
public void setData(String key, String value) { QName qn = new QName("data-" + key); this.getOtherAttributes().put(qn, value); }
Unserialize an embedded collection Return a collection of serialized objects (arrays) @param MapperInterface $mapper @param array $data @return array
protected function unserializeEmbeddedCollection(MapperInterface $mapper, array $data) { $collection = array(); foreach ($data as $document) { $collection[] = $mapper->unserialize($document); } return $collection; }
stops the timer with a given name. :param name: the name of the timer :type name: string
def stop(cls, name): cls.timer_end[name] = time.time() if cls.debug: print("Timer", name, "stopped ...")
Gets an object using a from clause. @param type The type of the desired object. @param clause The WHERE clause. @param args The arguments for the WHERE clause. @param <T> The type of the object. @return The object or {@code null}
public static <T> T objectFromClause(Class<T> type, String clause, Object... args) { return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args)); }
pickedPage można podać wcześniej przy konstruktorze @param int $pickedPage @return SqlPaginateParams
public function getSqlPaginateParams($pickedPage = false) { $p = new SqlPaginateParams(); if ($pickedPage) { $this->pickedPage = $pickedPage; } if ($this->pages == 0) { $p->setOffset(0); $p->setLimit(20); return $p; } if ($this->pickedPage > $this->pages) { $this->pickedPage = $this->pages; } if ($this->pickedPage < 1) { $this->pickedPage = 1; } $p->setOffset($this->pickedPage * $this->elementsPerPage - $this->elementsPerPage); $p->setLimit($this->elementsPerPage); return $p; }
Query for intersections of terms in two lists Return a list of intersection result objects with keys: - x : term from x - y : term from y - c : count of intersection - j : jaccard score
def query_intersections(self, x_terms=None, y_terms=None, symmetric=False): if x_terms is None: x_terms = [] if y_terms is None: y_terms = [] xset = set(x_terms) yset = set(y_terms) zset = xset.union(yset) # first built map of gene->termClosure. # this could be calculated ahead of time for all g, # but this may be space-expensive. TODO: benchmark gmap={} for z in zset: gmap[z] = [] for subj in self.subjects: ancs = self.inferred_types(subj) for a in ancs.intersection(zset): gmap[a].append(subj) for z in zset: gmap[z] = set(gmap[z]) ilist = [] for x in x_terms: for y in y_terms: if not symmetric or x<y: shared = gmap[x].intersection(gmap[y]) union = gmap[x].union(gmap[y]) j = 0 if len(union)>0: j = len(shared) / len(union) ilist.append({'x':x,'y':y,'shared':shared, 'c':len(shared), 'j':j}) return ilist
readFile fs promise wrapped @param {string} path @param {string} fileName
function readFile(path, fileName) { return new Promise((resolve, reject) => { fs.readFile(`${path}/${fileName}`, 'utf8', (err, content) => { if (err) { return reject(err) } return resolve(content) }) }) }
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitBuildSource.
func (in *GitBuildSource) DeepCopy() *GitBuildSource { if in == nil { return nil } out := new(GitBuildSource) in.DeepCopyInto(out) return out }
:sockets:: socket list :clean:: clean UTF8 strings or provide block to run on every read string :pool:: ActionPool to use Creates a new watcher for sockets start the watcher
def start if(@sockets.size < 0) raise 'No sockets available for listening' elsif([email protected]? && @runner.alive?) raise AlreadyRunning.new else @stop = false @runner = Thread.new{watch} end end
Registers action aliases for current task @param array $map Alias-to-filename hash array
public function register_action_map($map) { if (is_array($map)) { foreach ($map as $idx => $val) { $this->action_map[$idx] = $val; } } }
Create permission request The call is idempotent; that is, if one posts the same pos_id and pos_tid twice, only one Permission request is created.
def create_permission_request(self, customer, pos_id, pos_tid, scope, ledger=None, text=None, callback_uri=None, expires_in=None): arguments = {'customer': customer, 'pos_id': pos_id, 'pos_tid': pos_tid, 'scope': scope, 'ledger': ledger, 'text': text, 'callback_uri': callback_uri, 'expires_in': expires_in} return self.do_req('POST', self.merchant_api_base_url + '/permission_request/', arguments).json()
// readv returns the tokens starting from the current position until the first // match of t. A match is made only of t.typ and t.val are equal to the examined // token.
func (p *parser) readv(t token) ([]token, error) { var tokens []token for { read, err := p.readt(t.typ) tokens = append(tokens, read...) if err != nil { return tokens, err } if len(read) > 0 && read[len(read)-1].val == t.val { break } } return tokens, nil }
Retrieve the pattern for the given package. @param \Composer\Package\PackageInterface $package @return string
public function getPattern(PackageInterface $package) { if (isset($this->packages[$package->getName()])) { return $this->packages[$package->getName()]; } elseif (isset($this->packages[$package->getPrettyName()])) { return $this->packages[$package->getPrettyName()]; } elseif (isset($this->types[$package->getType()])) { return $this->types[$package->getType()]; } }
Add all the components to this calendar panel. @param dateTarget This date needs to be in the calendar.
public void layoutCalendar(Date timeTarget) { calendar.setTime(timeTarget); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); String[] array = new String[24 * 2]; calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); int selectedIndex = -1; for (int i = 0; i < array.length; i++) { if (hour == calendar.get(Calendar.HOUR_OF_DAY)) if (minute == calendar.get(Calendar.MINUTE)) selectedIndex = i; Date time = calendar.getTime(); String strTime = timeFormat.format(time); array[i] = strTime; calendar.add(Calendar.MINUTE, 30); } DefaultComboBoxModel model = new DefaultComboBoxModel(array); this.setVisibleRowCount(10); this.setModel(model); if (selectedIndex != -1) this.setSelectedIndex(selectedIndex); }
/* [MS-OSHARED] 2.3.3.1.4 Lpstr
function parse_lpstr(blob, type, pad) { var start = blob.l; var str = blob.read_shift(0, 'lpstr-cp'); if(pad) while((blob.l - start) & 3) ++blob.l; return str; }
Validate this measurement and update its 'outcome' field.
def validate(self): """""" # PASS if all our validators return True, otherwise FAIL. try: if all(v(self.measured_value.value) for v in self.validators): self.outcome = Outcome.PASS else: self.outcome = Outcome.FAIL return self except Exception as e: # pylint: disable=bare-except _LOG.error('Validation for measurement %s raised an exception %s.', self.name, e) self.outcome = Outcome.FAIL raise finally: if self._cached: self._cached['outcome'] = self.outcome.name
This method gets the singleton instance of this {@link CollectionReflectionUtilImpl}. <br> <b>ATTENTION:</b><br> Please prefer dependency-injection instead of using this method. @return the singleton instance.
public static CollectionReflectionUtilImpl getInstance() { if (instance == null) { synchronized (CollectionReflectionUtilImpl.class) { if (instance == null) { CollectionReflectionUtilImpl util = new CollectionReflectionUtilImpl(); util.initialize(); instance = util; } } } return instance; }
Add an 'OPTIONS' method supported on all routes for the pre-flight CORS request. @param server a RestExpress server instance.
private void addPreflightOptionsRequestSupport(RestExpress server, CorsOptionsController corsOptionsController) { RouteBuilder rb; for (String pattern : methodsByPattern.keySet()) { rb = server.uri(pattern, corsOptionsController) .action("options", HttpMethod.OPTIONS) .noSerialization() // Disable both authentication and authorization which are usually use header such as X-Authorization. // When browser does CORS preflight with OPTIONS request, such headers are not included. .flag(Flags.Auth.PUBLIC_ROUTE) .flag(Flags.Auth.NO_AUTHORIZATION); for (String flag : flags) { rb.flag(flag); } for (Entry<String, Object> entry : parameters.entrySet()) { rb.parameter(entry.getKey(), entry.getValue()); } routeBuilders.add(rb); } }
/* String[] validTypes = new String[] { "application/xhtml+xml", "application/x-dtbncx+xml", "text/css" };
void buildCSSTypesDictionary() { String description; String value; TextSearchDictionaryEntry de; //search eval() expression description = "text/css"; value = "text/css"; de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009); v.add(de); }
// TODO: This is hacky. Look into using a library like gojsonpointer[1] instead. // // [1] https://github.com/xeipuuv/gojsonpointer
func (s *Schema) refToSchema(str string, rootSchema Schema, loadExternal bool) (*Schema, error) { parentURL, err := url.Parse(s.parentId) if err == nil && parentURL.IsAbs() { sURL, err := url.Parse(str) if err == nil && !sURL.IsAbs() && !strings.HasPrefix(str, "#") { str = parentURL.ResolveReference(sURL).String() } } var split []string url, err := url.Parse(str) cacheKey, cacheKeyErr := resolveCacheKey(str) if err == nil && cacheKeyErr == nil { cachedSchema, ok := rootSchema.Cache[cacheKey] if ok { rootSchema = *cachedSchema } else { // Handle external URIs. if !loadExternal { return new(Schema), errors.New("external schemas are disabled") } resp, err := http.Get(str) if err != nil { return new(Schema), errors.New("bad external url") } defer resp.Body.Close() s, err := ParseWithCache(resp.Body, loadExternal, &rootSchema.Cache) if err != nil { return new(Schema), errors.New("error parsing external doc") } rootSchema.Cache[cacheKey] = s rootSchema = *s } str = url.Fragment } // Remove the prefix from internal URIs. str = strings.TrimPrefix(str, "#") str = strings.TrimPrefix(str, "/") split = strings.Split(str, "/") // Make replacements. for i, v := range split { r := strings.NewReplacer("~0", "~", "~1", "/", "%25", "%") split[i] = r.Replace(v) } // Resolve the local part of the URI. return resolveLocalPath(split, rootSchema, str) }
// Load loads data from Dump. If the input is not the same as the output from Dump() then it will return a error.
func (s *AtomicSequence) Load(data []byte) error { if s.initialized { return errors.New("cannot load into an initialized sequence") } vals := make(map[string]uint64) if err := json.Unmarshal(data, &vals); err != nil { return err } if val, ok := vals["current"]; !ok { return errors.New("improperly formatted data or sequence version") } else { atomic.SwapUint64(&s.current, val) } if val, ok := vals["increment"]; !ok { return errors.New("improperly formatted data or sequence version") } else { atomic.SwapUint64(&s.increment, val) } if val, ok := vals["minvalue"]; !ok { return errors.New("improperly formatted data or sequence version") } else { atomic.SwapUint64(&s.minvalue, val) } if val, ok := vals["maxvalue"]; !ok { return errors.New("improperly formatted data or sequence version") } else { atomic.SwapUint64(&s.maxvalue, val) } s.initialized = true return nil }
Exports one instance of custom field data @param data_controller $data @param array $subcontext subcontext to pass to content_writer::export_data
public static function export_customfield_data(data_controller $data, array $subcontext) { $context = $data->get_context(); $exportdata = $data->to_record(); $exportdata->fieldtype = $data->get_field()->get('type'); $exportdata->fieldshortname = $data->get_field()->get('shortname'); $exportdata->fieldname = $data->get_field()->get_formatted_name(); $exportdata->timecreated = \core_privacy\local\request\transform::datetime($exportdata->timecreated); $exportdata->timemodified = \core_privacy\local\request\transform::datetime($exportdata->timemodified); unset($exportdata->contextid); // Use the "export_value" by default for the 'value' attribute, however the plugins may override it in their callback. $exportdata->value = $data->export_value(); $classname = manager::get_provider_classname_for_component('customfield_' . $data->get_field()->get('type')); if (class_exists($classname) && is_subclass_of($classname, customfield_provider::class)) { component_class_callback($classname, 'export_customfield_data', [$data, $exportdata, $subcontext]); } else { // Custom field plugin does not implement customfield_provider, just export default value. writer::with_context($context)->export_data($subcontext, $exportdata); } }
Unlock the account. :param account: Account :return:
def unlock_account(account): return Web3Provider.get_web3().personal.unlockAccount(account.address, account.password)
Set button as HTML link object <a href="">. @param string $page @param array $args @return $this
public function link($page, $args = array()) { $this->setElement('a'); $this->setAttr('href', $this->app->url($page, $args)); return $this; }
// connect connects to the SSH server, unless a AuthMethod was set with // SetAuth method, by default uses an auth method based on PublicKeysCallback, // it connects to a SSH agent, using the address stored in the SSH_AUTH_SOCK // environment var.
func (c *command) connect() error { if c.connected { return transport.ErrAlreadyConnected } if c.auth == nil { if err := c.setAuthFromEndpoint(); err != nil { return err } } var err error config, err := c.auth.ClientConfig() if err != nil { return err } overrideConfig(c.config, config) c.client, err = dial("tcp", c.getHostWithPort(), config) if err != nil { return err } c.Session, err = c.client.NewSession() if err != nil { _ = c.client.Close() return err } c.connected = true return nil }
Helper method to actually perform the subdoc get count operation.
private Observable<DocumentFragment<Lookup>> getCountIn(final String id, final LookupSpec spec, final long timeout, final TimeUnit timeUnit) { return Observable.defer(new Func0<Observable<DocumentFragment<Lookup>>>() { @Override public Observable<DocumentFragment<Lookup>> call() { final SubGetCountRequest request = new SubGetCountRequest(id, spec.path(), bucketName); request.xattr(spec.xattr()); request.accessDeleted(accessDeleted); addRequestSpan(environment, request, "subdoc_count"); return applyTimeout(deferAndWatch(new Func1<Subscriber, Observable<SimpleSubdocResponse>>() { @Override public Observable<SimpleSubdocResponse> call(Subscriber s) { request.subscriber(s); return core.send(request); } }).map(new Func1<SimpleSubdocResponse, DocumentFragment<Lookup>>() { @Override public DocumentFragment<Lookup> call(SimpleSubdocResponse response) { try { if (response.status().isSuccess()) { try { long count = subdocumentTranscoder.decode(response.content(), Long.class); SubdocOperationResult<Lookup> single = SubdocOperationResult .createResult(spec.path(), Lookup.GET_COUNT, response.status(), count); return new DocumentFragment<Lookup>(id, response.cas(), response.mutationToken(), Collections.singletonList(single)); } finally { if (response.content() != null) { response.content().release(); } } } else { if (response.content() != null && response.content().refCnt() > 0) { response.content().release(); } if (response.status() == ResponseStatus.SUBDOC_PATH_NOT_FOUND) { SubdocOperationResult<Lookup> single = SubdocOperationResult .createResult(spec.path(), Lookup.GET_COUNT, response.status(), null); return new DocumentFragment<Lookup>(id, response.cas(), response.mutationToken(), Collections.singletonList(single)); } else { throw SubdocHelper.commonSubdocErrors(response.status(), id, spec.path()); } } } finally { if (environment.operationTracingEnabled()) { environment.tracer().scopeManager() .activate(response.request().span(), true) .close(); } } } }), request, environment, timeout, timeUnit); } }); }
The method prints the structure of all meta_signal-notifications as log-messages.
def observe_meta_signal_changes(self, changed_model, prop_name, info): " self.logger.info(NotificationOverview(info))
Clear element ID list in cache
protected function clearIDList() { $arCacheTags = $this->getCacheTagList(); $sCacheKey = $this->getCacheKey(); CCache::clear($arCacheTags, $sCacheKey); }
Gets a Site Role by his Id. @param mixed $nb_site_role A CNabuDataObject containing a field named nb_role_id or a valid Id. @return CNabuSiteRole|bool Returns the Site Role instance if exists or false if not.
public function getSiteRole($nb_site_role) { if (is_numeric($nb_role_id = nb_getMixedValue($nb_site_role, NABU_ROLE_FIELD_ID))) { $retval = $this->getSiteRoles()->getItem($nb_role_id); } else { $retval = false; } return $retval; }
Move partition to under-loaded replication-group if possible.
def move_partition_replica(self, under_loaded_rg, eligible_partition): """""" # Evaluate possible source and destination-broker source_broker, dest_broker = self._get_eligible_broker_pair( under_loaded_rg, eligible_partition, ) if source_broker and dest_broker: self.log.debug( 'Moving partition {p_name} from broker {source_broker} to ' 'replication-group:broker {rg_dest}:{dest_broker}'.format( p_name=eligible_partition.name, source_broker=source_broker.id, dest_broker=dest_broker.id, rg_dest=under_loaded_rg.id, ), ) # Move partition if eligible brokers found source_broker.move_partition(eligible_partition, dest_broker)
Set the value of Hash / hash @param $value string @return User
public function setHash(string $value) : User { if ($this->data['hash'] !== $value) { $this->data['hash'] = $value; $this->setModified('hash'); } return $this; }
// Create the next block to propose and return it. // We really only need to return the parts, but the block // is returned for convenience so we can log the proposal block. // Returns nil block upon error. // NOTE: keep it side-effect free for clarity.
func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) { var commit *types.Commit if cs.Height == 1 { // We're creating a proposal for the first block. // The commit is empty, but not nil. commit = types.NewCommit(types.BlockID{}, nil) } else if cs.LastCommit.HasTwoThirdsMajority() { // Make the commit from LastCommit commit = cs.LastCommit.MakeCommit() } else { // This shouldn't happen. cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block.") return } proposerAddr := cs.privValidator.GetPubKey().Address() return cs.blockExec.CreateProposalBlock(cs.Height, cs.state, commit, proposerAddr) }
Write an item to the cache for a given number of minutes. @param string $key @param mixed $value @param int $minutes
public function put($key, $value, $minutes) { $this->forever($key, $value); $this->redis->expire($key, $minutes * 60); }
Component factory. Delegates the creation of components to a createComponent<Name> method. @param string $name
protected function createComponent($name): ?IComponent { $method = 'createComponent'.ucfirst($name); if (method_exists($this, $method)) { $this->checkRequirements(self::getReflection()->getMethod($method)); } return parent::createComponent($name); }
get schema info @param Request $request request @return Response
public function schemaAction(Request $request) { $api = $this->decideApiAndEndpoint($request->getUri()); $this->registerProxySources($api['apiName']); $this->apiLoader->addOptions($api); $schema = $this->apiLoader->getEndpointSchema(urldecode($api['endpoint'])); $schema = $this->transformationHandler->transformSchema( $api['apiName'], $api['endpoint'], $schema, clone $schema ); $response = new Response(json_encode($schema), 200); $response->headers->set('Content-Type', 'application/json'); return $this->templating->renderResponse( 'GravitonCoreBundle:Main:index.json.twig', array ('response' => $response->getContent()), $response ); }
// Run all jobs with delay seconds
func (s *Scheduler) RunAllwithDelay(d int) { for i := 0; i < s.size; i++ { s.jobs[i].run() time.Sleep(time.Duration(d)) } }
Get the string representation of the full path name @param parent the parent path @return the full path in string
final public String getFullName(final String parent) { if (isEmptyLocalName()) { return parent; } StringBuilder fullName = new StringBuilder(parent); if (!parent.endsWith(Path.SEPARATOR)) { fullName.append(Path.SEPARATOR); } fullName.append(getLocalName()); return fullName.toString(); }
Extracts all files from the "master" language and takes them as translation groups. @param string $lang @return void
private function getTranslationGroups($lang = 'en'): void { $dir = resource_path('lang/'. $lang . '/'); $files = array_diff(scandir($dir), array('..', '.')); foreach($files as $index => $filename){ $groupname = str_replace(".php", "", $filename); $this->updateTranslationGroups($groupname); } }
Check if a route is localized in a given language @param string $name @param string $lang @return bool
function isLocalized($name,$lang=NULL) { if (!isset($lang)) $lang=$this->current; return !$this->isGlobal($name) && array_key_exists($name,$this->_aliases) && (!isset($this->rules[$lang][$name]) || $this->rules[$lang][$name]!==FALSE); }
Apply the include and exclude filters to those files in *unmatched*, moving those that are included, but not excluded, into the *matched* set. Both *matched* and *unmatched* are sets of unqualified file names.
def match_files(self, matched, unmatched): """""" for pattern in self.iter(): pattern.match_files(matched, unmatched) if not unmatched: # Optimization: If we have matched all files already # simply return at this point - nothing else to do break
// NewOTP takes a new key, a starting time, a step, the number of // digits of output (typically 6 or 8) and the hash algorithm to // use, and builds a new OTP.
func NewTOTP(key []byte, start uint64, step uint64, digits int, algo crypto.Hash) *TOTP { h := hashFromAlgo(algo) if h == nil { return nil } return &TOTP{ OATH: &OATH{ key: key, counter: start, size: digits, hash: h, algo: algo, }, step: step, } }
返回对应的termin root path(不依赖对应的config信息)
public static String getTerminRoot(Long channelId, Long pipelineId) { // 根据channelId , pipelineId构造path return MessageFormat.format(ArbitrateConstants.NODE_TERMIN_ROOT, String.valueOf(channelId), String.valueOf(pipelineId)); }
Parses a Disgenet file ad the one that can be downloaded from http://www.disgenet.org/ds/DisGeNET/results/all_gene_disease_associations.tar.gz and writes corresponding json objects.
public void parse() { Map<String, Disgenet> disgenetMap = new HashMap<>(); BufferedReader reader; try { // Disgenet file is usually downloaded as a .tar.gz file if (disgenetFilePath.toFile().getName().endsWith("tar.gz")) { TarArchiveInputStream tarInput = new TarArchiveInputStream( new GzipCompressorInputStream(new FileInputStream(disgenetFilePath.toFile()))); // TarArchiveEntry currentEntry = tarInput.getNextTarEntry(); // BufferedReader br = null; reader = new BufferedReader(new InputStreamReader(tarInput)); // Read directly from tarInput } else { reader = FileUtils.newBufferedReader(disgenetFilePath); } // if (disgenetFilePath.toFile().getName().endsWith("txt.gz")) { // reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(disgenetFilePath.toFile())))); // } else { // reader = Files.newBufferedReader(disgenetFilePath, Charset.defaultCharset()); // } logger.info("Parsing Disgenet file " + disgenetFilePath + " ..."); // first line is the header -> ignore it reader.readLine(); long processedDisgenetLines = fillDisgenetMap(disgenetMap, reader); logger.info("Serializing parsed variants ..."); Collection<Disgenet> allDisgenetRecords = disgenetMap.values(); for (Disgenet disGeNetRecord : allDisgenetRecords) { serializer.serialize(disGeNetRecord); } logger.info("Done"); this.printSummary(processedDisgenetLines, allDisgenetRecords.size()); } catch (FileNotFoundException e) { logger.error("Disgenet file " + disgenetFilePath + " not found"); } catch (IOException e) { logger.error("Error reading Disgenet file " + disgenetFilePath + ": " + e.getMessage()); } }
@param $postId @param bool $form @return Response
public function addCommentFormAction($postId, $form = false) { $action = $this->container->get(CreateCommentFormAction::class); return $action($postId, $form); }
// State returns the monitor status.
func (nm *NodeMonitor) State() *models.MonitorStatus { nm.Mutex.RLock() state := nm.state nm.Mutex.RUnlock() return state }
Solve A*X = b @param b A column vector with as many rows as A. @return X so that L*L^T*X = b @exception IllegalArgumentException Matrix row dimensions must agree. @exception RuntimeException Matrix is not symmetric positive definite.
public double[] solve(double[] b) { if(b.length != L.length) { throw new IllegalArgumentException(ERR_MATRIX_DIMENSIONS); } if(!isspd) { throw new ArithmeticException(ERR_MATRIX_NOT_SPD); } // Work on a copy! return solveLtransposed(solveLInplace(copy(b))); }
Get all running (unfinished) flows from database. {@inheritDoc}
@Override public List<ExecutableFlow> getRunningFlows() { final ArrayList<ExecutableFlow> flows = new ArrayList<>(); try { getFlowsHelper(flows, this.executorLoader.fetchUnfinishedFlows().values()); } catch (final ExecutorManagerException e) { logger.error("Failed to get running flows.", e); } return flows; }
Checks whether there is already an existing pending/in-progress data request for a user for a given request type. @param int $userid The user ID. @param int $type The request type. @return bool @throws coding_exception @throws dml_exception
public static function has_ongoing_request($userid, $type) { global $DB; // Check if the user already has an incomplete data request of the same type. $nonpendingstatuses = [ self::DATAREQUEST_STATUS_COMPLETE, self::DATAREQUEST_STATUS_CANCELLED, self::DATAREQUEST_STATUS_REJECTED, self::DATAREQUEST_STATUS_DOWNLOAD_READY, self::DATAREQUEST_STATUS_EXPIRED, self::DATAREQUEST_STATUS_DELETED, ]; list($insql, $inparams) = $DB->get_in_or_equal($nonpendingstatuses, SQL_PARAMS_NAMED, 'st', false); $select = "type = :type AND userid = :userid AND status {$insql}"; $params = array_merge([ 'type' => $type, 'userid' => $userid ], $inparams); return data_request::record_exists_select($select, $params); }
// Prev returns the previous Page relative to the given Page in // this weighted page set.
func (wp WeightedPages) Prev(cur Page) Page { for x, c := range wp { if c.Page == cur { if x == 0 { return wp[len(wp)-1].Page } return wp[x-1].Page } } return nil }
Get available locales @param string|null|true $domain If provided, locales for the given domain will be returned. If true, then the current state domain will be used (if in domain mode). @return ArrayList
public static function getLocales($domain = null) { // Optionally filter by domain $domainObj = Domain::getByDomain($domain); if ($domainObj) { return $domainObj->getLocales(); } return Locale::getCached(); }
>>> p = Preso() >>> z = p.to_file('/tmp/foo.odp') >>> sorted(z.ls('/')) ['META-INF/manifest.xml', 'content.xml', 'meta.xml', 'mimetype', 'settings.xml', 'styles.xml']
def to_file(self, filename=None, write_style=True): out = zipwrap.Zippier(filename, "w") out.write("mimetype", self.mime_type) for p in self._pictures: out.write("Pictures/%s" % p.internal_name, p.get_data()) out.write("content.xml", self.to_xml()) if write_style: out.write("styles.xml", self.styles_xml()) out.write("meta.xml", self.meta_xml()) out.write("settings.xml", self.settings_xml()) out.write("META-INF/manifest.xml", self.manifest_xml(out)) return out
TODO @param $config @return bool
public function save($config) { if (!file_put_contents($this->filename, Yaml::dump($config))) { return false; } return true; }
A decorator for flags classes to forbid declaring flags with overlapping bits.
def unique_bits(flags_class): flags_class = unique(flags_class) other_bits = 0 for name, member in flags_class.__members_without_aliases__.items(): bits = int(member) if other_bits & bits: for other_name, other_member in flags_class.__members_without_aliases__.items(): if int(other_member) & bits: raise ValueError("%r: '%s' and '%s' have overlapping bits" % (flags_class, other_name, name)) else: other_bits |= bits
Handles the optional labelling of the plot with relevant quantities Args: plt (plt): Plot of the locpot vs c axis label_fontsize (float): Fontsize of labels Returns Labelled plt
def get_labels(self, plt, label_fontsize=10): # center of vacuum and bulk region if len(self.slab_regions) > 1: label_in_vac = (self.slab_regions[0][1] + self.slab_regions[1][0])/2 if abs(self.slab_regions[0][0]-self.slab_regions[0][1]) > \ abs(self.slab_regions[1][0]-self.slab_regions[1][1]): label_in_bulk = self.slab_regions[0][1]/2 else: label_in_bulk = (self.slab_regions[1][1] + self.slab_regions[1][0]) / 2 else: label_in_bulk = (self.slab_regions[0][0] + self.slab_regions[0][1])/2 if self.slab_regions[0][0] > 1-self.slab_regions[0][1]: label_in_vac = self.slab_regions[0][0] / 2 else: label_in_vac = (1 + self.slab_regions[0][1]) / 2 plt.plot([0, 1], [self.vacuum_locpot]*2, 'b--', zorder=-5, linewidth=1) xy = [label_in_bulk, self.vacuum_locpot+self.ave_locpot*0.05] plt.annotate(r"$V_{vac}=%.2f$" %(self.vacuum_locpot), xy=xy, xytext=xy, color='b', fontsize=label_fontsize) # label the fermi energy plt.plot([0, 1], [self.efermi]*2, 'g--', zorder=-5, linewidth=3) xy = [label_in_bulk, self.efermi+self.ave_locpot*0.05] plt.annotate(r"$E_F=%.2f$" %(self.efermi), xytext=xy, xy=xy, fontsize=label_fontsize, color='g') # label the bulk-like locpot plt.plot([0, 1], [self.ave_bulk_p]*2, 'r--', linewidth=1., zorder=-1) xy = [label_in_vac, self.ave_bulk_p + self.ave_locpot * 0.05] plt.annotate(r"$V^{interior}_{slab}=%.2f$" % (self.ave_bulk_p), xy=xy, xytext=xy, color='r', fontsize=label_fontsize) # label the work function as a barrier plt.plot([label_in_vac]*2, [self.efermi, self.vacuum_locpot], 'k--', zorder=-5, linewidth=2) xy = [label_in_vac, self.efermi + self.ave_locpot * 0.05] plt.annotate(r"$\Phi=%.2f$" %(self.work_function), xy=xy, xytext=xy, fontsize=label_fontsize) return plt
is the host any of the registered URLs for this website?
public static function isHostKnownAliasHost($urlHost, $idSite) { $websiteData = Cache::getCacheWebsiteAttributes($idSite); if (isset($websiteData['hosts'])) { $canonicalHosts = array(); foreach ($websiteData['hosts'] as $host) { $canonicalHosts[] = self::toCanonicalHost($host); } $canonicalHost = self::toCanonicalHost($urlHost); if (in_array($canonicalHost, $canonicalHosts)) { return true; } } return false; }
List server id and scripts file name
function list(scriptModule, agent, msg, cb) { const servers = []; const scripts = []; const idMap = agent.idMap; for (const sid in idMap) { if (idMap.hasOwnProperty(sid)) { servers.push(sid); } } fs.readdir(scriptModule.root, (err, filenames) => { if (err) { filenames = []; } for (let i = 0, l = filenames.length; i < l; i++) { scripts.push(filenames[i]); } cb(null, { servers: servers, scripts: scripts }); }); }
Updates the commerce wish list item in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. @param commerceWishListItem the commerce wish list item @return the commerce wish list item that was updated
public static com.liferay.commerce.wish.list.model.CommerceWishListItem updateCommerceWishListItem( com.liferay.commerce.wish.list.model.CommerceWishListItem commerceWishListItem) { return getService().updateCommerceWishListItem(commerceWishListItem); }
* This method is used to clear KeyStore configurations when the entire config is being reloaded. *
public void clearKSMap() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Clearing keystore maps"); synchronized (keyStoreMap) { keyStoreMap.clear(); } }
// List runs the list action.
func (c *SpaceController) List(ctx *app.ListSpaceContext) error { _, err := login.ContextIdentity(ctx) if err != nil { return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error())) } offset, limit := computePagingLimits(ctx.PageOffset, ctx.PageLimit) var response app.SpaceList txnErr := application.Transactional(c.db, func(appl application.Application) error { spaces, cnt, err := appl.Spaces().List(ctx.Context, &offset, &limit) if err != nil { return err } entityErr := ctx.ConditionalEntities(spaces, c.config.GetCacheControlSpaces, func() error { count := int(cnt) spaceData, err := ConvertSpacesFromModel(ctx.Request, spaces, IncludeBacklogTotalCount(ctx.Context, c.db)) if err != nil { return err } response = app.SpaceList{ Links: &app.PagingLinks{}, Meta: &app.SpaceListMeta{TotalCount: count}, Data: spaceData, } setPagingLinks(response.Links, buildAbsoluteURL(ctx.Request), len(spaces), offset, limit, count) return nil }) if entityErr != nil { return entityErr } return nil }) if txnErr != nil { return jsonapi.JSONErrorResponse(ctx, txnErr) } return ctx.OK(&response) }
// add inserts or updates "r" in the cache for the replica with the key "r.Key".
func (c *replicationLagCache) add(r replicationLagRecord) { if !r.Up { // Tablet is down. Do no longer track it. delete(c.entries, r.Key) delete(c.ignoredSlowReplicasInARow, r.Key) return } entry, ok := c.entries[r.Key] if !ok { entry = newReplicationLagHistory(c.historyCapacityPerReplica) c.entries[r.Key] = entry } entry.add(r) }
Run any git command, like "status" or "checkout -b mybranch origin/mybranch" @throws RuntimeException @param string $commandString @return string $output
public function git($commandString) { // clean commands that begin with "git " $commandString = preg_replace('/^git\s/', '', $commandString); $commandString = $this->options['git_executable'].' '.$commandString; $command = new $this->options['command_class']($this->dir, $commandString, $this->debug); return $command->run(); }
can lead to classcastexception if comparator is not of the right type
@SuppressWarnings("unchecked") public <T> void sort(Arr arr, Comparator<T> c) { int l = arr.getLength(); Object[] objs = new Object[l]; for (int i=0; i<l; i++) { objs[i] = arr.get(i); } Arrays.sort((T[])objs, c); for (int i=0; i<l; i++) { arr.put(i, objs[i]); } }
Create a new cell at the specified coordinate @param string $pCoordinate Coordinate of the cell @return PHPExcel_Cell Cell that was created
private function _createNewCell($pCoordinate) { $cell = $this->_cellCollection->addCacheData( $pCoordinate, new PHPExcel_Cell( NULL, PHPExcel_Cell_DataType::TYPE_NULL, $this ) ); $this->_cellCollectionIsSorted = false; // Coordinates $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($aCoordinates[0])) $this->_cachedHighestColumn = $aCoordinates[0]; $this->_cachedHighestRow = max($this->_cachedHighestRow, $aCoordinates[1]); // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist $rowDimension = $this->getRowDimension($aCoordinates[1], FALSE); $columnDimension = $this->getColumnDimension($aCoordinates[0], FALSE); if ($rowDimension !== NULL && $rowDimension->getXfIndex() > 0) { // then there is a row dimension with explicit style, assign it to the cell $cell->setXfIndex($rowDimension->getXfIndex()); } elseif ($columnDimension !== NULL && $columnDimension->getXfIndex() > 0) { // then there is a column dimension, assign it to the cell $cell->setXfIndex($columnDimension->getXfIndex()); } return $cell; }
Determine if the browser is among the custom browser rules or not. Rules are checked in the order they were added. @access protected @return boolean Returns true if we found the browser we were looking for in the custom rules, false otherwise.
protected function checkBrowserCustom() { foreach ($this->_customBrowserDetection as $browserName => $customBrowser) { $uaNameToLookFor = $customBrowser['uaNameToLookFor']; $isMobile = $customBrowser['isMobile']; $isRobot = $customBrowser['isRobot']; $separator = $customBrowser['separator']; $uaNameFindWords = $customBrowser['uaNameFindWords']; if ($this->checkSimpleBrowserUA($uaNameToLookFor, $this->_agent, $browserName, $isMobile, $isRobot, $separator, $uaNameFindWords)) { return true; } } return false; }
Find related object on the database and updates it with attributes in self, if it didn't find it on database it creates a new one.
def convert(attribute="id") klass = persistence_class object = klass.where(attribute.to_sym => self.send(attribute)).first object ||= persistence_class.new attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) } attributes.delete(:id) object.attributes = attributes object.save self.id = object.id object end
Finish establishing section Wrap up title node, but stick in the section node. Add the section names based on all the text nodes added to the title.
def depart_heading(self, _): assert isinstance(self.current_node, nodes.title) # The title node has a tree of text nodes, use the whole thing to # determine the section id and names text = self.current_node.astext() if self.translate_section_name: text = self.translate_section_name(text) name = nodes.fully_normalize_name(text) section = self.current_node.parent section['names'].append(name) self.document.note_implicit_target(section, section) self.current_node = section
верификация номер телефона @return bool @throws Exception
public function verifyPhone(): bool { $phone = new UserMetaPhone($this->notification_phone); $phone->verifyPhone(); $this->notification_phone = $phone; return $this->updateModel(); }
Expert users can override this method for more complete control over the execution of the Mapper. @param context @throws IOException
public void run(Context context) throws IOException, InterruptedException { setup(context); while (context.nextKeyValue()) { map(context.getCurrentKey(), context.getCurrentValue(), context); } cleanup(context); }
Add a response to the list. @param int $key @param array|null $response
public function addResponse($key, array $response) { $originalRequest = isset($this->request[$key]) ? $this->request[$key] : null; $responseBody = isset($response['body']) ? $response['body'] : null; $responseError = isset($response['error']) ? $response['error'] : null; $responseMethod = isset($response['method']) ? $response['method'] : null; $this->responses[$key] = new Response($originalRequest, $responseBody, $responseError, $responseMethod); }
Copy temporary project data to persistent storage. @param string[] $with @throws ReadException
private function updateStorage($with = []) { $data = array_merge($this->data, $with); $this->fs->create($this->fsPath, json_encode($data)); }
// drawCondFmtCellIs provides a function to create conditional formatting rule // for cell value (include between, not between, equal, not equal, greater // than and less than) by given priority, criteria type and format settings.
func drawCondFmtCellIs(p int, ct string, format *formatConditional) *xlsxCfRule { c := &xlsxCfRule{ Priority: p + 1, Type: validType[format.Type], Operator: ct, DxfID: &format.Format, } // "between" and "not between" criteria require 2 values. _, ok := map[string]bool{"between": true, "notBetween": true}[ct] if ok { c.Formula = append(c.Formula, format.Minimum) c.Formula = append(c.Formula, format.Maximum) } _, ok = map[string]bool{"equal": true, "notEqual": true, "greaterThan": true, "lessThan": true}[ct] if ok { c.Formula = append(c.Formula, format.Value) } return c }
Trims every string in the specified strings array. @param strings the specified strings array, returns {@code null} if the specified strings is {@code null} @return a trimmed strings array
public static String[] trimAll(final String[] strings) { if (null == strings) { return null; } return Arrays.stream(strings).map(StringUtils::trim).toArray(size -> new String[size]); }
Sobel method to generate bump map from a height map @param input - A height map @return bump map
@Override public ImageSource apply(ImageSource input) { int w = input.getWidth(); int h = input.getHeight(); MatrixSource output = new MatrixSource(input); Vector3 n = new Vector3(0, 0, 1); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (x < border || x == w - border || y < border || y == h - border) { output.setRGB(x, y, VectorHelper.Z_NORMAL); continue; } float s0 = input.getR(x - 1, y + 1); float s1 = input.getR(x, y + 1); float s2 = input.getR(x + 1, y + 1); float s3 = input.getR(x - 1, y); float s5 = input.getR(x + 1, y); float s6 = input.getR(x - 1, y - 1); float s7 = input.getR(x, y - 1); float s8 = input.getR(x + 1, y - 1); float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6); float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2); n.set(nx, ny, scale); n.nor(); int rgb = VectorHelper.vectorToColor(n); output.setRGB(x, y, rgb); } } return new MatrixSource(output); }
Modify the inner parameters of the Kepler propagator in order to place the spacecraft in the right Sphere of Influence
def _change_soi(self, body): if body == self.central: self.bodies = [self.central] self.step = self.central_step self.active = self.central.name self.frame = self.central.name else: soi = self.SOI[body.name] self.bodies = [body] self.step = self.alt_step self.active = body.name self.frame = soi.frame
Creates the signed license at the defined output path @throws BuildException @return void
protected function generateLicense() { $command = $this->prepareSignCommand() . ' 2>&1'; $this->log('Creating license at ' . $this->outputFile); $this->log('Running: ' . $command, Project::MSG_VERBOSE); $tmp = exec($command, $output, $return_var); // Check for exit value 1. Zendenc_sign command for some reason // returns 0 in case of failure and 1 in case of success... if ($return_var !== 1) { throw new BuildException("Creating license failed. \n\nZendenc_sign msg:\n" . implode( "\n", $output ) . "\n\n"); } }
Indicates whether activity is for compensation. @return true if this activity is for compensation.
public boolean isCompensationHandler() { Boolean isForCompensation = (Boolean) getProperty(BpmnParse.PROPERTYNAME_IS_FOR_COMPENSATION); return Boolean.TRUE.equals(isForCompensation); }
@param array $elements @return \marvin255\serviform\interfaces\HasChildren
public function setElements(array $elements) { $this->elements = []; foreach ($elements as $name => $element) { $this->setElement($name, $element); } return $this; }
Sets which partial view script to use for rendering tweets @param string|array $partial @return \UthandoTwitter\View\TweetFeed
public function setPartial($partial) { if (null === $partial || is_string($partial) || is_array($partial)) { $this->partial = $partial; } return $this; }
Add migrations to be applied. Args: migrations: a list of migrations to add of the form [(app, migration_name), ...] Raises: MigrationSessionError if called on a closed MigrationSession
def add_migrations(self, migrations): if self.__closed: raise MigrationSessionError("Can't change applied session") self._to_apply.extend(migrations)
Returns base basket price for payment cost calculations. Price depends on payment setup (payment administration) @param \OxidEsales\Eshop\Application\Model\Basket $oBasket oxBasket object @return double
public function getBaseBasketPriceForPaymentCostCalc($oBasket) { $dBasketPrice = 0; $iRules = $this->oxpayments__oxaddsumrules->value; // products brutto price if (!$iRules || ($iRules & self::PAYMENT_ADDSUMRULE_ALLGOODS)) { $dBasketPrice += $oBasket->getProductsPrice()->getSum($oBasket->isCalculationModeNetto()); } // discounts if ((!$iRules || ($iRules & self::PAYMENT_ADDSUMRULE_DISCOUNTS)) && ($oCosts = $oBasket->getTotalDiscount()) ) { $dBasketPrice -= $oCosts->getPrice(); } // vouchers if (!$iRules || ($iRules & self::PAYMENT_ADDSUMRULE_VOUCHERS)) { $dBasketPrice -= $oBasket->getVoucherDiscValue(); } // delivery if ((!$iRules || ($iRules & self::PAYMENT_ADDSUMRULE_SHIPCOSTS)) && ($oCosts = $oBasket->getCosts('oxdelivery')) ) { if ($oBasket->isCalculationModeNetto()) { $dBasketPrice += $oCosts->getNettoPrice(); } else { $dBasketPrice += $oCosts->getBruttoPrice(); } } // wrapping if (($iRules & self::PAYMENT_ADDSUMRULE_GIFTS) && ($oCosts = $oBasket->getCosts('oxwrapping')) ) { if ($oBasket->isCalculationModeNetto()) { $dBasketPrice += $oCosts->getNettoPrice(); } else { $dBasketPrice += $oCosts->getBruttoPrice(); } } // gift card if (($iRules & self::PAYMENT_ADDSUMRULE_GIFTS) && ($oCosts = $oBasket->getCosts('oxgiftcard')) ) { if ($oBasket->isCalculationModeNetto()) { $dBasketPrice += $oCosts->getNettoPrice(); } else { $dBasketPrice += $oCosts->getBruttoPrice(); } } return $dBasketPrice; }
***********************************************************************************
@Override public boolean removeArc(int x, int y, ICause cause) throws ContradictionException { assert cause != null; if (LB.arcExists(x, y)) { this.contradiction(cause, "remove mandatory arc " + x + "->" + y); return false; } if (UB.removeArc(x, y)) { if (reactOnModification) { delta.add(x, GraphDelta.AR_TAIL, cause); delta.add(y, GraphDelta.AR_HEAD, cause); } GraphEventType e = GraphEventType.REMOVE_ARC; notifyPropagators(e, cause); return true; } return false; }
// GetAvatarURL gets the user's avatar URL. See http://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-client-r0-profile-userid-avatar-url
func (cli *Client) GetAvatarURL() (url string, err error) { urlPath := cli.BuildURL("profile", cli.UserID, "avatar_url") s := struct { AvatarURL string `json:"avatar_url"` }{} _, err = cli.MakeRequest("GET", urlPath, nil, &s) if err != nil { return "", err } return s.AvatarURL, nil }
// ParseToRawMap takes the filename as a string and returns a RawMap.
func ParseToRawMap(fileName string) (cfg RawMap, err error) { var file *os.File cfg = make(RawMap, 0) file, err = os.Open(fileName) if err != nil { return } defer file.Close() scanner := bufio.NewScanner(file) var currentSection string for scanner.Scan() { line := scanner.Text() if commentLine.MatchString(line) { continue } else if blankLine.MatchString(line) { continue } else if configSection.MatchString(line) { section := configSection.ReplaceAllString(line, "$1") if !cfg.SectionInConfig(section) { cfg[section] = make(map[string]string, 0) } currentSection = section } else if configLine.MatchString(line) { regex := configLine if quotedConfigLine.MatchString(line) { regex = quotedConfigLine } if currentSection == "" { currentSection = defaultSection if !cfg.SectionInConfig(currentSection) { cfg[currentSection] = make(map[string]string, 0) } } key := regex.ReplaceAllString(line, "$1") val := regex.ReplaceAllString(line, "$2") cfg[currentSection][key] = val } else { err = fmt.Errorf("invalid config file") break } } return }
Loops through the output buffer, flushing each, before emitting the response. @param int|null $maxBufferLevel Flush up to this buffer level. @return void
protected function flush($maxBufferLevel = null) { if (null === $maxBufferLevel) { $maxBufferLevel = ob_get_level(); } while (ob_get_level() > $maxBufferLevel) { ob_end_flush(); } }
Scalar multiplies each item with c @param c
public void scalarMultiply(double c) { int m = rows; int n = cols; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { consumer.set(i, j, c * supplier.get(i, j)); } } }
allocateSpace().
private void freeAllocatedSpace(java.util.Collection sortedFreeSpaceList) { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, "freeAllocatedSpace", new Object[] { new Integer(sortedFreeSpaceList.size()), new Long(freeSpaceByLength.size()) }); // Remove from the head of the sorted set until we find the first non-negative // address - indicating that the storage was allocated java.util.Iterator listIterator = sortedFreeSpaceList.iterator(); Directory.StoreArea currentArea = null; while (listIterator.hasNext()) { currentArea = (Directory.StoreArea) listIterator.next(); if (currentArea.byteAddress > 0) break; } // Did we find at least one to merge? if (currentArea != null) { // We now have a pointer to the first store area in the sorted list // that needs to be merged into the free space map. // We iterate through the free space map (which is also in order) // merging the entries in, and moving our pointer forwards. FreeSpace spaceEntry = freeSpaceByAddressHead; FreeSpace previousEntry = null; do { // If spaceEntry is null then we have reached the end of the list. // We handle this case first, because we can avoid null-checks in // other branches. // The same logic is used to handle the case where we have moved // past the point in the address-sorted free space list where this // entry would be merged, and did not find any existing entries // to merge it with. Merging would have been performed in branches // below on an earlier pass round the loop if it was possible (as // we would have looked at the entry that is now spaceEntry as // spaceEntry.next in the below branches). if (spaceEntry == null || // Tail of list reached spaceEntry.address > currentArea.byteAddress // Moved past insertion point without merge ) { // Create a new entry, unless this is a zero-sized entry if (currentArea.length > 0) { FreeSpace newSpaceEntry = new FreeSpace(currentArea.byteAddress, currentArea.length); // Link it in behind the current entry newSpaceEntry.next = spaceEntry; if (previousEntry != null) { previousEntry.next = newSpaceEntry; } else { // We are the new head freeSpaceByAddressHead = newSpaceEntry; } newSpaceEntry.prev = previousEntry; if (spaceEntry != null) { spaceEntry.prev = newSpaceEntry; } // Add our extended entry into the length-sorted list freeSpaceByLength.add(newSpaceEntry); // Debug freespace list // if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled()) trace.debug(this, cclass, methodName, "ADD to freespace list"); // Keep track of the maximum free space count as a statistic if (gatherStatistics && freeSpaceByLength.size() > maxFreeSpaceCount) maxFreeSpaceCount = freeSpaceByLength.size(); // As we've added a new entry before the current on, we should use it next time round spaceEntry = newSpaceEntry; // Previous entry stayed the same - as we've inserted without moving forwards } // Regardless of whether we added an entry, move onto the next store area and // go back round the loop. if (listIterator.hasNext()) { currentArea = (Directory.StoreArea) listIterator.next(); } else currentArea = null; // We've run out of entries to merge } // Can our current store entry be merged with the current free space entry. else if (spaceEntry.address + spaceEntry.length == currentArea.byteAddress) { // We can merge this entry with the one before it. // Remove from the length-sorted list and change the size freeSpaceByLength.remove(spaceEntry); spaceEntry.length += currentArea.length; // Can we also merge it with the one after it? FreeSpace nextSpaceEntry = spaceEntry.next; if (nextSpaceEntry != null && currentArea.byteAddress + currentArea.length == nextSpaceEntry.address) { // Remove the eliminated space entry from the length-sorted list freeSpaceByLength.remove(nextSpaceEntry); // Debug freespace list // if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled()) trace.debug(this, cclass, methodName, "REMOVE from freespace list"); // Make the previous one larger spaceEntry.length += nextSpaceEntry.length; // Remove the next one spaceEntry.next = nextSpaceEntry.next; if (nextSpaceEntry.next != null) { nextSpaceEntry.next.prev = spaceEntry; } } // Add our extended entry into the length-sorted list freeSpaceByLength.add(spaceEntry); // We've merged this store entry now, so move onto the next one // in the sorted list. if (listIterator.hasNext()) { currentArea = (Directory.StoreArea) listIterator.next(); } else currentArea = null; // We've run out of entries to merge // Note we do not advance our position in the free space, as the // current entry could also be of interest to the next store item. } // Can our current store entry be merged with the next free space entry // (note that the case where it merges with both is already handled). else if (spaceEntry.next != null && currentArea.byteAddress + currentArea.length == spaceEntry.next.address) { // Remove from the length-sorted list and change the size FreeSpace nextSpaceEntry = spaceEntry.next; freeSpaceByLength.remove(nextSpaceEntry); nextSpaceEntry.address = currentArea.byteAddress; nextSpaceEntry.length += currentArea.length; // Add back into the length-sorted list freeSpaceByLength.add(nextSpaceEntry); // We've merged this store entry now, so move onto the next one // in the sorted list. if (listIterator.hasNext()) { currentArea = (Directory.StoreArea) listIterator.next(); } else currentArea = null; // We've run out of entries to merge // Note we do not advance our position in the free space, as the // current entry could also be of interest to the next store item. } // Otherwise this space entry is not interesting to us, and we // can simply move onto the next one. else { previousEntry = spaceEntry; spaceEntry = spaceEntry.next; } // Although looping through the free space map, our condition for // breaking the loop is when we've run out of entries to merge. } while (currentArea != null); } if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this, cclass, "freeAllocatedSpace", new Object[] { new Long(freeSpaceByLength.size()) }); }
Aligns the structures, duplicating ca2 regardless of {@link CECPParameters.getDuplicationHint() param.getDuplicationHint}. @param ca1 @param ca2 @param cpparams @return @throws StructureException
private AFPChain alignRight(Atom[] ca1, Atom[] ca2, CECPParameters cpparams) throws StructureException { long startTime = System.currentTimeMillis(); Atom[] ca2m = StructureTools.duplicateCA2(ca2); if(debug) { System.out.format("Duplicating ca2 took %s ms\n",System.currentTimeMillis()-startTime); startTime = System.currentTimeMillis(); } // Do alignment AFPChain afpChain = super.align(ca1, ca2m,params); // since the process of creating ca2m strips the name info away, set it explicitely try { afpChain.setName2(ca2[0].getGroup().getChain().getStructure().getName()); } catch( Exception e) {} if(debug) { System.out.format("Running %dx2*%d alignment took %s ms\n",ca1.length,ca2.length,System.currentTimeMillis()-startTime); startTime = System.currentTimeMillis(); } afpChain = postProcessAlignment(afpChain, ca1, ca2m, calculator, cpparams); if(debug) { System.out.format("Finding CP point took %s ms\n",System.currentTimeMillis()-startTime); startTime = System.currentTimeMillis(); } return afpChain; }
Checks if discount should be skipped for this article in basket. Returns true if yes. @return bool
public function skipDiscounts() { // already loaded skip discounts config if ($this->_blSkipDiscounts !== null) { return $this->_blSkipDiscounts; } if ($this->oxarticles__oxskipdiscounts->value) { return true; } $this->_blSkipDiscounts = false; if (\OxidEsales\Eshop\Core\Registry::get(\OxidEsales\Eshop\Application\Model\DiscountList::class)->hasSkipDiscountCategories()) { $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(); $sO2CView = getViewName('oxobject2category', $this->getLanguage()); $sViewName = getViewName('oxcategories', $this->getLanguage()); $sSelect = "select 1 from $sO2CView as $sO2CView left join {$sViewName} on {$sViewName}.oxid = $sO2CView.oxcatnid where $sO2CView.oxobjectid=" . $oDb->quote($this->getId()) . " and {$sViewName}.oxactive = 1 and {$sViewName}.oxskipdiscounts = '1' "; $this->_blSkipDiscounts = ($oDb->getOne($sSelect) == 1); } return $this->_blSkipDiscounts; }
Returns the product of each numerical column or row. Return: A new QueryCompiler object with the product of each numerical column or row.
def prod(self, **kwargs): if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().prod(**kwargs) return self._process_sum_prod( self._build_mapreduce_func(pandas.DataFrame.prod, **kwargs), **kwargs )
Switches the corners of the Tiles between rounded and rectangular @param ROUNDED
public void setRoundedCorners(final boolean ROUNDED) { if (null == roundedCorners) { _roundedCorners = ROUNDED; fireTileEvent(REDRAW_EVENT); } else { roundedCorners.set(ROUNDED); } }
Generates control's HTML element. @return Html
public function getControl() { $control = parent::getControl(); $control->type = $this->htmlType; $control->addClass($this->htmlType); list($min, $max) = $this->extractRangeRule($this->getRules()); if ($min instanceof DateTimeInterface) { $control->min = $min->format($this->htmlFormat); } if ($max instanceof DateTimeInterface) { $control->max = $max->format($this->htmlFormat); } $value = $this->getValue(); if ($value instanceof DateTimeInterface) { $control->value = $value->format($this->htmlFormat); } return $control; }
// SetTimeoutInMinutesOverride sets the TimeoutInMinutesOverride field's value.
func (s *StartBuildInput) SetTimeoutInMinutesOverride(v int64) *StartBuildInput { s.TimeoutInMinutesOverride = &v return s }
Marshall the given parameter object.
public void marshall(MethodSnapshot methodSnapshot, ProtocolMarshaller protocolMarshaller) { if (methodSnapshot == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(methodSnapshot.getAuthorizationType(), AUTHORIZATIONTYPE_BINDING); protocolMarshaller.marshall(methodSnapshot.getApiKeyRequired(), APIKEYREQUIRED_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Fetches the metric object corresponding to the given name.
def _GetMetric(self, metric_name): """""" if metric_name in self._counter_metrics: return self._counter_metrics[metric_name] elif metric_name in self._event_metrics: return self._event_metrics[metric_name] elif metric_name in self._gauge_metrics: return self._gauge_metrics[metric_name] else: raise ValueError("Metric %s is not registered." % metric_name)
Download the specified feed item @param models\Download\Feed\DownloadFeedItem $DownloadFeedItem @return bool @throws \GuzzleHttp\Exception\GuzzleException @throws \alphayax\freebox\Exception\FreeboxApiException
public function downloadFeedItem(models\Download\Feed\DownloadFeedItem $DownloadFeedItem) { $service = sprintf(self::API_DOWNLOAD_FEEDS_ITEMS_ITEM_DOWNLOAD, $DownloadFeedItem->getFeedId(), $DownloadFeedItem->getId()); $rest = $this->callService('POST', $service, $DownloadFeedItem); return $rest->getSuccess(); }
Perform session cleanup, since the end method should always be called explicitely by the calling code, this works better than the destructor. Set close_fileobj to False so fileobj can be returned open.
def end(self, close_fileobj=True): """""" log.debug("in TftpContext.end - closing socket") self.sock.close() if close_fileobj and self.fileobj is not None and not self.fileobj.closed: log.debug("self.fileobj is open - closing") self.fileobj.close()