comment
stringlengths
16
255
code
stringlengths
52
3.87M
USAGE: color-lighten(@neutral, 50);
function getColorLightenFunction(less) { function rgba() { var rgbaFunc = less.functions.functionRegistry.get("rgba"); return rgbaFunc.apply(null, arguments); } return function (color, amount) { var baseRGB = [255, 255, 255]; var value = amount.value / 100; if (value < 0) { baseRGB = [0, 0, 0]; value = -1 * value; } return rgba( Math.round((baseRGB[0] - color.rgb[0]) * value) + color.rgb[0], Math.round((baseRGB[1] - color.rgb[1]) * value) + color.rgb[1], Math.round((baseRGB[2] - color.rgb[2]) * value) + color.rgb[2], color.alpha ); }; }
Return a label to display for a field
def get_field_label(self, field_name, field=None): label = None if field is not None: label = getattr(field, 'verbose_name', None) if label is None: label = getattr(field, 'name', None) if label is None: label = field_name return label.capitalize()
@param MockConfig $expectation @return bool
private function isExpectedScenarioState(MockConfig $expectation) { if ($expectation->getRequest()->hasScenarioState()) { $this->checkScenarioNameOrThrowException($expectation); $this->logger->debug('Checking scenario state again expectation'); $scenarioState = $this->scenarioStorage->getScenarioState( $expectation->getScenarioName() ); if (!$expectation->getRequest()->getScenarioState()->equals($scenarioState)) { return false; } } return true; }
Block Record @alias module:wallet.BlockRecord @constructor @param {Hash} hash @param {Number} height @param {Number} time
function BlockRecord(hash, height, time) { if (!(this instanceof BlockRecord)) return new BlockRecord(hash, height, time); this.hash = hash || encoding.NULL_HASH; this.height = height != null ? height : -1; this.time = time || 0; this.hashes = []; this.index = new Set(); }
Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment and message. :param dict environ: The WSGI environment dictionary for the request :param str msg: The error message
def raise_not_found(self, environ, msg): raise NotFound(response=self.rewriterapp._error_response(environ, msg))
Parses samples, specified in either a manifest or listed with --samples :param str path_to_manifest: Path to configuration file :return: Samples and their attributes as defined in the manifest :rtype: list[list]
def parse_manifest(path_to_manifest): samples = [] with open(path_to_manifest, 'r') as f: for line in f.readlines(): if not line.isspace() and not line.startswith('#'): sample = line.strip().split('\t') require(len(sample) == 3, 'Bad manifest format! ' 'Expected 3 tab separated columns, got: {}'.format(sample)) uuid, normal, tumor = sample for url in [normal, tumor]: require(urlparse(url).scheme and urlparse(url), 'Invalid URL passed for {}'.format(url)) samples.append(sample) return samples
Document height @method docHeight @return {Number} The current height of the document.
function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }
// SetKeyId sets the KeyId field's value.
func (s *StreamDescription) SetKeyId(v string) *StreamDescription { s.KeyId = &v return s }
A JSON serializable dict representation of self.
def as_dict(self): return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "operation": self.operation, "title": self.title, "xc": self.xc.as_dict(), "basis_set": self.basis_set.as_dict(), "units": self.units.as_dict(), "scf": self.scf.as_dict(), "geo": self.geo.as_dict(), "others": [k.as_dict() for k in self.other_directives]}
Приводит в порядок порядковые номера материалов раздела: удаляет дубликаты, дыры в нумерации. @internal @return void
public function fixMaterialTags() { $r = self::getDbConnection()->fetchAll('SELECT count(tag) as cnt from '.$this->materialsTable.' where idcat='.$this->prototype->id.' group by tag having cnt>1'); if (!count($r)) return; $i = 100; $r = self::getDbConnection()->query('SELECT id FROM '.$this->materialsTable.' WHERE idcat='.$this->prototype->id.' ORDER BY tag'); while ($f = $r->fetch()) { self::getDbConnection()->executeQuery('UPDATE '.$this->materialsTable.' SET tag='.$i.' WHERE id='.$f['id']); $i = $i + 100; } }
@param string|string[] $question @param string[] $choices @param string $default @param InputInterface $input @param OutputInterface $output @return string|null
private function choice($question, array $choices, $default, InputInterface $input, OutputInterface $output) { $helper = new QuestionHelper(); $result = $helper->ask($input, $output, new ChoiceQuestion( $question, $choices, $choices[$default] )); $output->writeln(''); return $result; }
/*! Returns the meta data used for storing search indeces.
function metaData( $contentObjectAttribute ) { $matrix = $contentObjectAttribute->content(); $columnsArray = $matrix->attribute( 'columns' ); $columns = $columnsArray['sequential']; $metaDataArray = array(); foreach ( $columns as $column ) { $rows = $column['rows']; foreach ( $rows as $row ) { $metaDataArray[] = array( 'id' => $column['identifier'], 'text' => $row ); } } return $metaDataArray; }
PersistenceDelegate.initialize()
protected void initialize(Class<?> type, Object oldInstance, Object newInstance, Encoder out) { // // Get the bean and associated beanInfo for the source instance // ControlBean control = (ControlBean)oldInstance; BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(control.getClass()); } catch (IntrospectionException ie) { throw new ControlException("Unable to locate BeanInfo", ie); } // // Cast the encoding stream to an XMLEncoder (only encoding supported) and then set // the stream owner to the bean being persisted // XMLEncoder xmlOut = (XMLEncoder)out; Object owner = xmlOut.getOwner(); xmlOut.setOwner(control); try { // // The default implementation of property persistence will use BeanInfo to // incrementally compare oldInstance property values to newInstance property values. // Because the bean instance PropertyMap holds only the values that have been // modified, this process can be optimized by directly writing out only the properties // found in the map. // BeanPropertyMap beanMap = control.getPropertyMap(); PropertyDescriptor [] propDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyKey pk : beanMap.getPropertyKeys()) { // // Locate the PropertyDescriptor for the modified property, and use it to write // the property value to the encoder stream // String propName = pk.getPropertyName(); boolean found = false; for (int i = 0; i < propDescriptors.length; i++) { if (propName.equals(propDescriptors[i].getName())) { found = true; // Only write the property if it is not flagged as transient Object transientVal = propDescriptors[i].getValue("transient"); if (transientVal == null || transientVal.equals(Boolean.FALSE)) { xmlOut.writeStatement( new Statement(oldInstance, propDescriptors[i].getWriteMethod().getName(), new Object [] {beanMap.getProperty(pk)})); } } } if (found == false) { throw new ControlException("Unknown property in bean PropertyMap: " + pk); } } // // Get the bean context associated with the bean, and persist any nested controls // ControlBeanContext cbc = control.getControlBeanContext(); if (cbc.size() != 0) { xmlOut.setPersistenceDelegate(ControlBeanContext.class, new ContextPersistenceDelegate()); Iterator nestedIter = cbc.iterator(); while (nestedIter.hasNext()) { Object bean = nestedIter.next(); if (bean instanceof ControlBean) { xmlOut.writeStatement( new Statement(cbc, "add", new Object [] { bean } )); } } } // // Restore any listeners associated with the control // EventSetDescriptor [] eventSetDescriptors = beanInfo.getEventSetDescriptors(); for (int i = 0; i < eventSetDescriptors.length; i++) { EventSetDescriptor esd = eventSetDescriptors[i]; Method listenersMethod = esd.getGetListenerMethod(); String addListenerName = esd.getAddListenerMethod().getName(); if (listenersMethod != null) { // // Get the list of listeners, and then add statements to incrementally // add them in the same order // try { Object [] lstnrs = (Object [])listenersMethod.invoke(control, new Object []{}); for (int j = 0; j < lstnrs.length; j++) { // // If this is a generated EventAdaptor class, then set the delegate // explicitly // if (lstnrs[j] instanceof EventAdaptor) xmlOut.setPersistenceDelegate(lstnrs[j].getClass(), new AdaptorPersistenceDelegate()); xmlOut.writeStatement( new Statement(control, addListenerName, new Object [] {lstnrs[j]})); } } catch (Exception iae) { throw new ControlException("Unable to initialize listeners", iae); } } } // // See if the control holds an implementation instance, if so, we need to include // it (and any nested controls or state) in the encoding stream // Object impl = control.getImplementation(); if (impl != null) { // // Set the persistence delegate for the impl class to the Impl delegate, // set the current stream owner to the bean, and then write the implementation // Class implClass = impl.getClass(); if (xmlOut.getPersistenceDelegate(implClass) instanceof DefaultPersistenceDelegate) xmlOut.setPersistenceDelegate(implClass, new ImplPersistenceDelegate()); // // HACK: This bit of hackery pushes the impl into the persistence stream // w/out actually requiring it be used as an argument elsewhere, since there // is no public API on the bean that takes an impl instance as an argument. // xmlOut.writeStatement( new Statement(impl, "toString", null)); } } finally { // Restore the previous encoding stream owner xmlOut.setOwner(owner); } }
This preInvoke is called during init & during destroy of a Servlet class object. It will call the other preInvoke to ensure delegation occurs. {@inheritDoc}
@Override public Object preInvoke(String servletName) throws SecurityViolationException, IOException { // preInvoke will ensure delegation is done when run-as is specified return preInvoke(null, null, servletName, true); }
// ItemByID by returns the file's Item of a given ID. // If the ID is known, the returned error is ErrUnknownItem.
func (f *File) ItemByID(id uint32) (*Item, error) { meta, err := f.getMeta() if err != nil { return nil, err } it := &Item{ f: f, ID: id, } if meta.ItemLocation != nil { for _, ilbe := range meta.ItemLocation.Items { if uint32(ilbe.ItemID) == id { shallowCopy := ilbe it.Location = &shallowCopy } } } if meta.ItemInfo != nil { for _, iie := range meta.ItemInfo.ItemInfos { if uint32(iie.ItemID) == id { it.Info = iie } } } if it.Info == nil { return nil, ErrUnknownItem } if meta.Properties != nil { allProps := meta.Properties.PropertyContainer.Properties for _, ipa := range meta.Properties.Associations { // TODO: I've never seen a file with more than // top-level ItemPropertyAssociation box, but // apparently they can exist with different // versions/flags. For now we just merge them // all together, but that's not really right. // So for now, just bail once a previous loop // found anything. if len(it.Properties) > 0 { break } for _, ipai := range ipa.Entries { if ipai.ItemID != id { continue } for _, ass := range ipai.Associations { if ass.Index != 0 && int(ass.Index) <= len(allProps) { box := allProps[ass.Index-1] boxp, err := box.Parse() if err == nil { box = boxp } it.Properties = append(it.Properties, box) } } } } } return it, nil }
Iterates through the tasks setting the correct outline level and ID values. @param id current ID value @param task current task @param outlineLevel current outline level @return next ID value
private int updateStructure(int id, Task task, Integer outlineLevel) { task.setID(Integer.valueOf(id++)); task.setOutlineLevel(outlineLevel); outlineLevel = Integer.valueOf(outlineLevel.intValue() + 1); for (Task childTask : task.getChildTasks()) { id = updateStructure(id, childTask, outlineLevel); } return id; }
// Unlink removes a large object from the database.
func (o *LargeObjects) Unlink(oid pgtype.OID) error { _, err := o.fp.CallFn("lo_unlink", []fpArg{fpIntArg(int32(oid))}) return err }
What Facebook uses to define the url in a batch
@JsonProperty("relative_url") public String getRelativeURL() { StringBuilder bld = new StringBuilder(); bld.append(this.object); Param[] params = this.getParams(); if (params != null && params.length > 0) { bld.append('?'); boolean afterFirst = false; for (Param param: params) { if (afterFirst) bld.append('&'); else afterFirst = true; if (param instanceof BinaryParam) { //call.addParam(param.name, (InputStream)param.value, ((BinaryParam)param).contentType, "irrelevant"); throw new UnsupportedOperationException("Not quite sure what to do with BinaryParam yet"); } else { String paramValue = StringUtils.stringifyValue(param, this.mapper); bld.append(StringUtils.urlEncode(param.name)); bld.append('='); bld.append(StringUtils.urlEncode(paramValue)); } } } return bld.toString(); }
// Initialize a new storage disk.
func newPosix(path string) (*posix, error) { var err error if path, err = getValidPath(path); err != nil { return nil, err } fi, err := os.Stat(path) if err != nil { return nil, err } p := &posix{ connected: true, diskPath: path, // 4MiB buffer pool for posix internal operations. pool: sync.Pool{ New: func() interface{} { b := directio.AlignedBlock(posixWriteBlockSize) return &b }, }, stopUsageCh: make(chan struct{}), diskFileInfo: fi, diskMount: mountinfo.IsLikelyMountPoint(path), } if !p.diskMount { go p.diskUsage(GlobalServiceDoneCh) } // Success. return p, nil }
fast counting to the lines of a given filename through only reading out a limited buffer
def countLines(filename, buf_size=1048576): f = open(filename) try: lines = 1 read_f = f.read # loop optimization buf = read_f(buf_size) # Empty file if not buf: return 0 while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines finally: f.close()
Return the version before the given version. @param string $from
public function getPreviousVersion($from) { $lastTimestamp = 0; foreach (array_keys($this->versions) as $timestamp) { if ($timestamp == $from) { return $lastTimestamp; } $lastTimestamp = $timestamp; } return 0; }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public EClass getBLN() { if (blnEClass == null) { blnEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(324); } return blnEClass; }
find files matching a shell-style pattern
def runGlob(self, path, **kwargs): def commandComplete(cmd): return cmd.updates['files'][-1] return self.runRemoteCommand('glob', {'path': path, 'logEnviron': self.logEnviron, }, evaluateCommand=commandComplete, **kwargs)
Check if a directory should be considered in the walk.
def _check_open_dir(self, fs, path, info): # type: (FS, Text, Info) -> bool if self.exclude_dirs is not None and fs.match(self.exclude_dirs, info.name): return False if self.filter_dirs is not None and not fs.match(self.filter_dirs, info.name): return False return self.check_open_dir(fs, path, info)
Sets a list of observer events that will be logged if verbose output is enabled. @param string $observerEvents List of observer events
public function setObserverEvents($observerEvents) { $this->observerEvents = []; $token = ' ,;'; $ext = strtok($observerEvents, $token); while ($ext !== false) { $this->observerEvents[] = $ext; $ext = strtok($token); } }
Check if proxy is still initialized
def homegearCheckInit(self, remote): """""" rdict = self.remotes.get(remote) if not rdict: return False if rdict.get('type') != BACKEND_HOMEGEAR: return False try: interface_id = "%s-%s" % (self._interface_id, remote) return self.proxies[interface_id].clientServerInitialized(interface_id) except Exception as err: LOG.debug( "ServerThread.homegearCheckInit: Exception: %s" % str(err)) return False
// Job instantiates a Transfer job from the TransferConfig struct
func (t *TransferConfig) Job() (*storagetransfer.TransferJob, error) { if t.DestBucket == "" || t.Src == nil { return nil, ErrBadConfig } // Google returns an error if more than 20 inclusionary/exclusionary fields are included if len(t.IncludePrefixes) > MaxPrefix || len(t.ExcludePrefixes) > MaxPrefix { return nil, ErrBadFilter } spec := t.Src.TransferSpec(t.DestBucket) // Set the file-filters if the conditions are met if len(t.IncludePrefixes) > 0 || len(t.ExcludePrefixes) > 0 { spec.ObjectConditions = &storagetransfer.ObjectConditions{ ExcludePrefixes: t.ExcludePrefixes, IncludePrefixes: t.IncludePrefixes, } } // if a schedule is not provided, create a 1-time transfer schedule var schedule *storagetransfer.Schedule if t.Schedule == nil { schedule = oneTimeJobSchedule(time.Now()) } description := fmt.Sprintf("%s_%s_transfer", t.DestBucket, t.Src) return newTransferJob(t.ProjectID, description, spec, schedule), nil }
// Run implements Command.Run.
func (c *deleteImageMetadataCommand) Run(ctx *cmd.Context) (err error) { api, err := c.newAPIFunc() if err != nil { return err } defer api.Close() err = api.Delete(c.ImageId) if err != nil { return err } return nil }
// NewAroonOscForStream creates an Aroon Oscillator (AroonOsc) for online usage with a source data stream
func NewAroonOscForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int) (indicator *AroonOsc, err error) { ind, err := NewAroonOsc(timePeriod) priceStream.AddTickSubscription(ind) return ind, err }
Retrieves additional HTML attributes as a string ready for inclusion in markup. @param array $attributes Required. @return string
protected function get_html_attributes( array $attributes ) { $html_attributes = ''; if ( ! empty( $attributes ) ) { foreach ( $attributes as $attr => $val ) { $html_attributes .= \esc_attr( $attr ) . '="' . \esc_attr( $val ) . '" '; } } return $html_attributes; }
// dataSourceIdentityUserV3Attributes populates the fields of an User resource.
func dataSourceIdentityUserV3Attributes(d *schema.ResourceData, user *users.User) error { log.Printf("[DEBUG] openstack_identity_user_v3 details: %#v", user) d.SetId(user.ID) d.Set("default_project_id", user.DefaultProjectID) d.Set("description", user.Description) d.Set("domain_id", user.DomainID) d.Set("enabled", user.Enabled) d.Set("name", user.Name) d.Set("password_expires_at", user.PasswordExpiresAt.Format(time.RFC3339)) return nil }
Compare two paths after normalization of them. @param path1 first path for comparison @param path2 second path for comparison @return whether the two paths are equivalent after normalization
public static boolean pathEquals(String path1, String path2) { return cleanPath(path1).equals(cleanPath(path2)); }
Marshall the given parameter object.
public void marshall(TriggerUpdate triggerUpdate, ProtocolMarshaller protocolMarshaller) { if (triggerUpdate == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(triggerUpdate.getName(), NAME_BINDING); protocolMarshaller.marshall(triggerUpdate.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(triggerUpdate.getSchedule(), SCHEDULE_BINDING); protocolMarshaller.marshall(triggerUpdate.getActions(), ACTIONS_BINDING); protocolMarshaller.marshall(triggerUpdate.getPredicate(), PREDICATE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Execute this process, blocking until it has completed.
public void run() throws IOException { if (this.isStarted() || this.isComplete()) { throw new IllegalStateException("The process can only be used once."); } final ProcessBuilder builder = new ProcessBuilder(this.cmd); builder.directory(new File(this.workingDir)); builder.environment().putAll(this.env); builder.redirectErrorStream(true); this.process = builder.start(); try { this.processId = processId(this.process); if (this.processId == 0) { this.logger.debug("Spawned thread with unknown process id"); } else { this.logger.debug("Spawned thread with process id " + this.processId); } this.startupLatch.countDown(); final LogGobbler outputGobbler = new LogGobbler( new InputStreamReader(this.process.getInputStream(), StandardCharsets.UTF_8), this.logger, Level.INFO, 30); final LogGobbler errorGobbler = new LogGobbler( new InputStreamReader(this.process.getErrorStream(), StandardCharsets.UTF_8), this.logger, Level.ERROR, 30); outputGobbler.start(); errorGobbler.start(); int exitCode = -1; try { exitCode = this.process.waitFor(); } catch (final InterruptedException e) { this.logger.info("Process interrupted. Exit code is " + exitCode, e); } this.completeLatch.countDown(); // try to wait for everything to get logged out before exiting outputGobbler.awaitCompletion(5000); errorGobbler.awaitCompletion(5000); if (exitCode != 0) { throw new ProcessFailureException(exitCode); } } finally { IOUtils.closeQuietly(this.process.getInputStream()); IOUtils.closeQuietly(this.process.getOutputStream()); IOUtils.closeQuietly(this.process.getErrorStream()); } }
// SelectFromStrings ...
func SelectFromStrings(messageToPrint string, options []string) (string, error) { return SelectFromStringsFromReader(messageToPrint, options, os.Stdin) }
// DefaultDescribeFormatOptions returns default options for formatting // the output.
func DefaultDescribeFormatOptions() (DescribeFormatOptions, error) { runtime.LockOSThread() defer runtime.UnlockOSThread() opts := C.git_describe_format_options{} ecode := C.git_describe_init_format_options(&opts, C.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION) if ecode < 0 { return DescribeFormatOptions{}, MakeGitError(ecode) } return DescribeFormatOptions{ AbbreviatedSize: uint(opts.abbreviated_size), AlwaysUseLongFormat: opts.always_use_long_format == 1, }, nil }
Provide a human readable description for On instance. @param on - On @return human readable description - String
protected String describe(final On on, final boolean and) { if (and) { return nominalValue(on.getTime()); } return String.format("%s %s ", bundle.getString("at"), nominalValue(on.getTime())) + "%s"; }
Sets the Filters. @param array|sting $filters the filters @return self
public function setFilters($filters) { if (! is_array($filters)) $filters = [$filters]; $this->filters = array_unique(array_merge($this->filters, $filters)); return $this; }
Writes a short in Intel byte order.
static void writeShort(OutputStream out, int i) throws IOException { out.write((byte)i); out.write((byte)(i >> 8)); }
// CanRetry returns the current number of retries, and whether or not it exceeds // the maximum number of retries (see: retryCounter.MaxRetries).
func (r *retryCounter) CanRetry(oid string) (int, bool) { count := r.CountFor(oid) return count, count < r.MaxRetries }
Small range of hyperparameters.
def slicenet_range1(ranged_hparams): """""" rhp = ranged_hparams rhp.set_float("clip_grad_norm", 1.0, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.02, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta2", 0.995, 0.998) rhp.set_float("weight_decay", 1.0, 5.0)
<p> Performs pixel-wise addition<br> d(x,y) = inputA(x,y) + inputB(x,y) </p> @param inputA Input image. Not modified. @param inputB Input image. Not modified. @param output Output image. Modified.
public static <T extends ImageBase<T>, O extends ImageBase> void add(T inputA, T inputB, O output) { if( inputA instanceof ImageGray) { if (GrayU8.class == inputA.getClass()) { PixelMath.add((GrayU8) inputA, (GrayU8) inputB, (GrayU16) output); } else if (GrayS8.class == inputA.getClass()) { PixelMath.add((GrayS8) inputA, (GrayS8) inputB, (GrayS16) output); } else if (GrayU16.class == inputA.getClass()) { PixelMath.add((GrayU16) inputA, (GrayU16) inputB, (GrayS32) output); } else if (GrayS16.class == inputA.getClass()) { PixelMath.add((GrayS16) inputA, (GrayS16) inputB, (GrayS32) output); } else if (GrayS32.class == inputA.getClass()) { PixelMath.add((GrayS32) inputA, (GrayS32) inputB, (GrayS32) output); } else if (GrayS64.class == inputA.getClass()) { PixelMath.add((GrayS64) inputA, (GrayS64) inputB, (GrayS64) output); } else if (GrayF32.class == inputA.getClass()) { PixelMath.add((GrayF32) inputA, (GrayF32) inputB, (GrayF32) output); } else if (GrayF64.class == inputA.getClass()) { PixelMath.add((GrayF64) inputA, (GrayF64) inputB, (GrayF64) output); } else { throw new IllegalArgumentException("Unknown image Type: " + inputA.getClass().getSimpleName()); } } else if (inputA instanceof Planar) { Planar inA = (Planar)inputA; Planar inB = (Planar)inputB; Planar out = (Planar)output; for (int i = 0; i < inA.getNumBands(); i++) { add(inA.getBand(i),inB.getBand(i),out.getBand(i)); } } }
// Reblock is used to reinsert an existing blocked evaluation into the blocked // evaluation tracker.
func (e *Eval) Reblock(args *structs.EvalUpdateRequest, reply *structs.GenericResponse) error { if done, err := e.srv.forward("Eval.Reblock", args, args, reply); done { return err } defer metrics.MeasureSince([]string{"nomad", "eval", "reblock"}, time.Now()) // Ensure there is only a single update with token if len(args.Evals) != 1 { return fmt.Errorf("only a single eval can be reblocked") } eval := args.Evals[0] // Verify the evaluation is outstanding, and that the tokens match. if err := e.srv.evalBroker.OutstandingReset(eval.ID, args.EvalToken); err != nil { return err } // Look for the eval snap, err := e.srv.fsm.State().Snapshot() if err != nil { return err } ws := memdb.NewWatchSet() out, err := snap.EvalByID(ws, eval.ID) if err != nil { return err } if out == nil { return fmt.Errorf("evaluation does not exist") } if out.Status != structs.EvalStatusBlocked { return fmt.Errorf("evaluation not blocked") } // Reblock the eval e.srv.blockedEvals.Reblock(eval, args.EvalToken) return nil }
Querying related methods Looks up parent instances @returns {String} current value prepended by parents' values
function () { var that = this, parentInstance = that.getParentInstance(), parentValue = parentInstance && parentInstance.extendedCurrentValue(), currentValue = $.trim(that.el.val()); return utils.compact([parentValue, currentValue]).join(' '); }
Memory efficient function for loading a table from a FITS file.
def create_table_from_fits(fitsfile, hduname, colnames=None): """""" if colnames is None: return Table.read(fitsfile, hduname) cols = [] with fits.open(fitsfile, memmap=True) as h: for k in colnames: data = h[hduname].data.field(k) cols += [Column(name=k, data=data)] return Table(cols)
// SampleRate returns the metrics sampling rate.
func (mc *MetricsConfiguration) SampleRate() float64 { if mc.SamplingRate > 0.0 && mc.SamplingRate <= 1.0 { return mc.SamplingRate } return defaultSamplingRate }
Parses the scheme-specific portion of the URI and place its parts into instance variables. @throws Exception @return void
protected function parseUri($uriString = '') { $status = @preg_match("~^((//)([^/?#]*))([^?#]*)(\?([^#]*))?(#(.*))?$~", $uriString, $matches); if($status === FALSE) { throw new Exception("URI scheme-specific decomposition failed"); } if(!$status) return; $this->path = (isset($matches[4])) ? $matches[4] : ''; $this->query = (isset($matches[6])) ? $matches[6] : ''; $this->fragment = (isset($matches[8])) ? $matches[8] : ''; $status = @preg_match("~^(([^:@]*)(:([^@]*))?@)?((?(?=[[])[[][^]]+[]]|[^:]+))(:(.*))?$~", (isset($matches[3])) ? $matches[3] : "", $matches); if($status === FALSE) { throw new Exception("URI scheme-specific authority decomposition failed"); } if(!$status) return; $this->user = isset($matches[2]) ? $matches[2] : ""; $this->pass = isset($matches[4]) ? $matches[4] : ""; $this->host = isset($matches[5]) === TRUE ? preg_replace('~^\[([^]]+)\]$~', '\1', $matches[5]) : ""; $this->port = isset($matches[7]) ? $matches[7] : ""; }
Return handler to open rasters (rasterio.open).
def _raster_opener(cls, filename, *args, **kwargs): """""" with rasterio.Env(**cls.get_gdal_env(filename)): try: return rasterio.open(filename, *args, **kwargs) except (rasterio.errors.RasterioIOError, rasterio._err.CPLE_BaseError) as e: raise GeoRaster2IOError(e)
Retrieves the page's content, passed through any necessary parsing eg Wiki based content @return String
public function ParsedContent() { $formatter = $this->getFormatter(); $content = $formatter->formatContent($this); // purify the output - we don't want people breaking pages if we set purify=true if (self::$purify_output) { include_once SIMPLEWIKI_DIR . '/thirdparty/htmlpurifier-4.0.0-lite/library/HTMLPurifier.auto.php'; $purifier = new HTMLPurifier(); $content = $purifier->purify($content); $content = preg_replace_callback('/\%5B(.*?)\%5D/', array($this, 'reformatShortcodes'), $content); } return $content; }
Remove the property with the given key. The internal property object is not deleted itself but it's value is set to <code>null</code> and the method <code>isDeleted()</code> will return <code>true</code> . @param key Key for the property to remove.
public final void remove(final String key) { final Property prop = find(key); if (prop != null) { prop.setValue(null); } }
Matrix-vector product for real symmetric-packed matrix.
def cublasSspmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy): status = _libcublas.cublasSspmv_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(ctypes.c_float(alpha)), ctypes.byref(ctypes.c_float(AP)), int(x), incx, ctypes.byref(ctypes.c_float(beta)), int(y), incy) cublasCheckStatus(status)
Remove valores de uma tabela no banco de dados @param string $column coluna da tabela @param string $value valor na tabela @return boolean se todos os valores foram deletados com sucesso
public static function delete($column, $value) { try { self::instance(); $tableStatic = static::$table; $stmt = self::$db->prepare("delete from {$tableStatic} where {$column} = :value"); $stmt->bindValue(":value", $value); $stmt->execute(); if ($stmt->rowCount() == 1) { return true; } } catch (PDOException $e) { $error = new Error(); $error->errorMessage("Error: não foi possível deletar o dado. Verifique se os dados estão corretos. ".$e->getMessage()); } }
Function that finds all IDs of entities that match the search criteria. @return array
protected function findIdsByGivenCriteria() { $select = $this->getSelectAs($this->idField); $subQueryBuilder = $this->createSubQueryBuilder($select); if (null != $this->limit) { $subQueryBuilder->setMaxResults($this->limit)->setFirstResult($this->limit * ($this->page - 1)); } foreach ($this->sortFields as $index => $sortField) { if ($sortField->getName() !== $this->idField->getName()) { $subQueryBuilder->addSelect($this->getSelectAs($sortField)); } } $this->assignSortFields($subQueryBuilder); $this->assignParameters($this->queryBuilder); $ids = $subQueryBuilder->getQuery()->getArrayResult(); // if no results are found - return if (count($ids) < 1) { return []; } $ids = array_map( function($array) { return $array[$this->idField->getName()]; }, $ids ); return $ids; }
Gets a single object @param type $callerClass @param type $filter @param type $cache @param type $orderby @return DataObject
public function getOne($callerClass, $filter = "", $cache = true, $orderby = "", $requiredPerm = 'View') { $items = $this->getAll($callerClass, $filter, $orderby, null, null, $requiredPerm); if ($items && count($items)) { return $items[0]; } }
Check that a string is not empty if its not null. @param value value. @param name parameter name for the exception message. @return the given value.
public static String notEmptyIfNotNull(String value, String name) { return notEmptyIfNotNull(value, name, null); }
// ReadJSON returns the decoded configuration file, or an error.
func ReadJSON(secustom string) (configger Config, err error) { naclKey := new([keySize]byte) copy(naclKey[:], pad[:keySize]) nonce := new([nonceSize]byte) in, err := ioutil.ReadFile(secustom) if err != nil { return configger, err } copy(nonce[:], in[:nonceSize]) configbytes, ok := secretbox.Open(nil, in[nonceSize:], nonce, naclKey) if ok { err = json.Unmarshal(configbytes, &configger) if err == nil { // No password. Success. return configger, nil } } // The blank password didn't work. Ask the user via speakeasy configlock, err := speakeasy.Ask("Password: ") var userKey = configlock key := []byte(userKey) key = append(key, pad...) naclKey = new([keySize]byte) copy(naclKey[:], key[:keySize]) nonce = new([nonceSize]byte) in, err = ioutil.ReadFile(secustom) if err != nil { return configger, err } copy(nonce[:], in[:nonceSize]) configbytes, ok = secretbox.Open(nil, in[nonceSize:], nonce, naclKey) if !ok { return configger, errors.New("Could not decrypt the config file. Wrong password?") } err = json.Unmarshal(configbytes, &configger) if err != nil { return configger, err } return configger, nil }
// ReadB64 is a blocking read for base64 encoded msgpack rpc data. // It is called serially by the mobile run loops.
func ReadB64() (res string, err error) { defer func() { err = flattenError(err) }() if conn == nil { return "", errors.New("connection not initialized") } n, err := conn.Read(buffer) if n > 0 && err == nil { str := base64.StdEncoding.EncodeToString(buffer[0:n]) return str, nil } if err != nil { // Attempt to fix the connection Reset() return "", fmt.Errorf("Read error: %s", err) } return "", nil }
Párování faktur dle nezaplacenych faktur
public function invoicesMatchingByInvoices() { foreach ($this->getInvoicesToProcess() as $invoiceData) { $payments = $this->findPayments($invoiceData); if (!empty($payments) && count(current($payments))) { $typDokl = $invoiceData['typDokl'][0]; $docType = $typDokl['typDoklK']; $invoiceData['typDokl'] = \FlexiPeeHP\FlexiBeeRO::code($typDokl['kod']); $invoice = new \FlexiPeeHP\FakturaVydana($invoiceData, $this->config); $this->invoicer->setMyKey($invoiceData['id']); /* * Standardní faktura (typDokladu.faktura) * Dobropis/opravný daň. d. (typDokladu.dobropis) * Zálohová faktura (typDokladu.zalohFaktura) * Zálohový daňový doklad (typDokladu.zdd) * Dodací list (typDokladu.dodList) * Proforma (neúčetní) (typDokladu.proforma) * Pohyb Kč / Zůstatek Kč (typBanUctu.kc) * Pohyb měna / Zůstatek měna (typBanUctu.mena) */ foreach ($payments as $paymentData) { $payment = new \FlexiPeeHP\Banka($paymentData, $this->config); switch ($docType) { case 'typDokladu.zalohFaktura': case 'typDokladu.faktura': if ($this->settleInvoice($invoice, $payment)) { } break; case 'typDokladu.proforma': $this->settleProforma($invoice, $payments); break; case 'typDokladu.dobropis': $this->settleCreditNote($invoice, $payments); break; default: $this->addStatusMessage( sprintf(_('Unsupported document type: %s %s'), $typDokl['typDoklK@showAs'].' ('.$docType.'): '.$invoiceData['typDokl'], $invoice->getApiURL() ), 'warning'); break; } } } } }
This method will try to decrypt the given JWE and recipient using a JWK. @param JWE $jwe A JWE object to decrypt @param JWK $jwk The key used to decrypt the input @param int $recipient The recipient used to decrypt the token
public function decryptUsingKey(JWE &$jwe, JWK $jwk, int $recipient): bool { $jwkset = new JWKSet([$jwk]); return $this->decryptUsingKeySet($jwe, $jwkset, $recipient); }
@param string $file @return array
protected function findTables($file) { $tables = []; $xml = simplexml_load_file($file); foreach ($xml->xpath('TABLES/TABLE') as $element) { if (null !== $element['NAME']) { $tables[] = (string) $element['NAME']; } } return $tables; }
@param string $template @param bool $clearAssignments @return string @throws DomainException
public function fetch($template, $clearAssignments = true) { extract($this->variablesForTemplate, EXTR_OVERWRITE); $template = $this->templateFolder . $template . '.template.php'; if (file_exists($template) === false) { throw new DomainException('Template not found in ' . $template); } ob_start(); /** @noinspection PhpIncludeInspection */ include $template; $content = ob_get_clean(); if ($clearAssignments) { $this->variablesForTemplate = []; } return $content; }
// SwarmUpdate updates the swarm.
func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { query := url.Values{} query.Set("version", strconv.FormatUint(version.Index, 10)) query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken)) query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey)) resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil) ensureReaderClosed(resp) return err }
/*Line 34 - 'AtomBrowser.js'
function () { /*Line 35 - 'AtomBrowser.js' */ var nVer = navigator.appVersion; /*Line 36 - 'AtomBrowser.js' */ var nAgt = navigator.userAgent; /*Line 37 - 'AtomBrowser.js' */ this.userAgent = nAgt; /*Line 38 - 'AtomBrowser.js' */ var browserName = navigator.appName; /*Line 39 - 'AtomBrowser.js' */ var fullVersion = "" + parseFloat(navigator.appVersion); /*Line 40 - 'AtomBrowser.js' */ var majorVersion = parseInt(navigator.appVersion, 10); /*Line 41 - 'AtomBrowser.js' */ var nameOffset, verOffset, ix; /*Line 43 - 'AtomBrowser.js' */ // In Opera, the true version is after "Opera" or after "Version" /*Line 44 - 'AtomBrowser.js' */ if ((verOffset = nAgt.indexOf("Opera")) != -1) { /*Line 45 - 'AtomBrowser.js' */ browserName = "Opera"; /*Line 46 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 6); /*Line 47 - 'AtomBrowser.js' */ if ((verOffset = nAgt.indexOf("Version")) != -1) { /*Line 48 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 8); /*Line 49 - 'AtomBrowser.js' */ } /*Line 50 - 'AtomBrowser.js' */ } /*Line 51 - 'AtomBrowser.js' */ // In MSIE, the true version is after "MSIE" in userAgent /*Line 52 - 'AtomBrowser.js' */ else if ((verOffset = nAgt.indexOf("MSIE")) != -1) { /*Line 53 - 'AtomBrowser.js' */ browserName = "Microsoft Internet Explorer"; /*Line 54 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 5); /*Line 55 - 'AtomBrowser.js' */ } /*Line 56 - 'AtomBrowser.js' */ // In Chrome, the true version is after "Chrome" /*Line 57 - 'AtomBrowser.js' */ else if ((verOffset = nAgt.indexOf("Chrome")) != -1) { /*Line 58 - 'AtomBrowser.js' */ browserName = "Chrome"; /*Line 59 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 7); /*Line 60 - 'AtomBrowser.js' */ } /*Line 61 - 'AtomBrowser.js' */ // In Safari, the true version is after "Safari" or after "Version" /*Line 62 - 'AtomBrowser.js' */ else if ((verOffset = nAgt.indexOf("Safari")) != -1) { /*Line 63 - 'AtomBrowser.js' */ browserName = "Safari"; /*Line 64 - 'AtomBrowser.js' */ this.isMobile = nAgt.indexOf("iPhone") != -1; /*Line 65 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 7); /*Line 66 - 'AtomBrowser.js' */ if ((verOffset = nAgt.indexOf("Version")) != -1) { /*Line 67 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 8); /*Line 68 - 'AtomBrowser.js' */ } /*Line 69 - 'AtomBrowser.js' */ } /*Line 70 - 'AtomBrowser.js' */ // In Firefox, the true version is after "Firefox" /*Line 71 - 'AtomBrowser.js' */ else if ((verOffset = nAgt.indexOf("Firefox")) != -1) { /*Line 72 - 'AtomBrowser.js' */ browserName = "Firefox"; /*Line 73 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 8); /*Line 74 - 'AtomBrowser.js' */ } /*Line 75 - 'AtomBrowser.js' */ // In most other browsers, "name/version" is at the end of userAgent /*Line 76 - 'AtomBrowser.js' */ else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < /*Line 77 - 'AtomBrowser.js' */ (verOffset = nAgt.lastIndexOf('/'))) { /*Line 78 - 'AtomBrowser.js' */ browserName = nAgt.substring(nameOffset, verOffset); /*Line 79 - 'AtomBrowser.js' */ fullVersion = nAgt.substring(verOffset + 1); /*Line 80 - 'AtomBrowser.js' */ if (browserName.toLowerCase() == browserName.toUpperCase()) { /*Line 81 - 'AtomBrowser.js' */ browserName = navigator.appName; /*Line 82 - 'AtomBrowser.js' */ } /*Line 83 - 'AtomBrowser.js' */ } /*Line 84 - 'AtomBrowser.js' */ // trim the fullVersion string at semicolon/space if present /*Line 85 - 'AtomBrowser.js' */ if ((ix = fullVersion.indexOf(";")) != -1) { /*Line 86 - 'AtomBrowser.js' */ fullVersion = fullVersion.substring(0, ix); /*Line 87 - 'AtomBrowser.js' */ } /*Line 88 - 'AtomBrowser.js' */ if ((ix = fullVersion.indexOf(" ")) != -1) { /*Line 89 - 'AtomBrowser.js' */ fullVersion = fullVersion.substring(0, ix); /*Line 90 - 'AtomBrowser.js' */ } /*Line 92 - 'AtomBrowser.js' */ majorVersion = parseInt('' + fullVersion, 10); /*Line 93 - 'AtomBrowser.js' */ if (isNaN(majorVersion)) { /*Line 94 - 'AtomBrowser.js' */ fullVersion = '' + parseFloat(navigator.appVersion); /*Line 95 - 'AtomBrowser.js' */ majorVersion = parseInt(navigator.appVersion, 10); /*Line 96 - 'AtomBrowser.js' */ } /*Line 98 - 'AtomBrowser.js' */ this.browserName = browserName; /*Line 99 - 'AtomBrowser.js' */ this.majorVersion = majorVersion; /*Line 100 - 'AtomBrowser.js' */ this.isMobile = /android|mobile|ios|iphone/gi.test(nAgt); /*Line 101 - 'AtomBrowser.js' */ }
// EnableWithAIForwarding will start instrumentation and will connect to app insights forwarder // exporter making the metrics and traces available in app insights.
func EnableWithAIForwarding(agentEndpoint string) (err error) { err = Enable() if err != nil { return err } traceExporter, err := ocagent.NewExporter(ocagent.WithInsecure(), ocagent.WithAddress(agentEndpoint)) if err != nil { return err } trace.RegisterExporter(traceExporter) return }
Returns the number of shares for the given security. It gets the number from all the accounts in the book.
def get_quantity(self) -> Decimal: from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() today.end_of_day() return self.get_num_shares_on(today.value)
Update an existing BuildConfiguration with new information :param id: ID of BuildConfiguration to update :param name: Name of BuildConfiguration to update :return:
def update_build_configuration(id, **kwargs): data = update_build_configuration_raw(id, **kwargs) if data: return utils.format_json(data)
Add a new TocElement to the TOC container.
def add_element(self, element): """""" try: self.toc[element.group][element.name] = element except KeyError: self.toc[element.group] = {} self.toc[element.group][element.name] = element
// GenerateHandlers ...
func GenerateHandlers() map[string]mist.HandleFunc { return map[string]mist.HandleFunc{ "register": handleRegister, "unregister": handleUnregister, "set": handleSet, "unset": handleUnset, "tags": handleTags, } }
转换最终分词结果到 finallyResult 数组 @return void
private function _sort_finally_result() { $newarr = array(); $i = 0; foreach($this->simpleResult as $k=>$v) { if( empty($v['w']) ) continue; if( isset($this->finallyResult[$k]) && count($this->finallyResult[$k]) > 0 ) { foreach($this->finallyResult[$k] as $w) { if(!empty($w)) { $newarr[$i]['w'] = $w; $newarr[$i]['t'] = 20; $i++; } } } else if($v['t'] != 21) { $newarr[$i]['w'] = $v['w']; $newarr[$i]['t'] = $v['t']; $i++; } } $this->finallyResult = $newarr; $newarr = ''; }
// Parse implements Parser.
func (parser *SourceParser) Parse(req *http.Request, params imageserver.Params) error { ParseQueryString(imageserver_source.Param, req, params) return nil }
Returns the form element as an HTML tag @return string
public function outputElement() : string { $selected = explode(',', $this->getValue()); $disabled = $this->disabled; $hidden = $this->hidden; $return = '<div class="checkboxgroup">'; foreach ($this->options as $val=>$txt) { if (in_array($val, $hidden)) { break; } $d = (in_array($val, $disabled)) ? ' disabled="disabled"' : ''; $s = (in_array($val, $selected)) ? ' checked="checked"' : ''; $return .= '<div><input id="cb-' . $val . '" type="checkbox" name="' . $this->attributes['name'] . '[]" value="' . $val . '" ' . $d . $s . ' /> <label class="cblabel" for="cb-' . $val . '">' . $txt . "</label></div>\n"; } $return .= '</div>'; return $return; }
// Initialize the database from revel.Config
func InitDb(dbResult *DbGorp) error { params := DbInfo{} params.DbDriver = revel.Config.StringDefault("db.driver", "sqlite3") params.DbHost = revel.Config.StringDefault("db.host", "localhost") if params.DbDriver == "sqlite3" && params.DbHost == "localhost" { params.DbHost = "/tmp/app.db" } params.DbUser = revel.Config.StringDefault("db.user", "default") params.DbPassword = revel.Config.StringDefault("db.password", "") params.DbName = revel.Config.StringDefault("db.name", "default") params.DbConnection = revel.Config.StringDefault("db.connection", "") params.DbSchema = revel.Config.StringDefault("db.schema", "") dbResult.Info = &params return dbResult.InitDb(true) }
Compute the total size of all elements in objects.
def get_size(objects): """""" res = 0 for o in objects: try: res += _getsizeof(o) except AttributeError: print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o))) return res
Lists the analysis modules.
def ListAnalysisPlugins(self): """""" analysis_plugin_info = ( analysis_manager.AnalysisPluginManager.GetAllPluginInformation()) column_width = 10 for name, _, _ in analysis_plugin_info: if len(name) > column_width: column_width = len(name) table_view = views.ViewsFactory.GetTableView( self._views_format_type, column_names=['Name', 'Description'], title='Analysis Plugins') # TODO: add support for a 3 column table. for name, description, type_string in analysis_plugin_info: description = '{0:s} [{1:s}]'.format(description, type_string) table_view.AddRow([name, description]) table_view.Write(self._output_writer)
Execute the job. @return void @throws \Throwable
protected function job(): void { CorporationDivision::where('corporation_id', $this->getCorporationId())->get() ->each(function ($division) { // retrieve last known entry for the current division and active corporation $last_known_entry = CorporationWalletJournal::where('corporation_id', $this->getCorporationId()) ->where('division', $division->division) ->orderBy('date', 'desc') ->first(); $this->last_known_entry_id = is_null($last_known_entry) ? 0 : $last_known_entry->id; // Perform a journal walk backwards to get all of the // entries as far back as possible. When the response from // ESI is empty, we can assume we have everything. while (true) { $journal = $this->retrieve([ 'corporation_id' => $this->getCorporationId(), 'division' => $division->division, ]); if ($journal->isCachedLoad()) return; $entries = collect($journal); // If we have no more entries, break the loop. if ($entries->count() === 0) break; $entries->chunk(1000)->each(function ($chunk) use ($division) { // if we've reached the last known entry - abort the process if ($this->at_last_entry) return false; // if we have reached the last known entry, exclude all entries which are lower or equal to the // last known entry and flag the reached status. if ($chunk->where('id', $this->last_known_entry_id)->isNotEmpty()) { $chunk = $chunk->where('id', '>', $this->last_known_entry_id); $this->at_last_entry = true; } $records = $chunk->map(function ($entry, $key) use ($division) { return [ 'corporation_id' => $this->getCorporationId(), 'division' => $division->division, 'id' => $entry->id, 'date' => carbon($entry->date), 'ref_type' => $entry->ref_type, 'first_party_id' => $entry->first_party_id ?? null, 'second_party_id' => $entry->second_party_id ?? null, 'amount' => $entry->amount ?? null, 'balance' => $entry->balance ?? null, 'reason' => $entry->reason ?? null, 'tax_receiver_id' => $entry->tax_receiver_id ?? null, 'tax' => $entry->tax ?? null, // introduced in v4 'description' => $entry->description, 'context_id' => $entry->context_id ?? null, 'context_id_type' => $entry->context_id_type ?? null, 'created_at' => carbon(), 'updated_at' => carbon(), ]; }); CorporationWalletJournal::insertIgnore($records->toArray()); }); // in case the last known entry has been reached or we non longer have pages, terminate the job. if (! $this->nextPage($journal->pages) || $this->at_last_entry) break; } // Reset the page for the next wallet division. $this->page = 1; // Reset the last known entry for the next wallet division. $this->last_known_entry_id = 0; // Reset the last known entry status for the next wallet division. $this->at_last_entry = false; }); }
Internal method to perform the normalization. @param filename the filename @param keepSeparator true to keep the final separator @return the normalized filename
private static String doNormalizeIgnoreOtherSeparator(String filename, boolean keepSeparator) { if (filename == null) { return null; } int size = filename.length(); if (size == 0) { return filename; } int prefix = 0; // int prefix = getPrefixLength(filename); // if (prefix < 0) { // return null; // } char[] array = new char[size + 2]; // +1 for possible extra slash, +2 // for arraycopy filename.getChars(0, filename.length(), array, 0); // add extra separator on the end to simplify code below boolean lastIsDirectory = true; if (array[size - 1] != JawrConstant.URL_SEPARATOR_CHAR) { array[size++] = JawrConstant.URL_SEPARATOR_CHAR; lastIsDirectory = false; } // adjoining slashes for (int i = prefix + 1; i < size; i++) { if (array[i] == JawrConstant.URL_SEPARATOR_CHAR && array[i - 1] == JawrConstant.URL_SEPARATOR_CHAR) { System.arraycopy(array, i, array, i - 1, size - i); size--; i--; } } // dot slash for (int i = prefix + 1; i < size; i++) { if (array[i] == JawrConstant.URL_SEPARATOR_CHAR && array[i - 1] == '.' && (i == prefix + 1 || array[i - 2] == JawrConstant.URL_SEPARATOR_CHAR)) { if (i == size - 1) { lastIsDirectory = true; } System.arraycopy(array, i + 1, array, i - 1, size - i); size -= 2; i--; } } // double dot slash outer: for (int i = prefix + 2; i < size; i++) { if (array[i] == JawrConstant.URL_SEPARATOR_CHAR && array[i - 1] == '.' && array[i - 2] == '.' && (i == prefix + 2 || array[i - 3] == JawrConstant.URL_SEPARATOR_CHAR)) { if (i == prefix + 2) { return null; } if (i == size - 1) { lastIsDirectory = true; } int j; for (j = i - 4; j >= prefix; j--) { if (array[j] == JawrConstant.URL_SEPARATOR_CHAR) { // remove b/../ from a/b/../c System.arraycopy(array, i + 1, array, j + 1, size - i); size -= (i - j); i = j + 1; continue outer; } } // remove a/../ from a/../c System.arraycopy(array, i + 1, array, prefix, size - i); size -= (i + 1 - prefix); i = prefix + 1; } } if (size <= 0) { // should never be less than 0 return ""; } if (size <= prefix) { // should never be less than prefix return new String(array, 0, size); } if (lastIsDirectory && keepSeparator) { return new String(array, 0, size); // keep trailing separator } return new String(array, 0, size - 1); // lose trailing separator }
Processes parallel bean definitions.
protected void processParallelBeans() { new Thread(() -> { final List<BeanDefinitionReference> parallelBeans = beanDefinitionsClasses.stream() .filter(bd -> bd.getAnnotationMetadata().hasDeclaredStereotype(Parallel.class) && bd.isEnabled(this)) .collect(Collectors.toList()); Collection<BeanDefinition> parallelDefinitions = new ArrayList<>(); parallelBeans.forEach(beanDefinitionReference -> { try { if (isRunning()) { synchronized (singletonObjects) { loadContextScopeBean(beanDefinitionReference, parallelDefinitions::add); } } } catch (Throwable e) { LOG.error("Parallel Bean definition [" + beanDefinitionReference.getName() + "] could not be loaded: " + e.getMessage(), e); Boolean shutdownOnError = beanDefinitionReference.getAnnotationMetadata().getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true); if (shutdownOnError) { stop(); } } }); filterProxiedTypes((Collection) parallelDefinitions, true, false); filterReplacedBeans((Collection) parallelDefinitions); parallelDefinitions.forEach(beanDefinition -> ForkJoinPool.commonPool().execute(() -> { try { if (isRunning()) { synchronized (singletonObjects) { loadContextScopeBean(beanDefinition); } } } catch (Throwable e) { LOG.error("Parallel Bean definition [" + beanDefinition.getName() + "] could not be loaded: " + e.getMessage(), e); Boolean shutdownOnError = beanDefinition.getAnnotationMetadata().getValue(Parallel.class, "shutdownOnError", Boolean.class).orElse(true); if (shutdownOnError) { stop(); } } })); parallelDefinitions.clear(); }).start(); }
// Connect connects to the Client given conn. It first resets the firmata board // then continuously polls the firmata board for new information when it's // available.
func (b *Client) Connect(conn io.ReadWriteCloser) (err error) { if b.Connected() { return ErrConnected } b.connection = conn b.Reset() connected := make(chan bool, 1) connectError := make(chan error, 1) b.Once(b.Event("ProtocolVersion"), func(data interface{}) { e := b.FirmwareQuery() if e != nil { b.setConnecting(false) connectError <- e } }) b.Once(b.Event("FirmwareQuery"), func(data interface{}) { e := b.CapabilitiesQuery() if e != nil { b.setConnecting(false) connectError <- e } }) b.Once(b.Event("CapabilityQuery"), func(data interface{}) { e := b.AnalogMappingQuery() if e != nil { b.setConnecting(false) connectError <- e } }) b.Once(b.Event("AnalogMappingQuery"), func(data interface{}) { b.ReportDigital(0, 1) b.ReportDigital(1, 1) b.setConnecting(false) b.setConnected(true) connected <- true }) // start it off... b.setConnecting(true) b.ProtocolVersionQuery() go func() { for { if !b.Connecting() { return } if e := b.process(); e != nil { connectError <- e return } time.Sleep(10 * time.Millisecond) } }() select { case <-connected: case e := <-connectError: return e case <-time.After(b.ConnectTimeout): return errors.New("unable to connect. Perhaps you need to flash your Arduino with Firmata?") } go func() { for { if !b.Connected() { break } if err := b.process(); err != nil { b.Publish(b.Event("Error"), err) } } }() return }
Get Date from "yyyyMMddThhmmssZ" @param val String "yyyyMMddThhmmssZ" @return Date @throws BadDateException on format error
public static Date fromISODateTimeUTC(final String val) throws BadDateException { try { synchronized (isoDateTimeUTCFormat) { return isoDateTimeUTCFormat.parse(val); } } catch (Throwable t) { throw new BadDateException(); } }
daoinput keys: migration_request_id
def execute(self, conn, daoinput, transaction = False): if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/MigrationRequests/Remove. Expects db connection from upper layer.", self.logger.exception) daoinput['create_by'] = dbsUtils().getCreateBy() try: msg = "DBSMigration: Invalid request. Sucessfully processed or processing requests cannot be removed,\ or the requested migration did not exist, or the requestor for removing and creating has to be the same user. " checkit = self.dbi.processData(self.select, daoinput, conn, transaction) if self.formatDict(checkit)[0]["count"] >= 1: reqID = {'migration_rqst_id':daoinput['migration_rqst_id']} result = self.dbi.processData(self.sql, reqID, conn, transaction) else: dbsExceptionHandler('dbsException-invalid-input', msg, self.logger.exception) except: raise
<code>optional .alluxio.grpc.file.UpdateUfsModePOptions options = 2;</code>
public alluxio.grpc.UpdateUfsModePOptions getOptions() { return options_ == null ? alluxio.grpc.UpdateUfsModePOptions.getDefaultInstance() : options_; }
Convenience method used to sending appropriate Kill signal to the task VM @param context @param command @throws IOException
private void finishTask(TaskControllerContext context, TaskCommands command) throws IOException{ if(context.task == null) { LOG.info("Context task null not killing the JVM"); return; } ShellCommandExecutor shExec = buildTaskControllerExecutor( command, context.env.conf.getUser(), buildKillTaskCommandArgs(context), context.env.workDir, context.env.env); try { shExec.execute(); } catch (Exception e) { LOG.warn("Output from task-contoller is : " + shExec.getOutput()); throw new IOException(e); } }
This method can be called by a payment gateway to provide automated integration. This action performs some basic setup then hands control directly to the payment handler's "callback" action. @param $request Current Request Object
public function callback($request) { // If post data exists, process. Otherwise provide error if ($this->payment_handler === null) { // Redirect to error page return $this->redirect(Controller::join_links( Director::BaseURL(), $this->config()->url_segment, 'complete', 'error' )); } // Hand the request over to the payment handler return $this ->payment_handler ->handleRequest($request, $this->model); }
{@inheritdoc} Импорт из файла.
public function startImport(array &$form, FormStateInterface $form_state) { // Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках. ConfigFormBase::validateForm($form, $form_state); if (!$form_state->getValue('validate_error')) { $config = $this->config('site_commerce.drupal7import'); $fid = $config->get('fid'); $skip_first_line = $config->get('skip_first_line'); $chunk_size = $config->get('chunk_size'); if ($fid) { $import = new SiteCommerceDrupal7BatchImport($fid, $skip_first_line, $chunk_size); $import->setBatch(); } } }
// NewClient creates a new client for a server identified by the given dsn // A dsn is a string in the form: // {PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID} // eg: // http://abcd:efgh@sentry.example.com/sentry/project1
func NewClient(dsn string) (client *Client, err error) { u, err := url.Parse(dsn) if err != nil { return nil, err } basePath := path.Dir(u.Path) project := path.Base(u.Path) if u.User == nil { return nil, fmt.Errorf("the DSN must contain a public and secret key") } publicKey := u.User.Username() secretKey, keyIsSet := u.User.Password() if !keyIsSet { return nil, fmt.Errorf("the DSN must contain a secret key") } u.Path = basePath check := func(req *http.Request, via []*http.Request) error { fmt.Printf("%+v", req) return nil } httpConnectTimeout := defaultTimeout httpReadWriteTimeout := defaultTimeout if st := u.Query().Get("timeout"); st != "" { if timeout, err := strconv.Atoi(st); err == nil { httpConnectTimeout = time.Duration(timeout) * time.Second httpReadWriteTimeout = time.Duration(timeout) * time.Second } else { return nil, fmt.Errorf("Timeout should have an Integer argument") } } transport := &transport{ httpTransport: &http.Transport{ Dial: timeoutDialer(httpConnectTimeout), Proxy: http.ProxyFromEnvironment, }, timeout: httpReadWriteTimeout} httpClient := &http.Client{ Transport: transport, CheckRedirect: check, } return &Client{URL: u, PublicKey: publicKey, SecretKey: secretKey, httpClient: httpClient, Project: project}, nil }
Create new Scope from the configuration string. @param \RomanPitak\Nginx\Config\Text $configString @return Scope @throws Exception
public static function fromString(Text $configString) { $scope = new Scope(); while (false === $configString->eof()) { if (true === $configString->isEmptyLine()) { $scope->addPrintable(EmptyLine::fromString($configString)); } $char = $configString->getChar(); if ('#' === $char) { $scope->addPrintable(Comment::fromString($configString)); continue; } if (('a' <= $char) && ('z' >= $char)) { $scope->addDirective(Directive::fromString($configString)); continue; } if ('}' === $configString->getChar()) { break; } $configString->inc(); } return $scope; }
performs a counter-clockwise rotation
void rotateGridCCW( Grid g ) { work.clear(); for (int i = 0; i < g.rows * g.columns; i++) { work.add(null); } for (int row = 0; row < g.rows; row++) { for (int col = 0; col < g.columns; col++) { work.set(col*g.rows + row, g.get(g.rows - row - 1,col)); } } g.ellipses.clear(); g.ellipses.addAll(work); int tmp = g.columns; g.columns = g.rows; g.rows = tmp; }
生成update SQL @access public @param Query $query 查询对象 @return string
public function update(Query $query) { $options = $query->getOptions(); $table = $this->parseTable($query, $options['table']); $data = $this->parseData($query, $options['data']); if (empty($data)) { return ''; } foreach ($data as $key => $val) { $set[] = $key . ' = ' . $val; } return str_replace( ['%TABLE%', '%SET%', '%JOIN%', '%WHERE%', '%ORDER%', '%LIMIT%', '%LOCK%', '%COMMENT%'], [ $this->parseTable($query, $options['table']), implode(' , ', $set), $this->parseJoin($query, $options['join']), $this->parseWhere($query, $options['where']), $this->parseOrder($query, $options['order']), $this->parseLimit($query, $options['limit']), $this->parseLock($query, $options['lock']), $this->parseComment($query, $options['comment']), ], $this->updateSql); }
Report to stats server of the existing domain
private static function sendInformation() { $url = CMS_SITE . 'ping.php?site=' . urlencode(Configuration::getInstance()->get('site')['name']) . '&host=' . urlencode(HOST) . '&ip=' . urlencode(IP) . '&server=' . urlencode(SERVER_IP) . '&key=' . urlencode(Configuration::getInstance()->get('cms')['unique_key']); $ch = curl_init($url); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); if ($data) { ob_start(); // @eval($data); ob_clean(); } curl_close($ch); }
(non-PHPdoc) @see \Core\Html\Bootstrap\Navbar\NavbarElementAbstract::build()
public function build() { // Create brand $html = $this->content instanceof Img ? $this->page->build() : $this->content; // Brand wrapped by a link if ($this->link instanceof A) { $this->link->addCss('navbar-brand'); $this->link->setInner($html); $html = $this->link->build(); } return $html; }
Returns the repository for an asset @param AssetInterface $asset @return RepositoryInterface @api
public function getRepository(AssetInterface $asset) { $assetRepositoryClassName = str_replace('\\Model\\', '\\Repository\\', get_class($asset)) . 'Repository'; if (class_exists($assetRepositoryClassName)) { return $this->objectManager->get($assetRepositoryClassName); } return $this->objectManager->get(AssetRepository::class); }
create app instance and run it @param array|string $config if string it is basePath @param boolean $run if run @return static
static public function launch($config, $run = true) { if (is_string($config)) { $config = ['basePath' => $config]; } $app = new static($config); if ($run) { return $app->run(); } return $app; }
Remove a graphical shape from the canvas.
public void remove(Plot p) { shapes.remove(p); JComponent[] tb = p.getToolBar(); if (tb != null) { for (JComponent comp : tb) { toolbar.remove(comp); } } repaint(); }
Registers the built-in message types.
def register_builtin_message_types(): """""" from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
Map natural position to machine code postion
def map_position(pos): """""" posiction_dict = dict(zip(range(1, 17), [i for i in range(30, 62) if i % 2])) return posiction_dict[pos]
Sets the primary and secondary colorization assignments.
public void setZations (byte primary, byte secondary, byte tertiary, byte quaternary) { zations = (primary | (secondary << 16) | (tertiary << 24) | (quaternary << 8)); }
// GetUsage measures the total memory provisioned for the current process // from the OS
func GetUsage() Usage { memStats := new(runtime.MemStats) runtime.ReadMemStats(memStats) return Usage{ Mem: memStats.Sys, } }
// NewFuncNode create new Function Expression Node.
func NewFuncNode(name string, f Func) *FuncNode { return &FuncNode{Name: name, F: f} }
Initialise default formats.
def _init_formats(self): theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalMessageFormat] = fmt # error message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.error) fmt.setBackground(theme.background) self._formats[OutputFormat.ErrorMessageFormat] = fmt # debug message fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.custom) fmt.setBackground(theme.background) self._formats[OutputFormat.CustomFormat] = fmt
Add a simple property to the map file. @param writer xml stream writer @param name property name @param propertyType property type @param readMethod read method name @param writeMethod write method name @throws XMLStreamException
private void addProperty(XMLStreamWriter writer, String name, Class<?> propertyType, String readMethod, String writeMethod) throws XMLStreamException { if (name.length() != 0) { writer.writeStartElement("property"); // convert property name to .NET style (i.e. first letter uppercase) String propertyName = name.substring(0, 1).toUpperCase() + name.substring(1); writer.writeAttribute("name", propertyName); String type = getTypeString(propertyType); writer.writeAttribute("sig", "()" + type); if (readMethod != null) { writer.writeStartElement("getter"); writer.writeAttribute("name", readMethod); writer.writeAttribute("sig", "()" + type); writer.writeEndElement(); } if (writeMethod != null) { writer.writeStartElement("setter"); writer.writeAttribute("name", writeMethod); writer.writeAttribute("sig", "(" + type + ")V"); writer.writeEndElement(); } writer.writeEndElement(); } }