comment
stringlengths
16
255
code
stringlengths
52
3.87M
Computes the new parent id for the node being moved. @return int
protected function parentId() { switch ( $this->position ) { case 'root': return null; case 'child': return $this->target->getKey(); default: return $this->target->getParentId(); } }
// SetWinSize overwrites the playlist's window size.
func (p *MediaPlaylist) SetWinSize(winsize uint) error { if winsize > p.capacity { return errors.New("capacity must be greater than winsize or equal") } p.winsize = winsize return nil }
Show the sidebar and squish the container to make room for the sidebar. If hideOthers is true, hide other open sidebars.
function() { var options = this.options; if (options.hideOthers) { this.secondary.each(function() { var sidebar = $(this); if (sidebar.hasClass('is-expanded')) { sidebar.toolkit('offCanvas', 'hide'); } }); } this.fireEvent('showing'); this.container.addClass('move-' + this.opposite); this.element .reveal() .addClass('is-expanded') .aria('expanded', true); if (options.stopScroll) { $('body').addClass('no-scroll'); } this.fireEvent('shown'); }
Decide the fate of the cells
def nextGen(self): self.current_gen += 1 self.change_gen[self.current_gen % 3] = copy.copy(self.grid) grid_cp = copy.copy(self.grid) for cell in self.grid: y, x = cell y1 = (y - 1) % self.y_grid y2 = (y + 1) % self.y_grid x1 = (x - 1) % self.x_grid x2 = (x + 1) % self.x_grid n = self.countNeighbours(cell) if n < 2 or n > 3: del grid_cp[cell] self.addchar(y + self.y_pad, x + self.x_pad, ' ') else: grid_cp[cell] = min(self.grid[cell] + 1, self.color_max) for neighbour in product([y1, y, y2], [x1, x, x2]): if not self.grid.get(neighbour): if self.countNeighbours(neighbour) == 3: y, x = neighbour y = y % self.y_grid x = x % self.x_grid neighbour = y, x grid_cp[neighbour] = 1 self.grid = grid_cp
Return the kind specified by a given __property__ key. Args: key: key whose kind name is requested. Returns: The kind specified by key.
def key_to_kind(cls, key): if key.kind() == Kind.KIND_NAME: return key.id() else: return key.parent().id()
Gets a recursive list of traits used by a class @param string $class Full class name @return array
private function getRecursiveTraits($class = null) { if (null == $class) { $class = get_class($this); } $reflection = new \ReflectionClass($class); $traits = array_keys($reflection->getTraits()); foreach ($traits as $trait) { $traits = array_merge($traits, $this->getRecursiveTraits($trait)); } if ($parent = $reflection->getParentClass()) { $traits = array_merge($traits, $this->getRecursiveTraits($parent->getName())); } return $traits; }
// SetMaxRecords sets the MaxRecords field's value.
func (s *DescribeSnapshotCopyGrantsInput) SetMaxRecords(v int64) *DescribeSnapshotCopyGrantsInput { s.MaxRecords = &v return s }
Check if the current position of the pointer is valid @return bool True if the pointer position is valid
public function valid() : bool { if ($this->pointer >= 0 && $this->pointer < count($this->members)) { return true; } return false; }
Creates a new {@link TopicProducer}. The producer accepts arbitrary objects and uses the Jackson object mapper to convert them into JSON and sends them as a text message.
public TopicProducer<Object> createTopicJsonProducer(final String topic) { Preconditions.checkState(connectionFactory != null, "connection factory was never injected!"); return new TopicProducer<Object>(connectionFactory, jmsConfig, topic, producerCallback); }
Dynamically add an array of setting items @param string $owner @param array $definitions
public function addSettingItems($owner, array $definitions) { foreach ($definitions as $code => $definition) { $this->addSettingItem($owner, $code, $definition); } }
Update brand group of parameters.
def update_brand(self) -> None: """""" self.update(path=URL_GET + GROUP.format(group=BRAND))
construct a string of space-delimited control keys based on properties of this class. @param bool $disconnect @return string
protected function getControlKey($disconnect = false) { $key = ''; if ($disconnect) { return "*immed"; } /* if(?) *justproc if(?) *debug if(?) *debugproc if(?) *nostart if(?) *rpt*/ // Idle timeout supported by XMLSERVICE 1.62 // setting idle for *sbmjob protects the time taken by program calls // Do that with *idle(30/kill) or whatever the time in seconds. if (trim($this->getOption('idleTimeout')) != '') { $idleTimeout = $this->getOption('idleTimeout'); $key .= " *idle($idleTimeout/kill)"; // ends idle only, but could end MSGW with *call(30/kill) } // if cdata requested, request it. XMLSERVICE will then wrap all output in CDATA tags. if ($this->getOption('cdata')) { $key .= " *cdata"; } /* stateless calls in stored procedure job * * Add *here, which will run everything inside the current PHP/transport job * without spawning or submitting a separate XTOOLKIT job. */ if ($this->isStateless()) { $key .= " *here"; } else { // not stateless, so could make sense to supply *sbmjob parameters for spawning a separate job. if (trim($this->getOption('sbmjobParams')) != '') { $sbmjobParams = $this->getOption('sbmjobParams'); $key .= " *sbmjob($sbmjobParams)"; } } // if internal XMLSERVICE tracing, into database table XMLSERVLOG/LOG, is desired if ($this->getOption('trace')) { $key .= " *log"; } // directive not to run any program, but to parse XML and return parsed output, including dim/dou. if ($this->getOption('parseOnly')) { $key .= " *test"; // add a debugging level (1-9) to the parse, to make *test(n) where n is the debugging level if ($parseDebugLevel = $this->getOption('parseDebugLevel')) { $key .= "($parseDebugLevel)"; } } // return XMLSERVICE version/license information (no XML calls) if ($this->getOption('license')) { $key .= " *license"; } // check proc call speed (no XML calls) if ($this->getOption('transport')) { $key .= " *justproc"; } // get performance of last call data (no XML calls) if ($this->getOption('performance')) { $key .= " *rpt"; } // *fly is number of ticks of each operation. *nofly is the default if ($this->getOption('timeReport')) { $key .= " *fly"; } // PASE CCSID for <sh> type of functions such as WRKACTJOB ('system' command in PASE) if ($paseCcsid = $this->getOption('paseCcsid')) { $key .= " *pase($paseCcsid)"; } // allow custom control keys if ($this->getOption('customControl')) { $key .= " {$this->getOption('customControl')}"; } return trim($key); // trim off any extra blanks on beginning or end }
Need to refactor, fukken complicated conditions.
def check_symbol_to_proc return unless method_call.block_argument_names.count == 1 return if method_call.block_body.nil? return unless method_call.block_body.sexp_type == :call return if method_call.arguments.count > 0 body_method_call = MethodCall.new(method_call.block_body) return unless body_method_call.arguments.count.zero? return if body_method_call.has_block? return unless body_method_call.receiver.name == method_call.block_argument_names.first add_offense(:block_vs_symbol_to_proc) end
Helper method to lookup a DAO if it has already been associated with the table-config. Otherwise this returns null.
public synchronized static <D extends Dao<T, ?>, T> D lookupDao(ConnectionSource connectionSource, DatabaseTableConfig<T> tableConfig) { if (connectionSource == null) { throw new IllegalArgumentException("connectionSource argument cannot be null"); } TableConfigConnectionSource key = new TableConfigConnectionSource(connectionSource, tableConfig); Dao<?, ?> dao = lookupDao(key); if (dao == null) { return null; } else { @SuppressWarnings("unchecked") D castDao = (D) dao; return castDao; } }
// Provided for compatibility with the Transformer interface. Since Caser has no // special treatment of bytes, the bytes are converted to and from strings. // Will treat the entirety of src as ONE variable name.
func (c Caser) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { nSrc = len(src) // Always read all the bytes of src result := c.Bytes(src) if len(result) > len(dst) { err = transform.ErrShortDst } nDst = copy(dst, result) return }
Creates (or updates) a new ProjectStatus for the given build and returns it.
def create_or_update(cls, build): test_summary = build.test_summary metrics_summary = MetricsSummary(build) now = timezone.now() test_runs_total = build.test_runs.count() test_runs_completed = build.test_runs.filter(completed=True).count() test_runs_incomplete = build.test_runs.filter(completed=False).count() regressions = None fixes = None previous_build = Build.objects.filter( status__finished=True, datetime__lt=build.datetime, project=build.project, ).order_by('datetime').last() if previous_build is not None: comparison = TestComparison(previous_build, build) if comparison.regressions: regressions = yaml.dump(comparison.regressions) if comparison.fixes: fixes = yaml.dump(comparison.fixes) finished, _ = build.finished data = { 'tests_pass': test_summary.tests_pass, 'tests_fail': test_summary.tests_fail, 'tests_xfail': test_summary.tests_xfail, 'tests_skip': test_summary.tests_skip, 'metrics_summary': metrics_summary.value, 'has_metrics': metrics_summary.has_metrics, 'last_updated': now, 'finished': finished, 'test_runs_total': test_runs_total, 'test_runs_completed': test_runs_completed, 'test_runs_incomplete': test_runs_incomplete, 'regressions': regressions, 'fixes': fixes } status, created = cls.objects.get_or_create(build=build, defaults=data) if not created and test_summary.tests_total >= status.tests_total: # XXX the test above for the new total number of tests prevents # results that arrived earlier, but are only being processed now, # from overwriting a ProjectStatus created by results that arrived # later but were already processed. status.tests_pass = test_summary.tests_pass status.tests_fail = test_summary.tests_fail status.tests_xfail = test_summary.tests_xfail status.tests_skip = test_summary.tests_skip status.metrics_summary = metrics_summary.value status.has_metrics = metrics_summary.has_metrics status.last_updated = now finished, _ = build.finished status.finished = finished status.build = build status.test_runs_total = test_runs_total status.test_runs_completed = test_runs_completed status.test_runs_incomplete = test_runs_incomplete status.regressions = regressions status.fixes = fixes status.save() return status
Static pressure. Args: msg (String): 28 bytes hexadecimal message string Returns: int: static pressure in hPa
def p44(msg): d = hex2bin(data(msg)) if d[34] == '0': return None p = bin2int(d[35:46]) # hPa return p
Trace TCP flows. Keyword arguments: * fout -- str, output path * format -- str, output format * byteorder -- str, output file byte order * nanosecond -- bool, output nanosecond-resolution file flag
def trace(fout=None, format=None, byteorder=sys.byteorder, nanosecond=False): str_check(fout or '', format or '') return TraceFlow(fout=fout, format=format, byteorder=byteorder, nanosecond=nanosecond)
Sets the URL to navigate to when the menu item is invoked. @param url the url to set.
public void setUrl(final String url) { MenuItemModel model = getOrCreateComponentModel(); model.url = url; model.action = null; }
// SetSecurityGroupArns sets the SecurityGroupArns field's value.
func (s *Ec2Config) SetSecurityGroupArns(v []*string) *Ec2Config { s.SecurityGroupArns = v return s }
Does not perform {@link PrivilegedAction} unless necessary. @param javaClass @param fieldName @return a field from the class @throws NoSuchMethodException
static Field lookupField(Class<?> javaClass, String fieldName) throws NoSuchFieldException { if (System.getSecurityManager() != null) { try { return AccessController.doPrivileged(new FieldLookupAction(javaClass, fieldName)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchFieldException) { throw (NoSuchFieldException) e.getCause(); } throw new WeldException(e.getCause()); } } else { return FieldLookupAction.lookupField(javaClass, fieldName); } }
migrate the retry jobs of a queue @param string $queue @return array
protected function migrateRetryJobs($queue) { $luaScript = <<<LUA -- Get all of the jobs with an expired "score"... local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1]) -- If we have values in the array, we will remove them from the first queue -- and add them onto the destination queue in chunks of 100, which moves -- all of the appropriate jobs onto the destination queue very safely. if(next(val) ~= nil) then redis.call('zremrangebyrank', KEYS[1], 0, #val - 1) for i = 1, #val, 100 do redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val))) end end return val LUA; return $this->client->eval( $luaScript, 2, $this->getRetryZsetNameWithPrefix($queue), $this->getQueueNameWithPrefix($queue), time() ); }
Dump the payload to JSON
def jsonify_payload(self): # Assume already json serialized if isinstance(self.payload, string_types): return self.payload return json.dumps(self.payload, cls=StandardJSONEncoder)
Get system backtrace in formated view @param bool $trace Custom php backtrace @param bool $addObject Show objects in result @return JBDump
public static function trace($trace = null, $addObject = false) { if (!self::isDebug()) { return false; } $_this = self::i(); $trace = $trace ? $trace : debug_backtrace($addObject); unset($trace[0]); $result = $_this->convertTrace($trace, $addObject); return $_this->dump($result, '! backtrace !'); }
Get a short value from the form, and place it in <code>attribute</code>. @param name attribute name @param attribute attribute to put value @since 1.11.1
@Api public void getValue(String name, ShortAttribute attribute) { attribute.setValue(toShort(formWidget.getValue(name))); }
Submits the {@link org.apache.gobblin.metrics.GobblinTrackingEvent} to the {@link org.apache.gobblin.metrics.MetricContext}. @param name Name of the event. @param additionalMetadata Additional metadata to be added to the event.
public void submit(String name, Map<String, String> additionalMetadata) { if(this.metricContext.isPresent()) { Map<String, String> finalMetadata = Maps.newHashMap(this.metadata); if(!additionalMetadata.isEmpty()) { finalMetadata.putAll(additionalMetadata); } // Timestamp is set by metric context. this.metricContext.get().submitEvent(new GobblinTrackingEvent(0l, this.namespace, name, finalMetadata)); } }
// FallbackAddr is a functional option that allows callers of NewInvoice to set // the Invoice's fallback on-chain address that can be used for payment in case // the Lightning payment fails
func FallbackAddr(fallbackAddr btcutil.Address) func(*Invoice) { return func(i *Invoice) { i.FallbackAddr = fallbackAddr } }
Get our daemon script path.
def get_manager_cmd(self): """""" cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py")) assert os.path.exists(cmd) return cmd
// SetMaxHumanLabeledObjectCount sets the MaxHumanLabeledObjectCount field's value.
func (s *LabelingJobStoppingConditions) SetMaxHumanLabeledObjectCount(v int64) *LabelingJobStoppingConditions { s.MaxHumanLabeledObjectCount = &v return s }
Create a default {@link FeatureInfoWidget} with a {@link ZoomToObjectAction} to allow zooming to selected features. @param mapPresenter The map presenter used by the action(s). @return A feature info widget with actions.
public FeatureInfoWithActions getFeatureInfoWidgetWithActions(MapPresenter mapPresenter) { FeatureInfoWithActions widgetWithActions = new FeatureInfoWithActions(); widgetWithActions.addHasFeature(new ZoomToObjectAction(mapPresenter)); return widgetWithActions; }
// SetError sets the Error field's value.
func (s *TaskFailedEventDetails) SetError(v string) *TaskFailedEventDetails { s.Error = &v return s }
Access the Monitor Twilio Domain :returns: Monitor Twilio Domain :rtype: twilio.rest.monitor.Monitor
def monitor(self): if self._monitor is None: from twilio.rest.monitor import Monitor self._monitor = Monitor(self) return self._monitor
// ExecuteRaw receives, parse and executes raw source template contents // it's super-simple function without options and funcs, it's not used widely // implements the EngineRawExecutor interface
func (p *Engine) ExecuteRaw(src string, wr io.Writer, binding interface{}) (err error) { set := pongo2.NewSet("", pongo2.DefaultLoader) set.Globals = getPongoContext(p.Config.Globals) tmpl, err := set.FromString(src) if err != nil { return err } return tmpl.ExecuteWriter(getPongoContext(binding), wr) }
Returns a parameter value in the specified array, if not in, returns the first element instead @param string $name The parameter name @param array $array The array to be search @return mixed The parameter value
public function getInArray($name, array $array) { $value = $this->get($name); return in_array($value, $array) ? $value : $array[key($array)]; }
Sets metainfo properties as JCR properties to node.
private void setJCRProperties(NodeImpl parent, Properties props) throws Exception { if (!parent.isNodeType("dc:elementSet")) { parent.addMixin("dc:elementSet"); } ValueFactory vFactory = parent.getSession().getValueFactory(); LocationFactory lFactory = parent.getSession().getLocationFactory(); for (Entry entry : props.entrySet()) { QName qname = (QName)entry.getKey(); JCRName jcrName = lFactory.createJCRName(new InternalQName(qname.getNamespace(), qname.getName())); PropertyDefinitionData definition = parent .getSession() .getWorkspace() .getNodeTypesHolder() .getPropertyDefinitions(jcrName.getInternalName(), ((NodeData)parent.getData()).getPrimaryTypeName(), ((NodeData)parent.getData()).getMixinTypeNames()).getAnyDefinition(); if (definition != null) { if (definition.isMultiple()) { Value[] values = {createValue(entry.getValue(), vFactory)}; parent.setProperty(jcrName.getAsString(), values); } else { Value value = createValue(entry.getValue(), vFactory); parent.setProperty(jcrName.getAsString(), value); } } } }
Get profiles grouped by account and webproperty TODO Handle "(403) User does not have any Google Analytics account." @return array
protected function getGroupedProfiles() { $this->analytics->requireAuthentication(); $groupedProfiles = []; $accounts = $this->analytics->management_accounts->listManagementAccounts(); foreach ($accounts as $account) { $groupedProfiles[$account->getId()]['label'] = $account->getName(); $groupedProfiles[$account->getId()]['items'] = []; } $webproperties = $this->analytics->management_webproperties->listManagementWebproperties('~all'); $webpropertiesById = []; foreach ($webproperties as $webproperty) { $webpropertiesById[$webproperty->getId()] = $webproperty; } $profiles = $this->analytics->management_profiles->listManagementProfiles('~all', '~all'); foreach ($profiles as $profile) { if (isset($webpropertiesById[$profile->getWebpropertyId()])) { $webproperty = $webpropertiesById[$profile->getWebpropertyId()]; $groupedProfiles[$profile->getAccountId()]['items'][$profile->getId()] = ['label' => $webproperty->getName() . ' > ' . $profile->getName(), 'value' => $profile->getId()]; } } return $groupedProfiles; }
// addValueToMap adds the given value to the map on which the method is run. // This allows us to merge maps such as {foo: {bar: baz}} and {foo: {baz: faz}} // into {foo: {bar: baz, baz: faz}}.
func addValueToMap(keys []string, value interface{}, target map[string]interface{}) { next := target for i := range keys { // If we are on last key set or overwrite the val. if i == len(keys)-1 { next[keys[i]] = value break } if iface, ok := next[keys[i]]; ok { switch typed := iface.(type) { case map[string]interface{}: // If we already had a map inside, keep // stepping through. next = typed default: // If we didn't, then overwrite value // with a map and iterate with that. m := map[string]interface{}{} next[keys[i]] = m next = m } continue } // Otherwise, it wasn't present, so make it and step // into. m := map[string]interface{}{} next[keys[i]] = m next = m } }
// Run parses arguments from the command line and passes them to RunCommand.
func (s *Service) Run() { flag.Usage = s.Usage flag.Parse() args := flag.Args() if len(args) == 0 && s.defaultCommand != "" { args = append([]string{s.defaultCommand}, args...) } if len(args) == 0 { s.Usage() BootPrintln() return } err := s.RunCommand(args[0], args[1:]...) if err != nil { panic(err) } }
store one item in database
def _put_one(self, item): ''' ''' # prepare values values = [] for k, v in item.items(): if k == '_id': continue if 'dblite_serializer' in item.fields[k]: serializer = item.fields[k]['dblite_serializer'] v = serializer.dumps(v) if v is not None: v = sqlite3.Binary(buffer(v)) values.append(v) # check if Item is new => update it if '_id' in item: fieldnames = ','.join(['%s=?' % f for f in item if f != '_id']) values.append(item['_id']) SQL = 'UPDATE %s SET %s WHERE rowid=?;' % (self._table, fieldnames) # new Item else: fieldnames = ','.join([f for f in item if f != '_id']) fieldnames_template = ','.join(['?' for f in item if f != '_id']) SQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self._table, fieldnames, fieldnames_template) try: self._cursor.execute(SQL, values) except sqlite3.OperationalError, err: raise RuntimeError('Item put() error, %s, SQL: %s, values: %s' % (err, SQL, values) ) except sqlite3.IntegrityError: raise DuplicateItem('Duplicate item, %s' % item) self._do_autocommit()
Computes the theta & phi angles of the vector. @memberof Vec3# @returns {object} ret @returns {Number} ret.theta - angle from the xz plane @returns {Number} ret.phi - angle from the y axis
function() { return { theta: Math.atan2(this.z, this.x), phi: Math.asin(this.y / this.length()) }; }
CArray with evenly spaced numbers over a specified interval. @param $start The starting value of the sequence. @param $stop The end value of the sequence @param int $num Number of samples to generate. Default is 50. @return \CArray
public static function linspace($start, $stop, int $num): \CArray { return parent::linspace($start, $stop, $num); }
// Digests hashes each segment of each key fragment 26 times and returns them. // Optionally takes the SpongeFunction to use. Default is Kerl.
func Digests(key Trits, spongeFunc ...SpongeFunction) (Trits, error) { var err error fragments := int(math.Floor(float64(len(key)) / KeyFragmentLength)) digests := make(Trits, fragments*HashTrinarySize) buf := make(Trits, HashTrinarySize) h := GetSpongeFunc(spongeFunc, kerl.NewKerl) defer h.Reset() // iterate through each key fragment for i := 0; i < fragments; i++ { keyFragment := key[i*KeyFragmentLength : (i+1)*KeyFragmentLength] // each fragment consists of 27 segments for j := 0; j < KeySegmentsPerFragment; j++ { copy(buf, keyFragment[j*HashTrinarySize:(j+1)*HashTrinarySize]) // hash each segment 26 times for k := 0; k < KeySegmentHashRounds; k++ { h.Absorb(buf) buf, err = h.Squeeze(HashTrinarySize) if err != nil { return nil, err } h.Reset() } copy(keyFragment[j*HashTrinarySize:], buf) } // hash the key fragment (which now consists of hashed segments) if err := h.Absorb(keyFragment); err != nil { return nil, err } buf, err := h.Squeeze(HashTrinarySize) if err != nil { return nil, err } copy(digests[i*HashTrinarySize:], buf) h.Reset() } return digests, nil }
Loading hparams from json; can also start from hparams if specified.
def create_hparams_from_json(json_path, hparams=None): """""" tf.logging.info("Loading hparams from existing json %s" % json_path) with tf.gfile.Open(json_path, "r") as f: hparams_values = json.load(f) # Prevent certain keys from overwriting the passed-in hparams. # TODO(trandustin): Remove this hack after registries are available to avoid # saving them as functions. hparams_values.pop("bottom", None) hparams_values.pop("loss", None) hparams_values.pop("name", None) hparams_values.pop("top", None) hparams_values.pop("weights_fn", None) new_hparams = hparam.HParams(**hparams_values) # Some keys are in new_hparams but not hparams, so we need to be more # careful than simply using parse_json() from HParams if hparams: # hparams specified, so update values from json for key in sorted(new_hparams.values().keys()): if hasattr(hparams, key): # Overlapped keys value = getattr(hparams, key) new_value = getattr(new_hparams, key) if value != new_value: # Different values tf.logging.info("Overwrite key %s: %s -> %s" % ( key, value, new_value)) setattr(hparams, key, new_value) else: hparams = new_hparams return hparams
Sort an collection by values using a user-defined comparison function @param \Closure $callback @param bool $save_keys maintain index association @return static
public function sortBy( \Closure $callback, bool $save_keys = true ) { $items = $this->items; $save_keys ? uasort($items, $callback) : usort($items, $callback); return new static($items); }
Attempts to upload the Docker image for a given tool to `DockerHub <https://hub.docker.com>`_.
def upload(self, tool: Tool) -> bool: return self.__installation.build.upload(tool.image)
SET CHECK @param string $name @param string $arg @return $this
public function checks($name, $arg = null) { if (empty($arg)) { $this->checks[] = $name; } else { $this->checks[$name] = $arg; } return $this; }
From a list of top level trees, return the list of contained class definitions
List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) { List<JCClassDecl> result = new ArrayList<>(); for (JCCompilationUnit t : trees) { for (JCTree def : t.defs) { if (def.hasTag(JCTree.Tag.CLASSDEF)) result.add((JCClassDecl)def); } } return result; }
--------------------------------------------------------------------------------------------
@Override public void configure(Configuration parameters) { // enforce sequential configuration() calls synchronized (CONFIGURE_MUTEX) { if (mapreduceInputFormat instanceof Configurable) { ((Configurable) mapreduceInputFormat).setConf(configuration); } } }
Parses the requested parameter from the given state.<p> @param state the state @param paramName the parameter name @return the parameter value
public static String getParamFromState(String state, String paramName) { String prefix = PARAM_SEPARATOR + paramName + PARAM_ASSIGN; if (state.contains(prefix)) { String result = state.substring(state.indexOf(prefix) + prefix.length()); if (result.contains(PARAM_SEPARATOR)) { result = result.substring(0, result.indexOf(PARAM_SEPARATOR)); } return CmsEncoder.decode(result, CmsEncoder.ENCODING_UTF_8); } return null; }
// intIf returns a if cnd is true, otherwise b
func intIf(cnd bool, a, b int) int { if cnd { return a } return b }
Create a writer builder for Ebi41InvoiceType. @return The builder and never <code>null</code>
@Nonnull public static EbInterfaceWriter <Ebi41InvoiceType> ebInterface41 () { final EbInterfaceWriter <Ebi41InvoiceType> ret = EbInterfaceWriter.create (Ebi41InvoiceType.class); ret.setNamespaceContext (EbInterface41NamespaceContext.getInstance ()); return ret; }
// SetKey sets the Key field's value.
func (s *GetObjectLegalHoldInput) SetKey(v string) *GetObjectLegalHoldInput { s.Key = &v return s }
// Range check string's length
func Range(str string, params ...string) bool { if len(params) == 2 { value, _ := ToFloat(str) min, _ := ToFloat(params[0]) max, _ := ToFloat(params[1]) return InRange(value, min, max) } return false }
Add command arguments
def add_arguments(self, parser): """""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', help= 'Supply the base currency as code or a settings variable name. ' 'The default is taken from settings CURRENCIES_BASE or SHOP_DEFAULT_CURRENCY, ' 'or the db, otherwise USD')
Grab values from the $_SERVER global. @param mixed $index The index that we will be searching for. @param boolean $xss_clean Whether we want to clean it or not. @since 1.0.0 @return mixed
public function server(string $index = '', $xss_clean = false) { return $this->fetchFromArray($_SERVER, $index, $xss_clean); }
Get a server by calling {@link AbstractServerPredicate#chooseRandomlyAfterFiltering(java.util.List, Object)}. The performance for this method is O(n) where n is number of servers to be filtered.
@Override public Server choose(Object key) { ILoadBalancer lb = getLoadBalancer(); Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key); if (server.isPresent()) { return server.get(); } else { return null; } }
Validate that an attribute is greater than another attribute. @param string $attribute @param mixed $value @param array $parameters @return bool
public function validateGt($attribute, $value, $parameters) { $this->requireParameterCount(1, $parameters, 'gt'); $comparedToValue = $this->getValue($parameters[0]); $this->shouldBeNumeric($attribute, 'Gt'); if (is_null($comparedToValue) && (is_numeric($value) && is_numeric($parameters[0]))) { return $this->getSize($attribute, $value) > $parameters[0]; } if (! $this->isSameType($value, $comparedToValue)) { return false; } return $this->getSize($attribute, $value) > $this->getSize($attribute, $comparedToValue); }
// SetErrorCode returns source code that sets return parameters.
func (r *Rets) SetErrorCode() string { const code = `if r0 != 0 { %s = %sErrno(r0) }` if r.Name == "" && !r.ReturnsError { return "" } if r.Name == "" { return r.useLongHandleErrorCode("r1") } if r.Type == "error" { return fmt.Sprintf(code, r.Name, syscalldot()) } s := "" switch { case r.Type[0] == '*': s = fmt.Sprintf("%s = (%s)(unsafe.Pointer(r0))", r.Name, r.Type) case r.Type == "bool": s = fmt.Sprintf("%s = r0 != 0", r.Name) default: s = fmt.Sprintf("%s = %s(r0)", r.Name, r.Type) } if !r.ReturnsError { return s } return s + "\n\t" + r.useLongHandleErrorCode(r.Name) }
// StartPlugins starts all plugins in the correct order.
func (co *Coordinator) StartPlugins() { // Launch routers for _, router := range co.routers { logrus.Debug("Starting ", reflect.TypeOf(router)) if err := router.Start(); err != nil { logrus.WithError(err).Errorf("Failed to start router of type '%s'", reflect.TypeOf(router)) } } // Launch producers co.state = coordinatorStateStartProducers for _, producer := range co.producers { producer := producer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(producer)) producer.Produce(co.producerWorker) }) } // Set final log target and purge the intermediate buffer if core.StreamRegistry.IsStreamRegistered(core.LogInternalStreamID) { // The _GOLLUM_ stream has listeners, so use LogConsumer to write to it if *flagLogColors == "always" { logrus.SetFormatter(logger.NewConsoleFormatter()) } logrusHookBuffer.SetTargetHook(co.logConsumer) logrusHookBuffer.Purge() } else { logrusHookBuffer.SetTargetWriter(logger.FallbackLogDevice) logrusHookBuffer.Purge() } // Launch consumers co.state = coordinatorStateStartConsumers for _, consumer := range co.consumers { consumer := consumer go tgo.WithRecoverShutdown(func() { logrus.Debug("Starting ", reflect.TypeOf(consumer)) consumer.Consume(co.consumerWorker) }) } }
Get a consumer for a connection.
def consumer(self, conn): """""" return Consumer( connection=conn, queue=self.queue.name, exchange=self.exchange.name, exchange_type=self.exchange.type, durable=self.exchange.durable, auto_delete=self.exchange.auto_delete, routing_key=self.routing_key, no_ack=self.no_ack, )
Returns the generator reactive power variable set.
def _get_qgen_var(self, generators, base_mva): Qg = array([g.q / base_mva for g in generators]) Qmin = array([g.q_min / base_mva for g in generators]) Qmax = array([g.q_max / base_mva for g in generators]) return Variable("Qg", len(generators), Qg, Qmin, Qmax)
Associations labels getter. @param \Cake\Datasource\RepositoryInterface $table Table instance @return mixed[]
public function getAssociationLabels(RepositoryInterface $table) : array { /** @var \Cake\ORM\Table */ $table = $table; $result = []; foreach ($table->associations() as $association) { if (!in_array($association->type(), $this->searchableAssociations)) { continue; } $result[$association->getName()] = Inflector::humanize(current((array)$association->getForeignKey())); } return $result; }
Return matched comments @param int $page @return array
public function get_comments($page = '') { global $DB, $CFG, $USER, $OUTPUT; if (!$this->can_view()) { return false; } if (!is_numeric($page)) { $page = 0; } $params = array(); $perpage = (!empty($CFG->commentsperpage))?$CFG->commentsperpage:15; $start = $page * $perpage; $ufields = user_picture::fields('u'); list($componentwhere, $component) = $this->get_component_select_sql('c'); if ($component) { $params['component'] = $component; } $sql = "SELECT $ufields, c.id AS cid, c.content AS ccontent, c.format AS cformat, c.timecreated AS ctimecreated FROM {comments} c JOIN {user} u ON u.id = c.userid WHERE c.contextid = :contextid AND c.commentarea = :commentarea AND c.itemid = :itemid AND $componentwhere ORDER BY c.timecreated DESC"; $params['contextid'] = $this->contextid; $params['commentarea'] = $this->commentarea; $params['itemid'] = $this->itemid; $comments = array(); $formatoptions = array('overflowdiv' => true, 'blanktarget' => true); $rs = $DB->get_recordset_sql($sql, $params, $start, $perpage); foreach ($rs as $u) { $c = new stdClass(); $c->id = $u->cid; $c->content = $u->ccontent; $c->format = $u->cformat; $c->timecreated = $u->ctimecreated; $c->strftimeformat = get_string('strftimerecentfull', 'langconfig'); $url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid)); $c->profileurl = $url->out(false); // URL should not be escaped just yet. $c->fullname = fullname($u); $c->time = userdate($c->timecreated, $c->strftimeformat); $c->content = format_text($c->content, $c->format, $formatoptions); $c->avatar = $OUTPUT->user_picture($u, array('size'=>18)); $c->userid = $u->id; $candelete = $this->can_delete($c->id); if (($USER->id == $u->id) || !empty($candelete)) { $c->delete = true; } $comments[] = $c; } $rs->close(); if (!empty($this->plugintype)) { // moodle module will filter comments $comments = plugin_callback($this->plugintype, $this->pluginname, 'comment', 'display', array($comments, $this->comment_param), $comments); } return $comments; }
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (ne *ne_IN) WeekdayWide(weekday time.Weekday) string { return ne.daysWide[weekday] }
/*! Returns the objects which have at least one keyword in common \return an array of eZContentObjectTreeNode instances, or null if the attribute is not stored yet
function relatedObjects() { $return = false; if ( $this->ObjectAttributeID ) { $return = array(); // Fetch words $db = eZDB::instance(); $wordArray = $db->arrayQuery( "SELECT * FROM ezkeyword_attribute_link WHERE objectattribute_id='" . $this->ObjectAttributeID ."' " ); $keywordIDArray = array(); // Fetch the objects which have one of these words foreach ( $wordArray as $word ) { $keywordIDArray[] = $word['keyword_id']; } $keywordCondition = $db->generateSQLINStatement( $keywordIDArray, 'keyword_id' ); if ( count( $keywordIDArray ) > 0 ) { $objectArray = $db->arrayQuery( "SELECT DISTINCT ezcontentobject_attribute.contentobject_id FROM ezkeyword_attribute_link, ezcontentobject_attribute WHERE $keywordCondition AND ezcontentobject_attribute.id = ezkeyword_attribute_link.objectattribute_id AND objectattribute_id <> '" . $this->ObjectAttributeID ."' " ); $objectIDArray = array(); foreach ( $objectArray as $object ) { $objectIDArray[] = $object['contentobject_id']; } if ( count( $objectIDArray ) > 0 ) { $aNodes = eZContentObjectTreeNode::findMainNodeArray( $objectIDArray ); foreach ( $aNodes as $key => $node ) { $theObject = $node->object(); if ( $theObject->canRead() ) { $return[] = $node; } } } } } return $return; }
Extract read and write part values to an object for SCALAR, SPECTRUM and IMAGE @param da @return array of primitives for SCALAR, array of primitives for SPECTRUM, array of primitives array of primitives for IMAGE @throws DevFailed
public static Object extract(final DeviceAttribute da) throws DevFailed { if (da == null) { throw DevFailedUtils.newDevFailed(ERROR_MSG_DA); } return InsertExtractFactory.getAttributeExtractor(da.getType()).extract(da); }
Add values for PromotionIds, return this. @param promotionIds New values to add. @return This instance.
public OrderItem withPromotionIds(String... values) { List<String> list = getPromotionIds(); for (String value : values) { list.add(value); } return this; }
Parses the element and subelements and parses any HTML enabled text to its original HTML form for rendering. :returns: Parsed HTML enabled text content. :rtype: str
def get_html_content(self): # Extract full element node content (including subelements) html_content = '' if hasattr(self, 'xml_element'): xml = self.xml_element content_list = ["" if xml.text is None else xml.text] def to_string(xml): if isinstance(xml, _Comment): return str(xml) else: return ElementTree.tostring(xml).decode('utf-8') content_list += [to_string(e) for e in xml.getchildren()] full_xml_content = "".join(content_list) # Parse tags to generate HTML valid content first_regex = r'html:' second_regex = r' xmlns:html=(["\'])(?:(?=(\\?))\2.)*?\1' html_content = re.sub(first_regex, '', re.sub(second_regex, '', full_xml_content)) return html_content
Get the list of files changed with the type of change for a given revision. Results are returned as a structured array. @param String $rev A valid changeset for this repo @return array List of file changes
public function getChangedFiles($rev) { $raw_changes = $this->execute('hg status --change ' . $rev); $this->repository_type = 'hg'; $changes = []; foreach ($raw_changes as $key => $change) { $exploded_change = explode(' ', $change); $changes[$key]['type'] = $exploded_change[0]; $changes[$key]['path'] = $exploded_change[1]; } return $changes; }
Returns the loaded behaviors and loads them if not done before @return array behaviors
public function getBehaviors() { if (null === $this->behaviors) { // find behaviors in composer.lock file $lock = $this->findComposerLock(); if (null === $lock) { $this->behaviors = []; } else { $this->behaviors = $this->loadBehaviors($lock); } // find behavior in composer.json (useful when developing a behavior) $json = $this->findComposerJson(); if (null !== $json) { $behavior = $this->loadBehavior(json_decode($json->getContents(), true)); if (null !== $behavior) { $this->behaviors[$behavior['name']] = $behavior; } } } return $this->behaviors; }
APIMethod: getCentroid Returns: {<OpenLayers.Geometry.Point>} The centroid of the collection
function() { if (this.components) { var len = this.components.length; if (len > 0 && len <= 2) { return this.components[0].clone(); } else if (len > 2) { var sumX = 0.0; var sumY = 0.0; var x0 = this.components[0].x; var y0 = this.components[0].y; var area = -1 * this.getArea(); if (area != 0) { for (var i = 0; i < len - 1; i++) { var b = this.components[i]; var c = this.components[i+1]; sumX += (b.x + c.x - 2 * x0) * ((b.x - x0) * (c.y - y0) - (c.x - x0) * (b.y - y0)); sumY += (b.y + c.y - 2 * y0) * ((b.x - x0) * (c.y - y0) - (c.x - x0) * (b.y - y0)); } var x = x0 + sumX / (6 * area); var y = y0 + sumY / (6 * area); } else { for (var i = 0; i < len - 1; i++) { sumX += this.components[i].x; sumY += this.components[i].y; } var x = sumX / (len - 1); var y = sumY / (len - 1); } return new OpenLayers.Geometry.Point(x, y); } else { return null; } } }
Returns bearing from (lat1, lon1) to (lat2, lon2) in degrees @param lat1 @param lon1 @param lat2 @param lon2 @return
public static final double bearing(double lat1, double lon1, double lat2, double lon2) { return Math.toDegrees(radBearing(lat1, lon1, lat2, lon2)); }
Return the flow rate with only minor losses. This function applies to both laminar and turbulent flows.
def flow_pipeminor(Diam, HeadLossExpans, KMinor): #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([HeadLossExpans, ">=0", "Headloss due to expansion"], [KMinor, ">0", "K minor"]) return (area_circle(Diam).magnitude * np.sqrt(2 * gravity.magnitude * HeadLossExpans / KMinor) )
Parse a run of ordinary characters, or a single character with a special meaning in markdown, as a plain string, adding to inlines.
function(inlines) { var m; if ((m = this.match(reMain))) { inlines.push({ t: 'Str', c: m }); return m.length; } else { return 0; } }
Assigns value to all unfilled feature variables. @param value @return
public SyntacticCategory assignAllFeatures(String value) { Set<Integer> featureVars = Sets.newHashSet(); getAllFeatureVariables(featureVars); Map<Integer, String> valueMap = Maps.newHashMap(); for (Integer var : featureVars) { valueMap.put(var, value); } return assignFeatures(valueMap, Collections.<Integer, Integer>emptyMap()); }
Return true if gate tensor is (almost) unitary
def almost_unitary(gate: Gate) -> bool: """""" res = (gate @ gate.H).asoperator() N = gate.qubit_nb return np.allclose(asarray(res), np.eye(2**N), atol=TOLERANCE)
Adds limit and offset to SQL statement. @param int $limit @param int $offset @return void
public function addLimitOffset(int $limit, int $offset): void { if ($limit === 0 && $offset === 0) { return; } if ($limit === 0 && $offset <> 0) { return; } if ($offset === 0) { $this->statement .= ' LIMIT ' . $limit; } else { $this->statement .= sprintf(' LIMIT %d, %d', $offset, $limit); } $this->statement .= PHP_EOL; }
Finds actions, angles and frequencies for box orbit. Takes a series of phase-space points from an orbit integration at times t and returns L = (act,ang,n_vec,toy_aa, pars) -- explained in find_actions() below.
def box_actions(results, times, N_matrix, ifprint): if(ifprint): print("\n=====\nUsing triaxial harmonic toy potential") t = time.time() # Find best toy parameters omega = toy.findbestparams_ho(results) if(ifprint): print("Best omega "+str(omega)+" found in "+str(time.time()-t)+" seconds") # Now find toy actions and angles AA = np.array([toy.angact_ho(i,omega) for i in results]) AA = AA[~np.isnan(AA).any(1)] if(len(AA)==0): return t = time.time() act = solver.solver(AA, N_matrix) if act==None: return if(ifprint): print("Action solution found for N_max = "+str(N_matrix)+", size "+str(len(act[0]))+" symmetric matrix in "+str(time.time()-t)+" seconds") np.savetxt("GF.Sn_box",np.vstack((act[1].T,act[0][3:])).T) ang = solver.angle_solver(AA,times,N_matrix,np.ones(3)) if(ifprint): print("Angle solution found for N_max = "+str(N_matrix)+", size "+str(len(ang))+" symmetric matrix in "+str(time.time()-t)+" seconds") # Just some checks if(len(ang)>len(AA)): print("More unknowns than equations") return act[0], ang, act[1], AA, omega
将map的属性映射到bean对象 @param target @param properties @throws BeanMappingException
public void populate(Object target, Map properties) throws BeanMappingException { BeanMappingParam param = new BeanMappingParam(); param.setSrcRef(properties); param.setTargetRef(target); param.setConfig(this.populateConfig); param.setProcesses(BeanMappingEnvironment.getBeanMapVps()); // 执行mapping处理 BeanMappingExecutor.execute(param); }
// getOrCreateAutopilotConfig is used to get the autopilot config, initializing it if necessary
func (s *Server) getOrCreateAutopilotConfig() *autopilot.Config { state := s.fsm.State() _, config, err := state.AutopilotConfig() if err != nil { s.logger.Printf("[ERR] autopilot: failed to get config: %v", err) return nil } if config != nil { return config } if !ServersMeetMinimumVersion(s.LANMembers(), minAutopilotVersion) { s.logger.Printf("[WARN] autopilot: can't initialize until all servers are >= %s", minAutopilotVersion.String()) return nil } config = s.config.AutopilotConfig req := structs.AutopilotSetConfigRequest{Config: *config} if _, err = s.raftApply(structs.AutopilotRequestType, req); err != nil { s.logger.Printf("[ERR] autopilot: failed to initialize config: %v", err) return nil } return config }
Set whether or not to display the bank @param bool $displayBank True if yes, false if no @return $this The current instance for a fluent interface.
public function setDisplayBank($displayBank = true) { $this->isBool($displayBank, 'displayBank'); $this->displayBank = $displayBank; return $this; }
// fullCompactionStrategy returns a compactionStrategy for higher level generations of TSM files. // It returns nil if there are no TSM files to compact.
func (e *Engine) fullCompactionStrategy(group CompactionGroup, optimize bool) *compactionStrategy { s := &compactionStrategy{ group: group, logger: e.logger.With(zap.String("tsm1_strategy", "full"), zap.Bool("tsm1_optimize", optimize)), fileStore: e.FileStore, compactor: e.Compactor, fast: optimize, engine: e, level: 5, tracker: e.compactionTracker, } if optimize { s.level = 4 } return s }
Render the modal template @since 1.0.0 @see \uix\ui\uix @access public @return string HTML of modals templates
public function modal_template() { $output = '<script type="text/html" id="' . esc_attr( $this->id() ) . '-components">'; foreach ( $this->modals as $modal ) { $label = $modal->struct['label']; $data = $modal->get_data(); $data_template = $this->drill_in( $data[ $modal->slug ], '{{@root' ); $modal->set_data( array( $modal->slug => $data_template ) ); $modal->render(); $setup = null; if ( count( $modal->child ) > 1 ) { $setup = ' data-setup="true" '; } $output .= '<button type="button" class="button uix-component-trigger" style="margin:12px 0 0 12px;" data-label="' . esc_attr( $modal->attributes['data-title'] ) . '" data-type="' . $modal->slug . '" ' . $setup . ' data-id="' . esc_attr( $modal->id() ) . '">' . $label . '</button> '; } $output .= '</script>'; return $output; }
Convert the input URI into a correctly formatted uri prefix. In the future, may also resolve d2 uris.
public static String resolveUriPrefix(URI serverURI) throws URISyntaxException { if (RESTLI_SCHEMES.contains(serverURI.getScheme())) { return new URI(serverURI.getScheme(), serverURI.getAuthority(), null, null, null).toString() + "/"; } throw new RuntimeException("Unrecognized scheme for URI " + serverURI); }
Writes the given {@link Object} to the {@link JsonWriter}. @throws IOException
private static void writeValue(Object value, JsonWriter writer) throws IOException { if (value == null) { writer.nullValue(); } else if (value instanceof Number) { writer.value((Number) value); } else if (value instanceof Boolean) { writer.value((Boolean) value); } else if (value instanceof List) { listToWriter((List) value, writer); } else if (value instanceof Map) { mapToWriter((Map) value, writer); } else if (value.getClass().isArray()) { arrayToWriter(value, writer); } else { writer.value(String.valueOf(value)); } }
Creates a procedure. @param string $name Procedure name @return $this
public function createProcedure($name) { $definition = array( 'parent' => $this->context, 'name' => $name, 'sources' => array(), 'workers' => array(), 'targets' => array(), 'children' => array(), ); $this->definitions[$name] = $definition; $this->context = $name; return $this; }
Converts a value from one unit to another. @param int $to unit to convert to @param mixed $val value to convert @return float converted value
protected function convert($to, $val) { $val = $this->parseValue($val); return base_convert($val, $this->unit, $to); }
// SetMaxResults sets the MaxResults field's value.
func (s *ListAlgorithmsInput) SetMaxResults(v int64) *ListAlgorithmsInput { s.MaxResults = &v return s }
The typed collection type. Contains only elements of the supplied class. @see ITypedCollection @param IType $elementType @param string $collectionClass @return CollectionType
public static function collectionOf(IType $elementType, string $collectionClass = ITypedCollection::class) : CollectionType { $elementTypeString = $elementType->asTypeString(); if (!isset(self::$collections[$collectionClass][$elementTypeString])) { self::$collections[$collectionClass][$elementTypeString] = new CollectionType($elementType, $collectionClass); } return self::$collections[$collectionClass][$elementTypeString]; }
-------------------------------------------------------------------------- TODO: move the code below to the core (?)
function computeGameStateOfTaskEnvironment(taskEnvironment) { const { pastActions, currentAction } = taskEnvironment; const initialState = getInitialGameState(taskEnvironment); let currentState = doActionMoves(initialState, pastActions); if (currentAction !== null) { currentState = doAction(currentState, currentAction); } /* const someActionsTaken = taskEnvironment.pastActions.length > 0; // TODO: DRY identical someActionsTaken computation at two places (or avoid // finalGameStage computation altogether, it feels like a hack...) const finalGameStage = decideGameStage( currentState.fields, currentState.spaceship, taskEnvironment.interpreting, someActionsTaken); return { ...currentState, stage: finalGameStage }; */ return currentState; }
The :meth:`sqlalchemy.crud.updating.upsert_all` function in ORM syntax. :param engine: an engine created by``sqlalchemy.create_engine``. :param obj_or_data: single object or list of object
def upsert_all(cls, engine, obj_or_data): cls.update_all( engine=engine, obj_or_data=obj_or_data, upsert=True, )
// SetBody sets the Body field's value.
func (s *ADMMessage) SetBody(v string) *ADMMessage { s.Body = &v return s }
Cleas the cache of a specific post id @param integer $postId Post id to clear @return boolean
public static function clearCache($postId, $post) { if (wp_is_post_revision($postId) || get_post_status($postId) != 'publish') { return false; } wp_cache_delete($postId, self::getKeyGroup()); wp_cache_delete($post->post_type, self::getKeyGroup()); // Empty post type for all sites in network (?) if (function_exists('is_multisite') && is_multisite() && apply_filters('Municipio\Cache\EmptyForAllBlogs', false, $post)) { $blogs = get_sites(); foreach ($blogs as $blog) { wp_cache_delete($post->post_type, self::getKeyGroup($blog->blog_id)); } } return true; }
Synchronizes the values for the given element path.<p> @param cms the cms context @param elementPath the element path @param skipPaths the paths to skip @param sourceLocale the source locale
private void synchronizeElement( CmsObject cms, String elementPath, Collection<String> skipPaths, Locale sourceLocale) { if (elementPath.contains("/")) { String parentPath = CmsXmlUtils.removeLastXpathElement(elementPath); List<I_CmsXmlContentValue> parentValues = getValuesByPath(parentPath, sourceLocale); String elementName = CmsXmlUtils.getLastXpathElement(elementPath); for (I_CmsXmlContentValue parentValue : parentValues) { String valuePath = CmsXmlUtils.concatXpath(parentValue.getPath(), elementName); boolean skip = false; for (String skipPath : skipPaths) { if (valuePath.startsWith(skipPath)) { skip = true; break; } } if (!skip) { if (hasValue(valuePath, sourceLocale)) { List<I_CmsXmlContentValue> subValues = getValues(valuePath, sourceLocale); removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale); for (I_CmsXmlContentValue value : subValues) { if (value.isSimpleType()) { setValueForOtherLocales(cms, value, CmsXmlUtils.removeLastXpathElement(valuePath)); } else { List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value); for (I_CmsXmlContentValue simpleValue : simpleValues) { setValueForOtherLocales(cms, simpleValue, parentValue.getPath()); } } } } else { removeValuesInOtherLocales(valuePath, sourceLocale); } } } } else { if (hasValue(elementPath, sourceLocale)) { List<I_CmsXmlContentValue> subValues = getValues(elementPath, sourceLocale); removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale); for (I_CmsXmlContentValue value : subValues) { if (value.isSimpleType()) { setValueForOtherLocales(cms, value, null); } else { List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value); for (I_CmsXmlContentValue simpleValue : simpleValues) { setValueForOtherLocales(cms, simpleValue, null); } } } } else { removeValuesInOtherLocales(elementPath, sourceLocale); } } }
// UnmarshalTOML implements toml.UnmarshalerRec.
func (l *Netlist) UnmarshalTOML(fn func(interface{}) error) error { var masks []string if err := fn(&masks); err != nil { return err } for _, mask := range masks { _, n, err := net.ParseCIDR(mask) if err != nil { return err } *l = append(*l, *n) } return nil }
See the {@link debug} property for more information. @access private @return void
private function _write_log($daily = false, $hourly = false, $backtrace = false) { // if we are using a callback function to handle logs if (is_callable($this->log_path) && !isset($this->log_path_is_function)) // set flag $this->log_path_is_function = true; // if we are writing logs to a file else { // set flag $this->log_path_is_function = false; $pathinfo = pathinfo($this->log_path); // if log_path is given as full path to a file, together with extension if (isset($pathinfo['filename']) && isset($pathinfo['extension'])) { // use those values $file_name = $pathinfo['dirname'] . '/' . $pathinfo['filename']; $extension = '.' . $pathinfo['extension']; // otherwise } else { // the file name is "log" and the extension is ".txt" $file_name = rtrim($this->log_path, '/\\') . '/log'; $extension = '.txt'; } // if $hourly is set to TRUE, $daily *must* be true if ($hourly) $daily = true; // are we writing daily logs? // (suppress "strict standards" warning for PHP 5.4+) $file_name .= ($daily ? '-' . @date('Ymd') : ''); // are we writing hourly logs? // (suppress "strict standards" warning for PHP 5.4+) $file_name .= ($hourly ? '-' . @date('H') : ''); // log file's extension $file_name .= $extension; } // all the labels that may be used in a log entry $labels = array( strtoupper($this->language['date']), strtoupper('query'), strtoupper($this->language['execution_time']), strtoupper($this->language['warning']), strtoupper($this->language['error']), strtoupper($this->language['from_cache']), strtoupper($this->language['yes']), strtoupper($this->language['no']), strtoupper($this->language['backtrace']), strtoupper($this->language['file']), strtoupper($this->language['line']), strtoupper($this->language['function']), strtoupper($this->language['unbuffered']), ); // determine the longest label (for proper indenting) $longest_label_length = 0; // iterate through the labels foreach ($labels as $label) // if the label is longer than the longest label so far if (strlen($label) > $longest_label_length) // this is the longes label, so far // we use utf8_decode so that strlen counts correctly with accented chars $longest_label_length = strlen(utf8_decode($label)); $longest_label_length--; // the following regular expressions strips newlines and indenting from the MySQL string, so that // we have it in a single line $pattern = array( "/\s*(.*)\n|\r/", "/\n|\r/" ); $replace = array( ' $1', ' ' ); // if we are using a callback function for logs or we are writing the logs to a file and we can create/write to the log file if ($this->log_path_is_function || $handle = @fopen($file_name, 'a+')) { // we need to show both successful and unsuccessful queries $sections = array('successful-queries', 'unsuccessful-queries'); // iterate over the sections we need to show foreach ($sections as $section) { // if there are any queries in the section if (isset($this->debug_info[$section])) { // iterate through the debug information foreach ($this->debug_info[$section] as $debug_info) { // the output $output = // date $labels[0] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[0])), ' ', STR_PAD_RIGHT) . ': ' . @date('Y-m-d H:i:s') . "\n" . // query $labels[1] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[1])), ' ', STR_PAD_RIGHT) . ': ' . trim(preg_replace($pattern, $replace, $debug_info['query'])) . "\n" . // if execution time is available // (is not available for unsuccessful queries) (isset($debug_info['execution_time']) ? $labels[2] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[2])), ' ', STR_PAD_RIGHT) . ': ' . $this->_fix_pow($debug_info['execution_time']) . ' ' . $this->language['seconds'] . "\n" : '') . // if there is a warning message (isset($debug_info['warning']) && $debug_info['warning'] != '' ? $labels[3] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[3])), ' ', STR_PAD_RIGHT) . ': ' . strip_tags($debug_info['warning']) . "\n" : '') . // if there is an error message (isset($debug_info['error']) && $debug_info['error'] != '' ? $labels[4] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[4])), ' ', STR_PAD_RIGHT) . ': ' . $debug_info['error'] . "\n" : '') . // if not an action query, show whether the query was returned from the cache or was executed (isset($debug_info['affected_rows']) && $debug_info['affected_rows'] === false && isset($debug_info['from_cache']) && $debug_info['from_cache'] != 'nocache' ? $labels[5] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[5])), ' ', STR_PAD_RIGHT) . ': ' . $labels[6] . "\n" : '') . // if query was an unbuffered one (isset($debug_info['unbuffered']) && $debug_info['unbuffered'] ? $labels[12] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[12])), ' ', STR_PAD_RIGHT) . ': ' . $labels[6] . "\n" : ''); // if we are writing the logs to a file, write to the log file if (!$this->log_path_is_function) fwrite($handle, print_r($output, true)); $backtrace_output = ''; // if backtrace information should be written to the log file if ($backtrace) { $backtrace_output = $labels[8] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[8])), ' ', STR_PAD_RIGHT) . ':' . "\n"; // if we are writing the logs to a file, write to the log file if (!$this->log_path_is_function) fwrite($handle, print_r($backtrace_output, true)); // handle full backtrace info foreach ($debug_info['backtrace'] as $backtrace) { // output $tmp = "\n" . $labels[9] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[9])), ' ', STR_PAD_RIGHT) . ': ' . $backtrace[$this->language['file']] . "\n" . $labels[10] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[10])), ' ', STR_PAD_RIGHT) . ': ' . $backtrace[$this->language['line']] . "\n" . $labels[11] . str_pad('', $longest_label_length - strlen(utf8_decode($labels[11])), ' ', STR_PAD_RIGHT) . ': ' . $backtrace[$this->language['function']] . "\n"; // if we are writing the logs to a file, write to the log file if (!$this->log_path_is_function) fwrite($handle, print_r($tmp, true)); // otherwise, add to the string else $backtrace_output .= $tmp; } } // if we are writing the logs to a file, finish writing to the log file by adding a bottom border if (!$this->log_path_is_function) fwrite($handle, str_pad('', $longest_label_length + 1, '-', STR_PAD_RIGHT) . "\n"); // if we are using a callback to manage logs, pass log information to the log file else call_user_func_array($this->log_path, array($output, $backtrace_output)); } } } // if we are writing the logs to a file, close the log file if (!$this->log_path_is_function) fclose($handle); // if log file could not be created/opened } else trigger_error($this->language['could_not_write_to_log'], E_USER_ERROR); }
Attempts to extract a name of a missing class loader dependency from an exception such as {@link NoClassDefFoundError} or {@link ClassNotFoundException}.
public static String getNameOfMissingClassLoaderDependency(Throwable e) { if (e instanceof NoClassDefFoundError) { // NoClassDefFoundError sometimes includes CNFE as the cause. Since CNFE has a better formatted class name // and may also include classloader info, we prefer CNFE's over NCDFE's message. if (e.getCause() instanceof ClassNotFoundException) { return getNameOfMissingClassLoaderDependency(e.getCause()); } if (e.getMessage() != null) { return e.getMessage().replace('/', '.'); } } if (e instanceof ClassNotFoundException) { if (e.getMessage() != null) { return e.getMessage(); } } if (e.getCause() != null) { return getNameOfMissingClassLoaderDependency(e.getCause()); } else { return "[unknown]"; } }
Serialize to a non-circular Javascript object
function(obj) { if (obj instanceof Cell) { return { inside: obj.inside }; } else { return { back : serialize(obj.back), front : serialize(obj.front), plane: obj.plane, shp: obj.shp, complemented: obj.complemented, }; } }
Get option for output (cloned option and inner info removed) @public @return {Object}
function () { var option = clone(this.option); each(option, function (opts, mainType) { if (ComponentModel.hasClass(mainType)) { var opts = modelUtil.normalizeToArray(opts); for (var i = opts.length - 1; i >= 0; i--) { // Remove options with inner id. if (modelUtil.isIdInner(opts[i])) { opts.splice(i, 1); } } option[mainType] = opts; } }); delete option[OPTION_INNER_KEY]; return option; }
// CreateNonce generates a nonce using the common/crypto package.
func CreateNonce() ([]byte, error) { nonce, err := crypto.GetRandomNonce() return nonce, errors.WithMessage(err, "error generating random nonce") }

Dataset Card for CodeSearchNet

This dataset is a collection of comment-code pairs of various programming languages. See code_search_net for additional information. This dataset can be used directly with Sentence Transformers to train embedding models.

Dataset Subsets

pair subset

  • Columns: "comment", "code"
  • Column types: str, str
  • Examples:
    {
      'comment': 'Computes the new parent id for the node being moved.\n\n@return int',
      'code': "protected function parentId()\n\t{\n\t\tswitch ( $this->position )\n\t\t{\n\t\t\tcase 'root':\n\t\t\t\treturn null;\n\n\t\t\tcase 'child':\n\t\t\t\treturn $this->target->getKey();\n\n\t\t\tdefault:\n\t\t\t\treturn $this->target->getParentId();\n\t\t}\n\t}",
    }
    
  • Collection strategy: Reading the Code Search Net dataset from embedding-training-data.
  • Deduplified: No
Downloads last month
92

Collection including sentence-transformers/codesearchnet