comment
stringlengths
16
255
code
stringlengths
52
3.87M
Returns the region name for the current language. @return string|null
public function getRegionName(): ?string { return $this->region ? (static::regions()[$this->region] ?? $this->region) : null; }
This method returns a stream of RDF triples associated with this target resource @param limit is the number of child resources returned in the response, -1 for all @param resource the fedora resource @return {@link RdfStream}
private RdfStream getResourceTriples(final int limit, final FedoraResource resource) { final PreferTag returnPreference; if (prefer != null && prefer.hasReturn()) { returnPreference = prefer.getReturn(); } else if (prefer != null && prefer.hasHandling()) { returnPreference = prefer.getHandling(); } else { returnPreference = PreferTag.emptyTag(); } final LdpPreferTag ldpPreferences = new LdpPreferTag(returnPreference); final Predicate<Triple> tripleFilter = ldpPreferences.prefersServerManaged() ? x -> true : IS_MANAGED_TRIPLE.negate(); final List<Stream<Triple>> streams = new ArrayList<>(); if (returnPreference.getValue().equals("minimal")) { streams.add(getTriples(resource, of(PROPERTIES, MINIMAL)).filter(tripleFilter)); // Mementos already have the server managed properties in the PROPERTIES category // since mementos are immutable and these triples are no longer managed if (ldpPreferences.prefersServerManaged() && !resource.isMemento()) { streams.add(getTriples(resource, of(SERVER_MANAGED, MINIMAL))); } } else { streams.add(getTriples(resource, PROPERTIES).filter(tripleFilter)); // Additional server-managed triples about this resource // Mementos already have the server managed properties in the PROPERTIES category // since mementos are immutable and these triples are no longer managed if (ldpPreferences.prefersServerManaged() && !resource.isMemento()) { streams.add(getTriples(resource, SERVER_MANAGED)); } // containment triples about this resource if (ldpPreferences.prefersContainment()) { if (limit == -1) { streams.add(getTriples(resource, LDP_CONTAINMENT)); } else { streams.add(getTriples(resource, LDP_CONTAINMENT).limit(limit)); } } // LDP container membership triples for this resource if (ldpPreferences.prefersMembership()) { streams.add(getTriples(resource, LDP_MEMBERSHIP)); } // Include inbound references to this object if (ldpPreferences.prefersReferences()) { streams.add(getTriples(resource, INBOUND_REFERENCES)); } // Embed the children of this object if (ldpPreferences.prefersEmbed()) { streams.add(getTriples(resource, EMBED_RESOURCES)); } } final RdfStream rdfStream = new DefaultRdfStream( asNode(resource), streams.stream().reduce(empty(), Stream::concat)); if (httpTripleUtil != null && ldpPreferences.prefersServerManaged()) { return httpTripleUtil.addHttpComponentModelsForResourceToStream(rdfStream, resource, uriInfo, translator()); } return rdfStream; }
R(n) ratio expected from theory for given noise type alpha = b + 2
def rn_theory(af, b): # From IEEE1139-2008 # alpha beta ADEV_mu MDEV_mu Rn_mu # -2 -4 1 1 0 Random Walk FM # -1 -3 0 0 0 Flicker FM # 0 -2 -1 -1 0 White FM # 1 -1 -2 -2 0 Flicker PM # 2 0 -2 -3 -1 White PM # (a=-3 flicker walk FM) # (a=-4 random run FM) if b==0: return pow(af,-1) elif b==-1: # f_h = 0.5/tau0 (assumed!) # af = tau/tau0 # so f_h*tau = 0.5/tau0 * af*tau0 = 0.5*af avar = (1.038+3*np.log(2*np.pi*0.5*af)) / (4.0*pow(np.pi,2)) mvar = 3*np.log(256.0/27.0)/(8.0*pow(np.pi,2)) return mvar/avar else: return pow(af,0)
Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool
def equals(self, rhs): for comparator in self._comparators: if comparator.equals(rhs): return True return False
// SignRS384 signs data with rsa-sha384
func SignRS384(r *rsa.PrivateKey, data []byte) ([]byte, error) { h := sha512.New384() h.Write(data) d := h.Sum(nil) return rsa.SignPKCS1v15(rand.Reader, r, crypto.SHA384, d) }
Convert a string to a pure title case for each word, replacing special characters by space. @param string The string to convert (must not be <code>null</code>). @return The string in title case. @throws LionEngineException If invalid arguments.
public static String toTitleCaseWord(String string) { Check.notNull(string); final String[] words = SPACE.split(REPLACER.matcher(string).replaceAll(Constant.SPACE)); final StringBuilder title = new StringBuilder(string.length()); for (int i = 0; i < words.length; i++) { title.append(toTitleCase(words[i])); if (i < words.length - 1) { title.append(Constant.SPACE); } } return title.toString(); }
<code>optional string domainSocketPath = 5;</code>
public java.lang.String getDomainSocketPath() { java.lang.Object ref = domainSocketPath_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { domainSocketPath_ = s; } return s; } }
See bidirectional LSTM's conversion function for its output shapes.
def calculate_bidirectional_lstm_output_shapes(operator): ''' ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType]) input_shape = operator.inputs[0].type.shape # LSTM accepts [N, C] and [N, C, 1, 1] inputs if len(input_shape) not in [2, 4]: raise RuntimeError('Input must be a 2-D or 4-D tensor') params = operator.raw_operator.biDirectionalLSTM # The following line is more accurate but it may break some tests # output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, 2 *params.outputVectorSize] output_shape = ['None', 2 * params.outputVectorSize] state_shape = [1, params.outputVectorSize] # TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function if len(operator.inputs) > 1: Y_h_in = operator.inputs[1] # The forward initial hidden state of a single sequence Y_h_in.type.shape = state_shape Y_h_rev_in = operator.inputs[3] # The backward initial hidden state of a single sequence Y_h_rev_in.type.shape = state_shape if len(operator.inputs) > 2: Y_c_in = operator.inputs[2] # The forward initial cell state of a single sequence Y_c_in.type.shape = state_shape Y_c_rev_in = operator.inputs[4] # The backward initial cell state of a single sequence Y_c_rev_in.type.shape = state_shape operator.outputs[0].type.shape = output_shape if len(operator.outputs) > 1: operator.outputs[1].type.shape = state_shape operator.outputs[3].type.shape = state_shape if len(operator.outputs) > 2: operator.outputs[2].type.shape = state_shape operator.outputs[4].type.shape = state_shape
Computes an array that contains current content data; it can also lighten result according to requested format. @param integer $format @return array
public function jsonSerialize($format = self::JSON_DEFAULT_FORMAT) { $data = [ 'uid' => $this->_uid, 'label' => $this->_label, 'type' => $this->getContentType(), 'state' => $this->_state, 'created' => $this->_created->getTimestamp(), 'modified' => $this->_modified->getTimestamp(), 'revision' => $this->_revision, 'parameters' => $this->getAllParams(), 'accept' => array_map( function ($classname) { return str_replace(NAMESPACE_SEPARATOR, '/', $classname); }, self::getShortClassname($this->getAccept()) ), 'minentry' => $this->getMinEntry(), 'maxentry' => $this->getMaxEntry(), 'elements' => $this->computeElementsToJson($this->getData()), 'has_elements' => count($this->getData()) === 0 ? false : true, 'extra' => [], ]; if (0 === count($data['parameters'])) { $data['parameters'] = new \ArrayObject(); } return $this->formatJsonData($data, $format); }
Displays a list of available time zones. Use this list when setting a time zone using ``timezone.set_zone`` :return: a list of time zones :rtype: list CLI Example: .. code-block:: bash salt '*' timezone.list_zones
def list_zones(): ''' ''' ret = salt.utils.mac_utils.execute_return_result( 'systemsetup -listtimezones') zones = salt.utils.mac_utils.parse_return(ret) return [x.strip() for x in zones.splitlines()]
Get the default connection name. This method is used to get the fallback connection name if an instance is created through the EndpointRegistry without a connection. @return string @see \Muffin\Webservice\Model\EndpointRegistry::get()
public static function defaultConnectionName() { $namespaceParts = explode('\\', get_called_class()); $plugin = array_slice(array_reverse($namespaceParts), 3, 2); return Inflector::underscore(current($plugin)); }
@param QueryString|string $query @return Uri
public function setQuery($query) { if (!($query instanceof QueryString)) { $this->query = new QueryString($query); return $this; } $this->query = $query; return $this; }
Sort within buckets, then batch, then shuffle batches. Partitions data into chunks of size 100*batch_size, sorts examples within each chunk using sort_key, then batch these examples and shuffle the batches.
def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count, random_shuffler=None, shuffle=False, sort_within_batch=False): if random_shuffler is None: random_shuffler = random.shuffle for p in batch(data, batch_size * 100, batch_size_fn): p_batch = batch(sorted(p, key=key), batch_size, batch_size_fn) \ if sort_within_batch \ else batch(p, batch_size, batch_size_fn) if shuffle: for b in random_shuffler(list(p_batch)): yield b else: for b in list(p_batch): yield b
Adds the required data used in the service template @param \Aimeos\MW\View\Iface $view View object @return \Aimeos\MW\View\Iface View object with assigned parameters
protected function addViewData( \Aimeos\MW\View\Iface $view ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'media/property/type' ); $search = $manager->createSearch( true )->setSlice( 0, 10000 ); $search->setConditions( $search->compare( '==', 'media.property.type.domain', 'service' ) ); $search->setSortations( [$search->sort( '+', 'media.property.type.position')] ); $view->propertyTypes = $this->map( $manager->searchItems( $search ) ); return $view; }
Write a local variable table entry for every registered variable.
void generateTableEntries(CodeBuilder ga) { for (Variable var : allVariables) { try { var.local.tableEntry(ga); } catch (Throwable t) { throw new RuntimeException("unable to write table entry for: " + var.local, t); } } }
Get the authentication object. @param string $errorOnNull If true, throw an exception if auth null. @return MyAllocator\phpsdk\src\Object\Auth API Authentication object. @throws MyAllocator\phpsdk\src\Exception\ApiException
public function getAuth($errorOnNull = false) { if ($errorOnNull && !$this->auth) { $msg = 'No Auth object provided. (HINT: Set your Auth data using ' . '"$API->setAuth(Auth $auth)" or $API\' constructor. ' . 'See https://TODO for details.'; throw new ApiException($msg); } return $this->auth; }
Get page favicon url @return string url
public function getPageFavicon() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=shortcut], link[rel=icon], link[rel=shortcut icon]', 0); if ($node) { return $node->getAttribute('href'); } }
// refresh prints the progress of all downloads to the terminal
func (c *ConsoleClient) refresh() { // clear lines for incomplete downloads if c.inProgress > 0 { fmt.Printf("\033[%dA\033[K", c.inProgress) } // print newly completed downloads for i, resp := range c.responses { if resp != nil && resp.IsComplete() { if resp.Err() != nil { c.failed++ fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", resp.Request.URL(), resp.Err()) } else { c.succeeded++ fmt.Printf("Finished %s %s / %s (%d%%)\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress())) } c.responses[i] = nil } } // print progress for incomplete downloads c.inProgress = 0 for _, resp := range c.responses { if resp != nil { fmt.Printf("Downloading %s %s / %s (%d%%) - %s ETA: %s \033[K\n", resp.Filename, byteString(resp.BytesComplete()), byteString(resp.Size), int(100*resp.Progress()), bpsString(resp.BytesPerSecond()), etaString(resp.ETA())) c.inProgress++ } } }
This method is intended for internal use only. Returns the marshaled request configured with additional parameters to enable operation dry-run.
@Override public Request<ModifyInstancePlacementRequest> getDryRunRequest() { Request<ModifyInstancePlacementRequest> request = new ModifyInstancePlacementRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
Populate from an array. @param array $data
public function populate($data = array()) { if (isset($data['name']) && $data['name'] !== null) { $this->name = $data['name']; } if (isset($data['type']) && $data['type'] !== null) { $this->type = $data['type']; } }
/* (non-Javadoc) @see net.roboconf.doc.generator.internal.transformers.AbstractRoboconfTransformer #getConfiguredLayout()
@Override public Layout<AbstractType,String> getConfiguredLayout() { return new StaticLayout<AbstractType,String>( this.graph, this, getGraphDimension()); }
// UpdateJobs mocks base method
func (m *MockInstance) UpdateJobs(arg0 manifest.Manifest, arg1 ui.Stage) error { ret := m.ctrl.Call(m, "UpdateJobs", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
This mehtod will render the JavaScript associated with the id lookup if id has been set. @param request @param id @return
private String renderNameAndId(HttpServletRequest request, String id) { // if id is not set then we need to exit if (id == null) return null; // Legacy Java Script support -- This writes out a single table with both the id and names // mixed. This is legacy support to match the pre beehive behavior. String idScript = null; IScriptReporter scriptReporter = getScriptReporter(); ScriptRequestState srs = ScriptRequestState.getScriptRequestState(request); if (TagConfig.isLegacyJavaScript()) { idScript = srs.mapLegacyTagId(scriptReporter, id, _state.id); } // map the tagId to the real id if (TagConfig.isDefaultJavaScript()) { String script = srs.mapTagId(scriptReporter, id, _state.id, _state.name); // if we wrote out script in legacy mode, we need to make sure we preserve it. if (idScript != null) { idScript = idScript + script; } else { idScript = script; } } return idScript; }
Marshall the given parameter object.
public void marshall(CreateAliasRequest createAliasRequest, ProtocolMarshaller protocolMarshaller) { if (createAliasRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createAliasRequest.getFunctionName(), FUNCTIONNAME_BINDING); protocolMarshaller.marshall(createAliasRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(createAliasRequest.getFunctionVersion(), FUNCTIONVERSION_BINDING); protocolMarshaller.marshall(createAliasRequest.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(createAliasRequest.getRoutingConfig(), ROUTINGCONFIG_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
this method will generate a new container node that prevent control transformation to be applied to the shadow effect (which makes it looks as a real shadow)
public static Node createMaterialNode(Node control, int level) { Node container = new Pane(control){ @Override protected double computeMaxWidth(double height) { return computePrefWidth(height); } @Override protected double computeMaxHeight(double width) { return computePrefHeight(width); } @Override protected double computePrefWidth(double height) { return control.prefWidth(height); } @Override protected double computePrefHeight(double width) { return control.prefHeight(width); } }; container.getStyleClass().add("depth-container"); container.setPickOnBounds(false); level = level < 0 ? 0 : level; level = level > 5 ? 5 : level; container.setEffect(new DropShadow(BlurType.GAUSSIAN, depth[level].getColor(), depth[level].getRadius(), depth[level].getSpread(), depth[level].getOffsetX(), depth[level].getOffsetY())); return container; }
Add file to package from content @param content @param target Target path like /opt/application/bin/foo @return @throws IOException
@Override public FileBuilder addFile(ByteBuffer content, Path target) throws IOException { checkTarget(target); FileBuilder fb = new FileBuilder(); fb.content = content; fb.target = target; fb.size = content.limit(); fb.compressFilename(); fileBuilders.add(fb); return fb; }
dataURL 转成 blob 对象 @param dataURL @returns blob
function dataURLtoBlob(dataUrl) { let pos = dataUrl.indexOf(',', 0) let arr = [ dataUrl.slice(0, pos), dataUrl.slice(pos+1) ] let mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n) while(n--) { u8arr[n] = bstr.charCodeAt(n) } return new Blob([ u8arr ], { type:mime }) }
Extract a token from a request object.
def _get_token(self, request, refresh_token=False): if self.config.cookie_set(): token = self._get_token_from_cookies(request, refresh_token) if token: return token else: if self.config.cookie_strict(): raise exceptions.MissingAuthorizationCookie() if self.config.query_string_set(): token = self._get_token_from_query_string(request, refresh_token) if token: return token else: if self.config.query_string_strict(): raise exceptions.MissingAuthorizationQueryArg() token = self._get_token_from_headers(request, refresh_token) if token: return token raise exceptions.MissingAuthorizationHeader()
Get the usage for the remote exectuion options :return Usage for the remote execution options
def usage(self): # Retrieve the text for just the arguments usage = self.parser.format_help().split("optional arguments:")[1] # Remove any blank lines and return return "Remote Options:" + os.linesep + \ os.linesep.join([s for s in usage.splitlines() if s])
Create first user
public function createUser() { $data['name'] = $this->ask('Administrator name'); $data['email'] = $this->ask('Administrator email'); $data['password'] = bcrypt($this->secret('Administrator password')); $data['role_id'] = 1; User::create($data); $this->info('User has been created'); }
Remove a selection criteria from the subscription
public void removeSelectionCriteria(SelectionCriteria selCriteria) throws SIResourceException { if (tc.isEntryEnabled()) SibTr.entry(tc, "removeSelectionCriteria", new Object[] { selCriteria }); // If the selection criteria was removed then this is an indication that it was // in the matchspace and it can be removed. boolean wasRemoved = _consumerDispatcher.getConsumerDispatcherState().removeSelectionCriteria(selCriteria); if (wasRemoved) { Transaction tran = _messageProcessor.getTXManager().createAutoCommitTransaction(); if( !_consumerDispatcher.getReferenceStream().isUpdating() ) { try { _consumerDispatcher.getReferenceStream().requestUpdate(tran); } catch (MessageStoreException e) { // MessageStoreException shouldn't occur so FFDC. FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.MPSubscriptionImpl.removeSelectionCriteria", "1:203:1.6", this); // Add the criteria back into the list as the remove failed. _consumerDispatcher.getConsumerDispatcherState().addSelectionCriteria(selCriteria); SibTr.exception(tc, e); if (tc.isEntryEnabled()) SibTr.exit(tc, "removeSelectionCriteria", "SIResourceException"); throw new SIResourceException(e); } } // Remove the criteria from the matchspace _messageProcessor .getMessageProcessorMatching() .removeConsumerDispatcherMatchTarget( _consumerDispatcher, selCriteria ); } if (tc.isEntryEnabled()) SibTr.exit(tc, "removeSelectionCriteria"); }
// UnmarshalJSON converts the string to a LangID
func (lng *LangID) UnmarshalJSON(p []byte) error { if len(p) == 0 { return nil } if p[0] != '"' { var u uint16 if err := json.Unmarshal(p, &u); err != nil { return err } *lng = LangID(u) return nil } var s string if err := json.Unmarshal(p, &s); err != nil { return err } u, err := strconv.ParseUint(s, 16, 16) if err != nil { return err } *lng = LangID(u) return nil }
processing error
public JavaCompiler doProcessing(Context context, List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols, Iterable<? extends PackageSymbol> pckSymbols, Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { log = Log.instance(context); Set<PackageSymbol> specifiedPackages = new LinkedHashSet<PackageSymbol>(); for (PackageSymbol psym : pckSymbols) specifiedPackages.add(psym); this.specifiedPackages = Collections.unmodifiableSet(specifiedPackages); Round round = new Round(context, roots, classSymbols, deferredDiagnosticHandler); boolean errorStatus; boolean moreToDo; do { // Run processors for round n round.run(false, false); // Processors for round n have run to completion. // Check for errors and whether there is more work to do. errorStatus = round.unrecoverableError(); moreToDo = moreToDo(); round.showDiagnostics(errorStatus || showResolveErrors); // Set up next round. // Copy mutable collections returned from filer. round = round.next( new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()), new LinkedHashMap<String,JavaFileObject>(filer.getGeneratedClasses())); // Check for errors during setup. if (round.unrecoverableError()) errorStatus = true; } while (moreToDo && !errorStatus); // run last round round.run(true, errorStatus); round.showDiagnostics(true); filer.warnIfUnclosedFiles(); warnIfUnmatchedOptions(); /* * If an annotation processor raises an error in a round, * that round runs to completion and one last round occurs. * The last round may also occur because no more source or * class files have been generated. Therefore, if an error * was raised on either of the last *two* rounds, the compile * should exit with a nonzero exit code. The current value of * errorStatus holds whether or not an error was raised on the * second to last round; errorRaised() gives the error status * of the last round. */ if (messager.errorRaised() || werror && round.warningCount() > 0 && round.errorCount() > 0) errorStatus = true; Set<JavaFileObject> newSourceFiles = new LinkedHashSet<JavaFileObject>(filer.getGeneratedSourceFileObjects()); roots = cleanTrees(round.roots); JavaCompiler compiler = round.finalCompiler(); if (newSourceFiles.size() > 0) roots = roots.appendList(compiler.parseFiles(newSourceFiles)); errorStatus = errorStatus || (compiler.errorCount() > 0); // Free resources this.close(); if (!taskListener.isEmpty()) taskListener.finished(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING)); if (errorStatus) { if (compiler.errorCount() == 0) compiler.log.nerrors++; return compiler; } compiler.enterTreesIfNeeded(roots); return compiler; }
// NewStickerMessage function
func NewStickerMessage(packageID, stickerID string) *StickerMessage { return &StickerMessage{ PackageID: packageID, StickerID: stickerID, } }
Copies the shell items to a path. Returns: str: converted shell item list path or None.
def CopyToPath(self): number_of_path_segments = len(self._path_segments) if number_of_path_segments == 0: return None strings = [self._path_segments[0]] number_of_path_segments -= 1 for path_segment in self._path_segments[1:]: # Remove a trailing \ except for the last path segment. if path_segment.endswith('\\') and number_of_path_segments > 1: path_segment = path_segment[:-1] if ((path_segment.startswith('<') and path_segment.endswith('>')) or len(strings) == 1): strings.append(' {0:s}'.format(path_segment)) elif path_segment.startswith('\\'): strings.append('{0:s}'.format(path_segment)) else: strings.append('\\{0:s}'.format(path_segment)) number_of_path_segments -= 1 return ''.join(strings)
// SetFilters sets the Filters field's value.
func (s *DescribeMaintenanceWindowsInput) SetFilters(v []*MaintenanceWindowFilter) *DescribeMaintenanceWindowsInput { s.Filters = v return s }
Creates an answer from a functional interface - allows for a strongly typed answer to be created ideally in Java 8 @param answer interface to the answer - a void method @param <A> input parameter type 1 @return the answer object to use @since 2.1.0
@Incubating public static <A> Answer<Void> answerVoid(VoidAnswer1<A> answer) { return toAnswer(answer); }
// SetValuesToAdd sets the ValuesToAdd field's value.
func (s *ModifyDBClusterSnapshotAttributeInput) SetValuesToAdd(v []*string) *ModifyDBClusterSnapshotAttributeInput { s.ValuesToAdd = v return s }
Returns the collection of events provided by the given service interface. @param serviceInterface the service interface @return the events provided by the given service interface
public static Map<EventType, Method> getEventMap(Class<?> serviceInterface) { if (!serviceInterface.isInterface()) { Class type = serviceInterface; Map<EventType, Method> events = new HashMap<>(); while (type != Object.class) { for (Class<?> iface : type.getInterfaces()) { events.putAll(findEvents(iface)); } type = type.getSuperclass(); } return events; } return findEvents(serviceInterface); }
Outputs the HTML for an &lt;option&gt; field. @param array $values The options to output. @param mixed $selected_value A string or an array with the selected values that should be selected. @return string The HTML string.
public function select_option($values, $selected_value) { $content = ''; foreach ($values as $value => $title) { if (is_array($title)) { $label = $this->_escape($value); $content .= "<optgroup label=\"{$label}\">"; $content .= $this->select_option($title, $selected_value); $content .= "</optgroup>"; } else { $value = $this->_escape($value); $title = $this->_escape($title); $selected = ''; if (is_scalar($selected_value) && $value == $selected_value) { $selected = ' selected="selected"'; } elseif (is_array($selected_value) && in_array($value, $selected_value)) { $selected = ' selected="selected"'; } $content .= "<option value=\"{$value}\"{$selected}>{$title}</option>"; } } return $content; }
获取样式 @param {Object} dom DOM节点 @param {String} name 样式名 @param {Any} defaultValue 默认值 @return {String} 属性值
function getStyle(dom, name, defaultValue) { try { if (window.getComputedStyle) { return window.getComputedStyle(dom, null)[name]; } return dom.currentStyle[name]; } catch (e) { if (!Util.isNil(defaultValue)) { return defaultValue; } return null; } }
Set the Root.Description, possibly splitting long descriptions across multiple terms.
def set_wrappable_term(self, v, term): import textwrap for t in self['Root'].find(term): self.remove_term(t) for l in textwrap.wrap(v, 80): self['Root'].new_term(term, l)
Subclasses may override this. This method calls handleGetMonthLength() to obtain the calendar-specific month length.
protected int handleComputeJulianDay(int bestField) { boolean useMonth = (bestField == DAY_OF_MONTH || bestField == WEEK_OF_MONTH || bestField == DAY_OF_WEEK_IN_MONTH); int year; if (bestField == WEEK_OF_YEAR) { // Nota Bene! It is critical that YEAR_WOY be used as the year here, if it is // set. Otherwise, when WOY is the best field, the year may be wrong at the // extreme limits of the year. If YEAR_WOY is not set then it will fall back. // TODO: Should resolveField(YEAR_PRECEDENCE) be brought to bear? year = internalGet(YEAR_WOY, handleGetExtendedYear()); } else { year = handleGetExtendedYear(); } internalSet(EXTENDED_YEAR, year); int month = useMonth ? internalGet(MONTH, getDefaultMonthInYear(year)) : 0; // Get the Julian day of the day BEFORE the start of this year. // If useMonth is true, get the day before the start of the month. int julianDay = handleComputeMonthStart(year, month, useMonth); if (bestField == DAY_OF_MONTH) { if(isSet(DAY_OF_MONTH)) { return julianDay + internalGet(DAY_OF_MONTH, getDefaultDayInMonth(year, month)); } else { return julianDay + getDefaultDayInMonth(year, month); } } if (bestField == DAY_OF_YEAR) { return julianDay + internalGet(DAY_OF_YEAR); } int firstDOW = getFirstDayOfWeek(); // Localized fdw // At this point julianDay is the 0-based day BEFORE the first day of // January 1, year 1 of the given calendar. If julianDay == 0, it // specifies (Jan. 1, 1) - 1, in whatever calendar we are using (Julian // or Gregorian). // At this point we need to process the WEEK_OF_MONTH or // WEEK_OF_YEAR, which are similar, or the DAY_OF_WEEK_IN_MONTH. // First, perform initial shared computations. These locate the // first week of the period. // Get the 0-based localized DOW of day one of the month or year. // Valid range 0..6. int first = julianDayToDayOfWeek(julianDay + 1) - firstDOW; if (first < 0) { first += 7; } // Get zero-based localized DOW, valid range 0..6. This is the DOW // we are looking for. int dowLocal = 0; switch (resolveFields(DOW_PRECEDENCE)) { case DAY_OF_WEEK: dowLocal = internalGet(DAY_OF_WEEK) - firstDOW; break; case DOW_LOCAL: dowLocal = internalGet(DOW_LOCAL) - 1; break; } dowLocal = dowLocal % 7; if (dowLocal < 0) { dowLocal += 7; } // Find the first target DOW (dowLocal) in the month or year. // Actually, it may be just before the first of the month or year. // It will be an integer from -5..7. int date = 1 - first + dowLocal; if (bestField == DAY_OF_WEEK_IN_MONTH) { // Adjust the target DOW to be in the month or year. if (date < 1) { date += 7; } // The only trickiness occurs if the day-of-week-in-month is // negative. int dim = internalGet(DAY_OF_WEEK_IN_MONTH, 1); if (dim >= 0) { date += 7*(dim - 1); } else { // Move date to the last of this day-of-week in this month, // then back up as needed. If dim==-1, we don't back up at // all. If dim==-2, we back up once, etc. Don't back up // past the first of the given day-of-week in this month. // Note that we handle -2, -3, etc. correctly, even though // values < -1 are technically disallowed. int m = internalGet(MONTH, JANUARY); int monthLength = handleGetMonthLength(year, m); date += ((monthLength - date) / 7 + dim + 1) * 7; } } else { // assert(bestField == WEEK_OF_MONTH || bestField == WEEK_OF_YEAR) // Adjust for minimal days in first week if ((7 - first) < getMinimalDaysInFirstWeek()) { date += 7; } // Now adjust for the week number. date += 7 * (internalGet(bestField) - 1); } return julianDay + date; }
Returns the number of rows matching the dynamic query. @param dynamicQuery the dynamic query @param projection the projection to apply to the query @return the number of rows matching the dynamic query
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return cpDefinitionInventoryPersistence.countWithDynamicQuery(dynamicQuery, projection); }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eUnset(int featureID) { switch (featureID) { case XbasePackage.XINSTANCE_OF_EXPRESSION__TYPE: setType((JvmTypeReference)null); return; case XbasePackage.XINSTANCE_OF_EXPRESSION__EXPRESSION: setExpression((XExpression)null); return; } super.eUnset(featureID); }
Luckily `opts` is always the 2nd argument
function withPlugins(fn) { return function() { const args = Array.from(arguments); let plugins = (args[1] && args[1].plugins) || []; if (!isArray(plugins)) { plugins = Object.values(plugins); } args[1] = Object.assign({}, args[1], { plugins: internalPlugins.concat(plugins) }); return fn.apply(null, args); }; }
Marshall the given parameter object.
public void marshall(PlainTextMessageType plainTextMessageType, ProtocolMarshaller protocolMarshaller) { if (plainTextMessageType == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(plainTextMessageType.getLanguageCode(), LANGUAGECODE_BINDING); protocolMarshaller.marshall(plainTextMessageType.getText(), TEXT_BINDING); protocolMarshaller.marshall(plainTextMessageType.getVoiceId(), VOICEID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
*------------------------------ Date converter --------------------------*//
public static function parseFromFormat($format, $date) { // reverse engineer date formats $keys = [ 'Y' => ['year', '\d{4}'], 'y' => ['year', '\d{2}'], 'm' => ['month', '\d{2}'], 'n' => ['month', '\d{1,2}'], 'M' => ['month', '[A-Z][a-z]{3}'], 'F' => ['month', '[A-Z][a-z]{2,8}'], 'd' => ['day', '\d{2}'], 'j' => ['day', '\d{1,2}'], 'D' => ['day', '[A-Z][a-z]{2}'], 'l' => ['day', '[A-Z][a-z]{6,9}'], 'u' => ['hour', '\d{1,6}'], 'h' => ['hour', '\d{2}'], 'H' => ['hour', '\d{2}'], 'g' => ['hour', '\d{1,2}'], 'G' => ['hour', '\d{1,2}'], 'i' => ['minute', '\d{2}'], 's' => ['second', '\d{2}'], ]; // convert format string to regex $regex = ''; $chars = str_split($format); foreach ($chars as $n => $char) { $lastChar = isset($chars[ $n - 1 ]) ? $chars[ $n - 1 ] : ''; $skipCurrent = '\\' == $lastChar; if (!$skipCurrent && isset($keys[ $char ])) { $regex .= '(?P<' . $keys[ $char ][0] . '>' . $keys[ $char ][1] . ')'; } else { if ('\\' == $char) { $regex .= $char; } else { $regex .= preg_quote($char); } } } $dt = []; $dt['error_count'] = 0; // now try to match it if (preg_match('#^' . $regex . '$#', $date, $dt)) { foreach ($dt as $k => $v) { if (is_int($k)) { unset($dt[ $k ]); } } if (!jDateTime::checkdate($dt['month'], $dt['day'], $dt['year'], false)) { $dt['error_count'] = 1; } } else { $dt['error_count'] = 1; } $dt['errors'] = []; $dt['fraction'] = ''; $dt['warning_count'] = 0; $dt['warnings'] = []; $dt['is_localtime'] = 0; $dt['zone_type'] = 0; $dt['zone'] = 0; $dt['is_dst'] = ''; if (strlen($dt['year']) == 2) { $now = jDate::forge('now'); $x = $now->format('Y') - $now->format('y'); $dt['year'] += $x; } $dt['year'] = isset($dt['year']) ? (int)$dt['year'] : 0; $dt['month'] = isset($dt['month']) ? (int)$dt['month'] : 0; $dt['day'] = isset($dt['day']) ? (int)$dt['day'] : 0; $dt['hour'] = isset($dt['hour']) ? (int)$dt['hour'] : 0; $dt['minute'] = isset($dt['minute']) ? (int)$dt['minute'] : 0; $dt['second'] = isset($dt['second']) ? (int)$dt['second'] : 0; $dt['just_time'] = $dt['hour'] * 360 + $dt['minute'] * 60 + $dt['second']; return $dt; }
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MasterVolumeConfig.
func (in *MasterVolumeConfig) DeepCopy() *MasterVolumeConfig { if in == nil { return nil } out := new(MasterVolumeConfig) in.DeepCopyInto(out) return out }
// SetApplicationName sets the ApplicationName field's value.
func (s *UpdateApplicationInput) SetApplicationName(v string) *UpdateApplicationInput { s.ApplicationName = &v return s }
Given a table comment this method tries to extract a typehint for Doctrine Type, or returns the type given as default. @param string|null $comment @param string $currentType @return string
public function extractDoctrineTypeFromComment($comment, $currentType) { if ($comment !== null && preg_match('(\(DC2Type:(((?!\)).)+)\))', $comment, $match)) { return $match[1]; } return $currentType; }
Directive array @return string[]
protected static function directiveArray() { return array( self::DIRECTIVE_ALLOW, self::DIRECTIVE_DISALLOW, self::DIRECTIVE_HOST, self::DIRECTIVE_USERAGENT, self::DIRECTIVE_SITEMAP, self::DIRECTIVE_CRAWL_DELAY, self::DIRECTIVE_CACHE_DELAY, self::DIRECTIVE_CLEAN_PARAM ); }
Clip images based on bounds provided Implementation is borrowed from https://github.com/brendan-ward/rasterio/blob/e3687ce0ccf8ad92844c16d913a6482d5142cf48/rasterio/rio/convert.py
def clip(self): self.output("Clipping", normal=True) # create new folder for clipped images path = check_create_folder(join(self.scene_path, 'clipped')) try: temp_bands = copy(self.bands) temp_bands.append('QA') for i, band in enumerate(temp_bands): band_name = self._get_full_filename(band) band_path = join(self.scene_path, band_name) self.output("Band %s" % band, normal=True, color='green', indent=1) with rasterio.open(band_path) as src: bounds = transform_bounds( { 'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84', 'no_defs': True }, src.crs, *self.bounds ) if disjoint_bounds(bounds, src.bounds): bounds = adjust_bounding_box(src.bounds, bounds) window = src.window(*bounds) out_kwargs = src.meta.copy() out_kwargs.update({ 'driver': 'GTiff', 'height': window[0][1] - window[0][0], 'width': window[1][1] - window[1][0], 'transform': src.window_transform(window) }) with rasterio.open(join(path, band_name), 'w', **out_kwargs) as out: out.write(src.read(window=window)) # Copy MTL to the clipped folder copyfile(join(self.scene_path, self.scene + '_MTL.txt'), join(path, self.scene + '_MTL.txt')) return path except IOError as e: exit(e.message, 1)
Add sorting hat enrichment fields
def get_item_sh(self, item, roles=None, date_field=None): """""" eitem_sh = {} created = str_to_datetime(date_field) for rol in roles: identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, created, rol=rol)) if not eitem_sh[rol + '_org_name']: eitem_sh[rol + '_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_name']: eitem_sh[rol + '_name'] = SH_UNKNOWN_VALUE if not eitem_sh[rol + '_user_name']: eitem_sh[rol + '_user_name'] = SH_UNKNOWN_VALUE # Add the author field common in all data sources if rol == self.get_field_author(): identity = self.get_sh_identity(item, rol) eitem_sh.update(self.get_item_sh_fields(identity, created, rol="author")) if not eitem_sh['author_org_name']: eitem_sh['author_org_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_name']: eitem_sh['author_name'] = SH_UNKNOWN_VALUE if not eitem_sh['author_user_name']: eitem_sh['author_user_name'] = SH_UNKNOWN_VALUE return eitem_sh
Plot the data. @param string $chart_title @param string[] $x_axis @param string $x_axis_title @param int[][] $ydata @param string $y_axis_title @param string[] $z_axis @param int $y_axis_type @return string
private function myPlot( string $chart_title, array $x_axis, string $x_axis_title, array $ydata, string $y_axis_title, array $z_axis, int $y_axis_type ): string { if (!count($ydata)) { return I18N::translate('This information is not available.'); } // Colors for z-axis $colors = []; $index = 0; while (count($colors) < count($ydata)) { $colors[] = self::Z_AXIS_COLORS[$index]; $index = ($index + 1) % count(self::Z_AXIS_COLORS); } // Convert our sparse dataset into a fixed-size array $tmp = []; foreach (array_keys($z_axis) as $z) { foreach (array_keys($x_axis) as $x) { $tmp[$z][$x] = $ydata[$z][$x] ?? 0; } } $ydata = $tmp; // Convert the chart data to percentage if ($y_axis_type === self::Y_AXIS_PERCENT) { // Normalise each (non-zero!) set of data to total 100% array_walk($ydata, static function (array &$x) { $sum = array_sum($x); if ($sum > 0) { $x = array_map(static function ($y) use ($sum) { return $y * 100.0 / $sum; }, $x); } }); } $data = [ array_merge( [ I18N::translate('Century') ], array_values($z_axis) ) ]; $intermediate = []; foreach ($ydata as $century => $months) { foreach ($months as $month => $value) { $intermediate[$month][] = [ 'v' => $value, 'f' => ($y_axis_type === self::Y_AXIS_PERCENT) ? sprintf('%.1f%%', $value) : $value, ]; } } foreach ($intermediate as $key => $values) { $data[] = array_merge( [ $x_axis[$key] ], $values ); } $chart_options = [ 'title' => '', 'subtitle' => '', 'height' => 400, 'width' => '100%', 'legend' => [ 'position' => count($z_axis) > 1 ? 'right' : 'none', 'alignment' => 'center', ], 'tooltip' => [ 'format' => '\'%\'', ], 'vAxis' => [ 'title' => $y_axis_title ?? '', ], 'hAxis' => [ 'title' => $x_axis_title ?? '', ], 'colors' => $colors, ]; return view( 'statistics/other/charts/custom', [ 'data' => $data, 'chart_options' => $chart_options, 'chart_title' => $chart_title, ] ); }
// UnmarshalJSON populates a new Manifest struct from JSON data.
func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { m.canonical = make([]byte, len(b)) // store manifest in canonical copy(m.canonical, b) // Unmarshal canonical JSON into Manifest object var manifest Manifest if err := json.Unmarshal(m.canonical, &manifest); err != nil { return err } if manifest.MediaType != "" && manifest.MediaType != v1.MediaTypeImageManifest { return fmt.Errorf("if present, mediaType in manifest should be '%s' not '%s'", v1.MediaTypeImageManifest, manifest.MediaType) } m.Manifest = manifest return nil }
Save the current values in all the widgets back to the persistent data storage. :param validate: whether to validate the saved data or not. :raises: InvalidFields if any invalid data is found.
def save(self, validate): invalid = [] for column in self._columns: for widget in column: if widget.is_valid or not validate: if widget.name is not None: # This relies on the fact that we are passed the actual # dict and so can edit it directly. In this case, that # is all we want - no need to update the widgets. self._frame._data[widget.name] = widget.value else: invalid.append(widget.name) if len(invalid) > 0: raise InvalidFields(invalid)
// dec decodes the encoding s into z.
func (m *matcher) dec(z *nstate, s string) { b := append(m.buf[:0], s...) m.buf = b z.needFlag = syntax.EmptyOp(b[0]) b = b[1:] i, n := binary.Uvarint(b) if n <= 0 { bug() } b = b[n:] z.flag = flags(i) z.q.Reset() last := ^uint32(0) for len(b) > 0 { i, n = binary.Uvarint(b) if n <= 0 { bug() } b = b[n:] last += uint32(i) z.q.Add(last, 0, 0) } }
// Inputs returns the array of inputs that defines the Env.
func (tri EnvTriangle) Inputs() []Input { (&tri).defaults() d := tri.Dur.Mul(C(0.5)) return Env{ Levels: []Input{C(0), tri.Level, C(0)}, Times: []Input{d, d}, }.Inputs() }
Write request to the server. @param mixed $request The request to write @throws ValidationException
public function write($request) { if ($this->isComplete) { throw new ValidationException("Cannot call write() after streaming call is complete."); } if ($this->writesClosed) { throw new ValidationException("Cannot call write() after calling closeWrite()."); } $this->call->write($request); }
Add any relevant project dependencies to the classpath. Indirectly takes includePluginDependencies and ExecutableDependency into consideration.
protected void addExtraPluginDependencies(Set<Artifact> artifacts) throws MojoExecutionException { if (extraPluginDependencyArtifactId == null && extendedPluginDependencyArtifactId == null) { return; } Set<Artifact> deps = new HashSet<Artifact>(this.pluginDependencies); for (Artifact artifact : deps) { // must if (artifact.getArtifactId().equals(extraPluginDependencyArtifactId) || artifact.getArtifactId().equals(extendedPluginDependencyArtifactId)) { getLog().debug("Adding extra plugin dependency artifact: " + artifact.getArtifactId() + " to classpath"); artifacts.add(artifact); // add the transient dependencies of this artifact Set<Artifact> resolvedDeps = resolveExecutableDependencies(artifact); for (Artifact dep : resolvedDeps) { getLog().debug("Adding extra plugin dependency artifact: " + dep.getArtifactId() + " to classpath"); artifacts.add(dep); } } } }
###################################
private static ReadConfiguration getLocalConfiguration(String shortcutOrFile) { File file = new File(shortcutOrFile); if (file.exists()) return getLocalConfiguration(file); else { int pos = shortcutOrFile.indexOf(':'); if (pos<0) pos = shortcutOrFile.length(); String backend = shortcutOrFile.substring(0,pos); Preconditions.checkArgument(StandardStoreManager.getAllManagerClasses().containsKey(backend.toLowerCase()), "Backend shorthand unknown: %s", backend); String secondArg = null; if (pos+1<shortcutOrFile.length()) secondArg = shortcutOrFile.substring(pos + 1).trim(); BaseConfiguration config = new BaseConfiguration(); ModifiableConfiguration writeConfig = new ModifiableConfiguration(ROOT_NS,new CommonsConfiguration(config), BasicConfiguration.Restriction.NONE); writeConfig.set(STORAGE_BACKEND,backend); ConfigOption option = Backend.getOptionForShorthand(backend); if (option==null) { Preconditions.checkArgument(secondArg==null); } else if (option==STORAGE_DIRECTORY || option==STORAGE_CONF_FILE) { Preconditions.checkArgument(StringUtils.isNotBlank(secondArg),"Need to provide additional argument to initialize storage backend"); writeConfig.set(option,getAbsolutePath(secondArg)); } else if (option==STORAGE_HOSTS) { Preconditions.checkArgument(StringUtils.isNotBlank(secondArg),"Need to provide additional argument to initialize storage backend"); writeConfig.set(option,new String[]{secondArg}); } else throw new IllegalArgumentException("Invalid configuration option for backend "+option); return new CommonsConfiguration(config); } }
// Returns the number of items
func (m *SyncMap) Size() int { size := 0 for _, shard := range m.shards { shard.RLock() size += len(shard.items) shard.RUnlock() } return size }
Returns true if polyline_a overlaps polyline_b.
private static boolean polylineOverlapsPolyline_(Polyline polyline_a, Polyline polyline_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint. if (tryRasterizedContainsOrDisjoint_(polyline_a, polyline_b, tolerance, false) == Relation.disjoint) return false; return linearPathOverlapsLinearPath_(polyline_a, polyline_b, tolerance); }
If sub-classed, run any shutdown operations on this method.
def shutdown(self, exitcode=0, exitmsg=None): ''' ''' log.info('The salt-api is shutting down..') msg = 'The salt-api is shutdown. ' if exitmsg is not None: exitmsg = msg + exitmsg else: exitmsg = msg.strip() super(SaltAPI, self).shutdown(exitcode, exitmsg)
Returns seed signature for given request.
public static String getChunkSeedSignature(Request request, String region, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = request.header("x-amz-content-sha256"); DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, null, secretKey, null); signer.setScope(); signer.setCanonicalRequest(); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); return signer.signature; }
Returns a polygon containing the bounding box of the catalogue
def get_catalogue_bounding_polygon(catalogue): ''' ''' upper_lon = np.max(catalogue.data['longitude']) upper_lat = np.max(catalogue.data['latitude']) lower_lon = np.min(catalogue.data['longitude']) lower_lat = np.min(catalogue.data['latitude']) return Polygon([Point(lower_lon, upper_lat), Point(upper_lon, upper_lat), Point(upper_lon, lower_lat), Point(lower_lon, lower_lat)])
Boot the role model Attach event listener to remove the many-to-many records when trying to delete Will NOT delete any records if the role model uses soft deletes. @return void|bool
public static function boot() { parent::boot(); static::deleting(function ($role) { if (!method_exists(config('access.role'), 'bootSoftDeletes')) { $role->users()->sync([]); $role->perms()->sync([]); } return true; }); }
// UnmarshalJSON sets the object from the provided JSON representation
func (l *ElasticBeanstalkConfigurationTemplateSourceConfigurationList) UnmarshalJSON(buf []byte) error { // Cloudformation allows a single object when a list of objects is expected item := ElasticBeanstalkConfigurationTemplateSourceConfiguration{} if err := json.Unmarshal(buf, &item); err == nil { *l = ElasticBeanstalkConfigurationTemplateSourceConfigurationList{item} return nil } list := []ElasticBeanstalkConfigurationTemplateSourceConfiguration{} err := json.Unmarshal(buf, &list) if err == nil { *l = ElasticBeanstalkConfigurationTemplateSourceConfigurationList(list) return nil } return err }
new line, with a specific height @access protected @param float $h @param integer $curr real current position in the text, if new line in the write of a text
protected function _setNewLine($h, $curr = null) { $this->pdf->Ln($h); $this->_setNewPositionForNewLine($curr); }
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (ka *ka_GE) WeekdayShort(weekday time.Weekday) string { return ka.daysShort[weekday] }
Get the guest's group, containing only the 'guests' group model. @return \Flarum\Group\Group
public function getGroupsAttribute() { if (! isset($this->attributes['groups'])) { $this->attributes['groups'] = $this->relations['groups'] = Group::where('id', Group::GUEST_ID)->get(); } return $this->attributes['groups']; }
// SetEvalResourceName sets the EvalResourceName field's value.
func (s *ResourceSpecificResult) SetEvalResourceName(v string) *ResourceSpecificResult { s.EvalResourceName = &v return s }
Parse a WELCOME and update user state, then dispatch a WELCOME event.
def _parse_welcome(client, command, actor, args): """""" _, _, hostmask = args.rpartition(' ') client.user.update_from_hostmask(hostmask) client.dispatch_event("WELCOME", hostmask)
Write status message and line break to file descriptor.
def writeln (self, msg): """""" self.fd.write(u"%s%s" % (msg, unicode(os.linesep)))
从query字符中获取值,也就是获取$_GET的值 @param $key @param string $def @param null|string $filter @return null|string @throws Exception
public function getQuery($key, $def = "", $filter = null) { $val = $this->query[$key]; if ($filter) { $val = Filter::factory($val, $filter); } return $val === null ? $def : $val; }
Check the project file for the REPLACE_FOLDER card. If it exists, append it's value to create the batch directory path. This is the directory output is written to when run in batch mode.
def _getBatchDirectory(self, projectRootDirectory): # Set output directory to main directory as default batchDirectory = projectRootDirectory # Get the replace folder card replaceFolderCard = self.getCard('REPLACE_FOLDER') if replaceFolderCard: replaceDir = replaceFolderCard.value.strip('"') batchDirectory = os.path.join(batchDirectory, replaceDir) # Create directory if it doesn't exist if not os.path.isdir(batchDirectory): os.mkdir(batchDirectory) log.info('Creating directory for batch output: {0}'.format(batchDirectory)) return batchDirectory
Returns default, changed and command-line ini settings @param array $loadedConfig All current ini settings @param array $iniConfig Settings from user ini files @return string
private function mergeLoadedConfig(array $loadedConfig, array $iniConfig) { $content = ''; foreach ($loadedConfig as $name => $value) { // Value will either be null, string or array (HHVM only) if (!is_string($value) || strpos($name, 'xdebug') === 0 || $name === 'apc.mmap_file_mask') { continue; } if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { // Double-quote escape each value $content .= $name.'="'.addcslashes($value, '\\"').'"'.PHP_EOL; } } return $content; }
The asynchronous method of {@link #executeCommandAndCommitIfNeeded(ContextBuilder, VisitableCommand, int)}.
private <T> CompletableFuture<T> executeCommandAndCommitIfNeededAsync(ContextBuilder contextBuilder, VisitableCommand command, int keyCount) { InvocationContext ctx = contextBuilder.create(keyCount); checkLockOwner(ctx, command); //noinspection unchecked return isTxInjected(ctx) ? executeCommandAsyncWithInjectedTx(ctx, command) : (CompletableFuture<T>) invoker.invokeAsync(ctx, command); }
Sets opt out cookie @param {boolean} optOutState true - user opted out of tracking, false - user did not opted out @private @returns {boolean} Info about the success
function setCookie(optOutState) { switch (optOutState) { case true: document.cookie = `${disableStr}=true; expires=Thu, 18 Jan 2038 03:13:59 UTC; path=/`; window[disableStr] = true; break; case false: document.cookie = `${disableStr}=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/`; window[disableStr] = false; break; default: console.warn('setCookie for outOut invalid param optOutState. Param must be boolean'); return false; } return true; }
Get the number of names that have ever existed Return {'status': True, 'count': count} on success Return {'error': ...} on error
def rpc_get_num_names_cumulative( self, **con_info ): db = get_db_state(self.working_dir) num_names = db.get_num_names(include_expired=True) db.close() return self.success_response( {'count': num_names} )
Get Pubtator Bioconcepts from Pubmed Abstract Re-configure the denotations into an annotation dictionary format and collapse duplicate terms so that their spans are in a list.
def get_pubtator(pmid): r = get_url(PUBTATOR_TMPL.replace("PMID", pmid), timeout=10) if r and r.status_code == 200: pubtator = r.json()[0] else: log.error( f"Cannot access Pubtator, status: {r.status_code} url: {PUBTATOR_TMPL.replace('PMID', pmid)}" ) return None known_types = ["CHEBI", "Chemical", "Disease", "Gene", "Species"] for idx, anno in enumerate(pubtator["denotations"]): s_match = re.match(r"(\w+):(\w+)", anno["obj"]) c_match = re.match(r"(\w+):(\w+):(\w+)", anno["obj"]) if c_match: (ctype, namespace, cid) = ( c_match.group(1), c_match.group(2), c_match.group(3), ) if ctype not in known_types: log.info(f"{ctype} not in known_types for Pubtator") if namespace not in known_types: log.info(f"{namespace} not in known_types for Pubtator") pubtator["denotations"][idx][ "obj" ] = f'{pubtator_ns_convert.get(namespace, "UNKNOWN")}:{cid}' pubtator["denotations"][idx]["entity_type"] = pubtator_entity_convert.get( ctype, None ) pubtator["denotations"][idx][ "annotation_type" ] = pubtator_annotation_convert.get(ctype, None) elif s_match: (ctype, cid) = (s_match.group(1), s_match.group(2)) if ctype not in known_types: log.info(f"{ctype} not in known_types for Pubtator") pubtator["denotations"][idx][ "obj" ] = f'{pubtator_ns_convert.get(ctype, "UNKNOWN")}:{cid}' pubtator["denotations"][idx]["entity_type"] = pubtator_entity_convert.get( ctype, None ) pubtator["denotations"][idx][ "annotation_type" ] = pubtator_annotation_convert.get(ctype, None) annotations = {} for anno in pubtator["denotations"]: log.info(anno) if anno["obj"] not in annotations: annotations[anno["obj"]] = {"spans": [anno["span"]]} annotations[anno["obj"]]["entity_types"] = [anno.get("entity_type", [])] annotations[anno["obj"]]["annotation_types"] = [ anno.get("annotation_type", []) ] else: annotations[anno["obj"]]["spans"].append(anno["span"]) del pubtator["denotations"] pubtator["annotations"] = copy.deepcopy(annotations) return pubtator
// recv is a long running goroutine that accepts new data
func (s *Session) recv() { if err := s.recvLoop(); err != nil { s.exitErr(err) } }
shutdown all process @param int $signal
public function shutdown($signal = SIGTERM) { foreach ($this->processes as $process) { if ($process->isRunning()) { $process->shutdown(true, $signal); } } }
Auto Generated Code
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs): config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") cist = ET.SubElement(output, "cist") migrate_time = ET.SubElement(cist, "migrate-time") migrate_time.text = kwargs.pop('migrate_time') callback = kwargs.pop('callback', self._callback) return callback(config)
// ValidateAppNameEnv ensures that the environment variable specifying the // entrypoint of this process is set correctly.
func ValidateAppNameEnv(want string) (r results) { if got := os.Getenv(appNameEnv); got != want { r = append(r, fmt.Errorf("%s not set appropriately (need %q, got %q)", appNameEnv, want, got)) } return }
Return the deposited instance of the OmemoRatchet for the given manager. If there is none yet, create a new one, deposit it and return it. @param manager OmemoManager we want to have the ratchet for. @return OmemoRatchet instance
protected OmemoRatchet<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> getOmemoRatchet(OmemoManager manager) { OmemoRatchet<T_IdKeyPair, T_IdKey, T_PreKey, T_SigPreKey, T_Sess, T_Addr, T_ECPub, T_Bundle, T_Ciph> omemoRatchet = omemoRatchets.get(manager); if (omemoRatchet == null) { omemoRatchet = instantiateOmemoRatchet(manager, omemoStore); omemoRatchets.put(manager, omemoRatchet); } return omemoRatchet; }
Returns relevant URL. @return \moodle_url
public function get_url() { $params = $this->other; // Skip search area and course filters (MDL-33188). if (isset($params['areaids'])) { unset($params['areaids']); } if (isset($params['courseids'])) { unset($params['courseids']); } return new \moodle_url('/search/index.php', $params); }
// Equals returns true if all the fields of this RPC match the // provided RPC. // // This function performs a deep comparison.
func (v *RPC) Equals(rhs *RPC) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } if !bytes.Equal(v.SpanContext, rhs.SpanContext) { return false } if !(v.CallerName == rhs.CallerName) { return false } if !(v.ServiceName == rhs.ServiceName) { return false } if !(v.Encoding == rhs.Encoding) { return false } if !(v.Procedure == rhs.Procedure) { return false } if !((v.Headers == nil && rhs.Headers == nil) || (v.Headers != nil && rhs.Headers != nil && _Map_String_String_Equals(v.Headers, rhs.Headers))) { return false } if !_String_EqualsPtr(v.ShardKey, rhs.ShardKey) { return false } if !_String_EqualsPtr(v.RoutingKey, rhs.RoutingKey) { return false } if !_String_EqualsPtr(v.RoutingDelegate, rhs.RoutingDelegate) { return false } if !((v.Body == nil && rhs.Body == nil) || (v.Body != nil && rhs.Body != nil && bytes.Equal(v.Body, rhs.Body))) { return false } return true }
Get setter name. "setName" -> "name" @param m Method object. @return Property name of this setter.
private static String getSetterName(Method m) { String name = m.getName(); if (name.startsWith("set") && (name.length() >= 4) && m.getReturnType().equals(void.class) && (m.getParameterTypes().length == 1) ) { return Character.toLowerCase(name.charAt(3)) + name.substring(4); } return null; }
Enable the given modules. @param $modules
public function enableModules($modules) { foreach ($modules as $moduleToEnable => $value) { $module = $this->module->get($moduleToEnable); $module->enable(); } }
Rate single type. TODO: Memoize using `$classname` or something (abort for anonymous types!) @type {constructor} target @type {constructor} type @returns {number} The degree of ancestral separation (-1 for none)
function(target, type) { var r = 0, rating = -1, parent = target; if (target === type) { rating = 0; } else { while ((parent = gui.Class.parent(parent))) { r++; if (parent === type) { parent = null; rating = r; } } /* This would rate the degree of descendant separation ... var children; (function descend(t, level) { if ((children = gui.Class.children(t)).length) { if(children.indexOf(type) >-1) { rating = level; } else { children.every(function(c) { descend(c,level + 1); return rating === -1; }); } } }(target,1)); */ } return rating; }
Resolve data by splicing in the completed object @param $databaseResult
public function resolve($databaseResult) { $className = $this->className; try { $object = new $className(); $this->loader ->mapObjectWithOptions($object, $databaseResult); $databaseResult->{$this->fieldName} = $object; } catch (\Exception $e) { //This is fine, just an empty join echo $e->getMessage(); } }
Override polymorphic default to put the subclass-specific fields first
def get_fieldsets(self, request, obj=None): ''' ''' # If subclass declares fieldsets, this is respected if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \ or not self.base_fieldsets: return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj) other_fields = self.get_subclass_fields(request, obj) if other_fields: return ( (self.extra_fieldset_title, {'fields': other_fields}), ) + self.base_fieldsets else: return self.base_fieldsets
Sets the index to the given index without validating. If the index is out of bound the consecutive token() call will throw a runtime exception. @param indexToNavigateTo value to set the cursor's index to.
void index(int indexToNavigateTo) { this.index = 0; this.offset = 0; this.nextSplit = StringUtil.indexOf(path, '.', 0); this.token = null; for (int i = 1; i <= indexToNavigateTo; i++) { if (!advanceToNextToken()) { throw new IndexOutOfBoundsException("Index out of bound " + indexToNavigateTo + " in " + path); } } }
Returns the method meta data for the given method. @param method the method. @return an instance of {@link MethodMetaData}.
private MethodMetaData<? extends Annotation> getMethodMetaData(Method method) { MethodMetaData<? extends Annotation> methodMetaData = methodMetaDataCache.get(method); if (methodMetaData == null) { final String cacheName; final Annotation cacheAnnotation; final AggregatedParameterMetaData aggregatedParameterMetaData; final CacheKeyGenerator cacheKeyGenerator; final CacheDefaults cacheDefaultsAnnotation = method.getDeclaringClass().getAnnotation(CacheDefaults.class); if (method.isAnnotationPresent(CacheResult.class)) { final CacheResult cacheResultAnnotation = method.getAnnotation(CacheResult.class); cacheKeyGenerator = getCacheKeyGenerator(beanManager, cacheResultAnnotation.cacheKeyGenerator(), cacheDefaultsAnnotation); cacheName = getCacheName(method, cacheResultAnnotation.cacheName(), cacheDefaultsAnnotation, true); aggregatedParameterMetaData = getAggregatedParameterMetaData(method, false); cacheAnnotation = cacheResultAnnotation; } else if (method.isAnnotationPresent(CacheRemove.class)) { final CacheRemove cacheRemoveEntryAnnotation = method.getAnnotation(CacheRemove.class); cacheKeyGenerator = getCacheKeyGenerator(beanManager, cacheRemoveEntryAnnotation.cacheKeyGenerator(), cacheDefaultsAnnotation); cacheName = getCacheName(method, cacheRemoveEntryAnnotation.cacheName(), cacheDefaultsAnnotation, false); aggregatedParameterMetaData = getAggregatedParameterMetaData(method, false); cacheAnnotation = cacheRemoveEntryAnnotation; if (cacheName.isEmpty()) { throw log.cacheRemoveEntryMethodWithoutCacheName(method.getName()); } } else if (method.isAnnotationPresent(CacheRemoveAll.class)) { final CacheRemoveAll cacheRemoveAllAnnotation = method.getAnnotation(CacheRemoveAll.class); cacheKeyGenerator = null; cacheName = getCacheName(method, cacheRemoveAllAnnotation.cacheName(), cacheDefaultsAnnotation, false); aggregatedParameterMetaData = getAggregatedParameterMetaData(method, false); cacheAnnotation = cacheRemoveAllAnnotation; if (cacheName.isEmpty()) { throw log.cacheRemoveAllMethodWithoutCacheName(method.getName()); } } else if (method.isAnnotationPresent(CachePut.class)) { final CachePut cachePutAnnotation = method.getAnnotation(CachePut.class); cacheKeyGenerator = getCacheKeyGenerator(beanManager, cachePutAnnotation.cacheKeyGenerator(), cacheDefaultsAnnotation); cacheName = getCacheName(method, cachePutAnnotation.cacheName(), cacheDefaultsAnnotation, true); aggregatedParameterMetaData = getAggregatedParameterMetaData(method, true); cacheAnnotation = cachePutAnnotation; } else { throw log.methodWithoutCacheAnnotation(method.getName()); } final MethodMetaData<? extends Annotation> newCacheMethodMetaData = new MethodMetaData<Annotation>( method, aggregatedParameterMetaData, asSet(method.getAnnotations()), cacheKeyGenerator, cacheAnnotation, cacheName ); methodMetaData = methodMetaDataCache.putIfAbsent(method, newCacheMethodMetaData); if (methodMetaData == null) { methodMetaData = newCacheMethodMetaData; } } return methodMetaData; }
Try selecting abstract page by request parameter. @param string $key @return null|AbstractPage
private function searchPageByRequestKey($key) { $pageId = $this->getRequestParameter($key); if (empty($pageId)) { return null; } return $this->getEntityManager() ->find(AbstractPage::CN(), $pageId); }
This method allows to remove graph from the GraphServer instance @param graphId
public void dropGraph(long graphId) { val builder = new FlatBufferBuilder(128); val off = FlatDropRequest.createFlatDropRequest(builder, graphId); builder.finish(off); val req = FlatDropRequest.getRootAsFlatDropRequest(builder.dataBuffer()); val v = blockingStub.forgetGraph(req); if (v.status() != 0) throw new ND4JIllegalStateException("registerGraph() gRPC call failed"); }
map a function over a glob pattern, relative to a directory
def map_over_glob(fn, path, pattern): """""" return [fn(x) for x in glob.glob(os.path.join(path, pattern))]
解析locale字符串。 <p> Locale字符串是符合下列格式:<code>language_country_variant</code>。 </p> @param localeString 要解析的字符串 @return <code>Locale</code>对象,如果locale字符串为空,则返回<code>null</code>
public static Locale parseLocale(String localeString) { if (localeString == null || localeString.length() == 0) { return Locale.getDefault(); } localeString = localeString.trim(); if (localeString == null) { return null; } String language = ""; String country = ""; String variant = ""; // language int start = 0; int index = localeString.indexOf("_"); if (index >= 0) { language = localeString.substring(start, index).trim(); // country start = index + 1; index = localeString.indexOf("_", start); if (index >= 0) { country = localeString.substring(start, index).trim(); // variant variant = localeString.substring(index + 1).trim(); } else { country = localeString.substring(start).trim(); } } else { language = localeString.substring(start).trim(); } return new Locale(language, country, variant); }