comment
stringlengths
16
255
code
stringlengths
52
3.87M
Gets the list of <em>instances</em> associated to a virtual host name. @param virtualHostName the virtual hostname for which the instances need to be returned. @return list of <em>instances</em>.
public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) { return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getVipList) .map(AtomicReference::get) .orElseGet(Collections::emptyList); }
Handle the deleted event for the Ban model. @param \Cog\Contracts\Ban\Ban $ban @return void
public function deleted(BanContract $ban): void { $bannable = $ban->bannable()->withBanned()->first(); if ($bannable->bans->count() === 0) { $bannable->unsetBannedFlag()->save(); event(new ModelWasUnbanned($bannable)); } }
Clear sequence numbers in column 1-6 and anything beyond column 72. @param line the line of code @return a line of code without sequence numbers
public String cleanFixedLine(final String line) { StringBuilder cleanedLine = new StringBuilder(); int length = line.length(); /* Clear sequence numbering */ for (int i = 0; i < _startColumn - 1; i++) { cleanedLine.append(" "); } /* Trim anything beyond end column */ if (length > _startColumn - 1) { String areaA = line.substring(_startColumn - 1, (length > _endColumn) ? _endColumn : length); cleanedLine.append(areaA); } return cleanedLine.toString(); }
// DisableVanityNameServers Vanity Name Servers for the given domain // // See https://developer.dnsimple.com/v2/vanity/#disable
func (s *VanityNameServersService) DisableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) { path := versioned(vanityNameServerPath(accountID, domainIdentifier)) vanityNameServerResponse := &vanityNameServerResponse{} resp, err := s.client.delete(path, nil, nil) if err != nil { return nil, err } vanityNameServerResponse.HttpResponse = resp return vanityNameServerResponse, nil }
/* eslint-disable
function adaptor(prompt) { prompt = { ...prompt } switch (prompt.type) { case 'confirm': prompt.type = 'checkbox' prompt.transformType = 'confirm' prompt.value = [prompt.value] prompt.choices = [ { label: 'Yes?', value: true } ] break case 'list': prompt.type = 'radio' prompt.transformType = 'list' break } return prompt }
Create new array <p>Stack: ..., count =&gt; ..., arrayref @param name @param aClass @param size @throws IOException
public void addNewArray(String name, Class<?> aClass, int size) throws IOException { addNewArray(name, Typ.getTypeFor(aClass), size); }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SimpleAntlrPackage.OPTIONS__OPTION_VALUES: return ((InternalEList<?>)getOptionValues()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); }
// IsValidOsArch checks if a OS-architecture combination is valid given a map // of valid OS-architectures
func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error { if os, ok := labels["os"]; ok { if validArchs, ok := validOSArch[os]; !ok { // Not a whitelisted OS. TODO: how to warn rather than fail? validOses := make([]string, 0, len(validOSArch)) for validOs := range validOSArch { validOses = append(validOses, validOs) } sort.Strings(validOses) return fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses) } else { // Whitelisted OS. We check arch here, as arch makes sense only // when os is defined. if arch, ok := labels["arch"]; ok { found := false for _, validArch := range validArchs { if arch == validArch { found = true break } } if !found { return fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs) } } } } return nil }
// ListEmailForwards lists the email forwards for a domain. // // See https://developer.dnsimple.com/v2/domains/email-forwards/#list
func (s *DomainsService) ListEmailForwards(accountID string, domainIdentifier string, options *ListOptions) (*emailForwardsResponse, error) { path := versioned(emailForwardPath(accountID, domainIdentifier, 0)) forwardsResponse := &emailForwardsResponse{} path, err := addURLQueryOptions(path, options) if err != nil { return nil, err } resp, err := s.client.get(path, forwardsResponse) if err != nil { return nil, err } forwardsResponse.HttpResponse = resp return forwardsResponse, nil }
// RoundDown will round tp down to next "full" d.
func RoundDown(t time.Time, d TimeDelta) time.Time { td := d.RoundDown(t) DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(), td.Format("2006-01-02 15:04:05 (Mon)")) return td }
Add method info. @param methodInfoList the method info list @param classNameToClassInfo the map from class name to class info
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) { for (final MethodInfo mi : methodInfoList) { // Index method annotations addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo); // Index method parameter annotations if (mi.parameterAnnotationInfo != null) { for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) { final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i]; if (paramAnnotationInfoArr != null) { for (int j = 0; j < paramAnnotationInfoArr.length; j++) { final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j]; final ClassInfo annotationClassInfo = getOrCreateClassInfo( methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER, classNameToClassInfo); annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION, this); this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo); } } } } } if (this.methodInfo == null) { this.methodInfo = methodInfoList; } else { this.methodInfo.addAll(methodInfoList); } }
send the transaction using the API @param string|array $signed @param string[] $paths @param bool $checkFee @return string the complete raw transaction @throws \Exception
protected function sendTransaction($signed, $paths, $checkFee = false) { return $this->sdk->sendTransaction($this->identifier, $signed, $paths, $checkFee); }
Register application provider Workaround for BC break in https://github.com/laravel/framework/pull/25028 @param string $providerName @param bool $force
protected function appRegister($providerName, $force = false) { if (!$this->appRegisterParameters) { $method = new \ReflectionMethod(get_class($this->app), 'register'); $this->appRegisterParameters = count($method->getParameters()); } if ($this->appRegisterParameters == 3) { $this->app->register($providerName, [], $force); } else { $this->app->register($providerName, $force); } }
Sets or resets the order of the existing schemas in the current search path of the user. This is a PostgreSQL only function. @return void
public function determineExistingSchemaSearchPaths() { $names = $this->getSchemaNames(); $paths = $this->getSchemaSearchPaths(); $this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) { return in_array($v, $names); }); }
/* (non-Javadoc) @see javax.security.enterprise.authentication.mechanism.http.HttpMessageContext#forward(java.lang.String)
@Override public AuthenticationStatus forward(String path) { try { RequestDispatcher requestDispatcher = request.getRequestDispatcher(path); requestDispatcher.forward(request, response); } catch (Exception e) { // TODO: Add serviceability message } return AuthenticationStatus.SEND_CONTINUE; }
@param Shopgate_Model_XmlResultObject $itemNode @return Shopgate_Model_XmlResultObject
public function asXml(Shopgate_Model_XmlResultObject $itemNode) { /** * @var Shopgate_Model_XmlResultObject $stockNode */ $identifierNode = $itemNode->addChildWithCDATA('identifier', $this->getValue()); $identifierNode->addAttribute('uid', $this->getUid()); $identifierNode->addAttribute('type', $this->getType()); return $itemNode; }
创建BeanCopier @param <T> 目标Bean类型 @param source 来源对象,可以是Bean或者Map @param dest 目标Bean对象 @param copyOptions 拷贝属性选项 @return BeanCopier
public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) { return create(source, dest, dest.getClass(), copyOptions); }
// SetCertificate sets the Certificate field's value.
func (s *SslConfiguration) SetCertificate(v string) *SslConfiguration { s.Certificate = &v return s }
/* (non-Javadoc) @see org.joml.Matrix4x3fc#rotateX(float, org.joml.Matrix4x3f)
public Matrix4x3f rotateX(float ang, Matrix4x3f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.rotationX(ang); float sin, cos; if (ang == (float) Math.PI || ang == -(float) Math.PI) { cos = -1.0f; sin = 0.0f; } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) { cos = 0.0f; sin = 1.0f; } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) { cos = 0.0f; sin = -1.0f; } else { sin = (float) Math.sin(ang); cos = (float) Math.cosFromSin(sin, ang); } float rm11 = cos; float rm12 = sin; float rm21 = -sin; float rm22 = cos; // add temporaries for dependent values float nm10 = m10 * rm11 + m20 * rm12; float nm11 = m11 * rm11 + m21 * rm12; float nm12 = m12 * rm11 + m22 * rm12; // set non-dependent values directly dest.m20 = m10 * rm21 + m20 * rm22; dest.m21 = m11 * rm21 + m21 * rm22; dest.m22 = m12 * rm21 + m22 * rm22; // set other values dest.m10 = nm10; dest.m11 = nm11; dest.m12 = nm12; dest.m00 = m00; dest.m01 = m01; dest.m02 = m02; dest.m30 = m30; dest.m31 = m31; dest.m32 = m32; dest.properties = properties & ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return dest; }
get the activity that is started by the first instruction, if exists; return null if the first instruction is a start-transition instruction
protected ActivityImpl determineFirstActivity(ProcessDefinitionImpl processDefinition, ProcessInstanceModificationBuilderImpl modificationBuilder) { AbstractProcessInstanceModificationCommand firstInstruction = modificationBuilder.getModificationOperations().get(0); if (firstInstruction instanceof AbstractInstantiationCmd) { AbstractInstantiationCmd instantiationInstruction = (AbstractInstantiationCmd) firstInstruction; CoreModelElement targetElement = instantiationInstruction.getTargetElement(processDefinition); ensureNotNull(NotValidException.class, "Element '" + instantiationInstruction.getTargetElementId() + "' does not exist in process " + processDefinition.getId(), "targetElement", targetElement); if (targetElement instanceof ActivityImpl) { return (ActivityImpl) targetElement; } else if (targetElement instanceof TransitionImpl) { return (ActivityImpl) ((TransitionImpl) targetElement).getDestination(); } } return null; }
生成文件 @param template 模板 @param context 模板上下文 @param destPath 目标路径(绝对)
public static void toFile(Template template, VelocityContext context, String destPath) { PrintWriter writer = null; try { writer = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false); merge(template, context, writer); } catch (IORuntimeException e) { throw new UtilException(e, "Write Velocity content to [{}] error!", destPath); } finally { IoUtil.close(writer); } }
Read cookie data from the request's cookie data. @param string $key The key you want to read. @return null|string Either the cookie value, or null if the value doesn't exist. @deprecated 3.4.0 Use getCookie() instead.
public function cookie($key) { deprecationWarning( 'ServerRequest::cookie() is deprecated. ' . 'Use getCookie() instead.' ); if (isset($this->cookies[$key])) { return $this->cookies[$key]; } return null; }
Command line interface
def main(): parser = argparse.ArgumentParser( description='Extract the raw gps communication from an ULog file') parser.add_argument('filename', metavar='file.ulg', help='ULog input file') def is_valid_directory(parser, arg): """Check if valid directory""" if not os.path.isdir(arg): parser.error('The directory {} does not exist'.format(arg)) # File exists so return the directory return arg parser.add_argument('-o', '--output', dest='output', action='store', help='Output directory (default is CWD)', metavar='DIR', type=lambda x: is_valid_directory(parser, x)) args = parser.parse_args() ulog_file_name = args.filename msg_filter = ['gps_dump'] ulog = ULog(ulog_file_name, msg_filter) data = ulog.data_list output_file_prefix = os.path.basename(ulog_file_name) # strip '.ulg' if output_file_prefix.lower().endswith('.ulg'): output_file_prefix = output_file_prefix[:-4] # write to different output path? if args.output is not None: output_file_prefix = os.path.join(args.output, output_file_prefix) to_dev_filename = output_file_prefix+'_to_device.dat' from_dev_filename = output_file_prefix+'_from_device.dat' if len(data) == 0: print("File {0} does not contain gps_dump messages!".format(ulog_file_name)) exit(0) gps_dump_data = data[0] # message format check field_names = [f.field_name for f in gps_dump_data.field_data] if not 'len' in field_names or not 'data[0]' in field_names: print('Error: gps_dump message has wrong format') exit(-1) if len(ulog.dropouts) > 0: print("Warning: file contains {0} dropouts".format(len(ulog.dropouts))) print("Creating files {0} and {1}".format(to_dev_filename, from_dev_filename)) with open(to_dev_filename, 'wb') as to_dev_file: with open(from_dev_filename, 'wb') as from_dev_file: msg_lens = gps_dump_data.data['len'] for i in range(len(gps_dump_data.data['timestamp'])): msg_len = msg_lens[i] if msg_len & (1<<7): msg_len = msg_len & ~(1<<7) file_handle = to_dev_file else: file_handle = from_dev_file for k in range(msg_len): file_handle.write(gps_dump_data.data['data['+str(k)+']'][i])
Write the extension to the OutputStream. @param out the OutputStream to write the extension to @exception IOException on encoding errors
public void encode(OutputStream out) throws IOException { DerOutputStream tmp = new DerOutputStream(); if (extensionValue == null) { extensionId = PKIXExtensions.CertificateIssuer_Id; critical = true; encodeThis(); } super.encode(tmp); out.write(tmp.toByteArray()); }
Expires the given session.
private void expireSession(RaftSession session) { if (expiring.add(session.sessionId())) { log.debug("Expiring session due to heartbeat failure: {}", session); appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true, false)) .whenCompleteAsync((entry, error) -> { if (error != null) { expiring.remove(session.sessionId()); return; } appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> { raft.checkThread(); if (isRunning()) { if (commitError == null) { raft.getServiceManager().<Long>apply(entry.index()) .whenCompleteAsync((r, e) -> expiring.remove(session.sessionId()), raft.getThreadContext()); } else { expiring.remove(session.sessionId()); } } }); }, raft.getThreadContext()); } }
Unserializes in instance from an ASCII safe string representation produced by __toString. @param string $string String representation @return BloomFilter Unserialized instance
public static function unserializeFromStringRepresentation($string) { if (!preg_match('~k:(?P<k>\d+)/m:(?P<m>\d+)\((?P<bitfield>[0-9a-zA-Z+/=]+)\)~', $string, $matches)) { throw new InvalidArgumentException('Invalid string representation'); } $bf = new self((int) $matches['m'], (int) $matches['k']); $bf->bitField = base64_decode($matches['bitfield']); return $bf; }
{@inheritDoc} @see \rocket\ei\manage\gui\GuiFieldEditable::createMag($propertyName)
public function getMag(): Mag { $this->contentItemMag = new ContentItemMag($this->label, $this->panelConfigs, $this->targetReadEiFrame, $this->targetEditEiFrame); $this->contentItemMag->setNewMappingFormUrl($this->newMappingFormUrl); $this->contentItemMag->setValue($this->toManyEiField->getValue()); $this->contentItemMag->setReduced($this->reduced); return $this->contentItemMag; }
Convert a string to a byte array, no encoding is used. String must only contain characters <256.
public static byte[] str2bytes(String str) throws IOException { byte[] b=new byte[str.length()]; for(int i=0; i<str.length(); ++i) { char c=str.charAt(i); if(c>255) throw new UnsupportedEncodingException("string contained a char > 255, cannot convert to bytes"); b[i]=(byte)c; } return b; }
Convenient Method for the vibrato effekt @param aktMemo
protected void doVibratoEffekt(ChannelMemory aktMemo) { int periodAdd; switch (aktMemo.vibratoType & 0x03) { case 1: periodAdd = (Helpers.ModRampDownTable[aktMemo.vibratoTablePos]); // Sawtooth break; case 2: periodAdd = (Helpers.ModSquareTable [aktMemo.vibratoTablePos]); // Squarewave break; case 3: periodAdd = (Helpers.ModRandomTable [aktMemo.vibratoTablePos]); // Random. break; default:periodAdd = (Helpers.ModSinusTable [aktMemo.vibratoTablePos]); // Sinus break; } periodAdd = ((periodAdd<<4)*aktMemo.vibratoAmplitude) >> 7; setNewPlayerTuningFor(aktMemo, aktMemo.currentNotePeriod + periodAdd); aktMemo.vibratoTablePos = (aktMemo.vibratoTablePos + aktMemo.vibratoStep) & 0x3F; }
Get the value of a cookie. @param $name @param null $default @return null|string
public static function get($name, $default = null) { if (isset(static::$jar[$name])) { return static::parse(static::$jar[$name]['value']); } $cookie = Request::$cookieData; if (!is_null($value = $cookie->get($name))) { return static::parse($value); } return $default; }
Rails controller stuff ========================
def setup set_descriptor :default get_mxit_info @_mxit = descriptor @_mxit_validated = true @_mxit_validation_types = [] @_mxit_validation_messages = [] @_mxit_emulator = request.headers['X-Mxit-UserId-R'].nil? clean_session # Tidy multi-select if needed if params.include? :_mxit_rails_multi_select input = params[:_mxit_rails_multi_select].to_sym params.delete :_mxit_rails_multi_select array = mxit_form_session[input] || [] array.map! {|item| item.to_sym} set = Set.new array if params.include? :_mxit_rails_multi_select_value value = params[:_mxit_rails_multi_select_value].to_sym params.delete :_mxit_rails_multi_select_value if set.include? value set.delete value else set.add value end end params[input] = set.to_a.map {|item| item.to_s} mxit_form_session[input] = set.to_a.map {|item| item.to_sym} end end
@param \Spryker\Yves\Kernel\Container $container @return \Spryker\Yves\Kernel\Container
public function provideDependencies(Container $container) { $container[self::CLIENT_PAYONE] = function (Container $container) { return $container->getLocator()->payone()->client(); }; $container[self::CLIENT_CUSTOMER] = function (Container $container) { return new PayoneToCustomerBridge($container->getLocator()->customer()->client()); }; $container[self::CLIENT_CART] = function (Container $container) { return new PayoneToCartBridge($container->getLocator()->cart()->client()); }; $container[self::CLIENT_SHIPMENT] = function (Container $container) { return new PayoneToShipmentBridge($container->getLocator()->shipment()->client()); }; $container[self::CLIENT_CALCULATION] = function (Container $container) { return new PayoneToCalculationBridge($container->getLocator()->calculation()->client()); }; return $container; }
State for handling dateto:foo constructs. Potentially emits a token.
function indateto($content){ if (strlen($content) < 8) { // State exit or missing parameter. return true; } // Strip off the dateto: part and add the reminder to the parsed token array $param = trim(substr($content,7)); $this->tokens[] = new search_token(TOKEN_DATETO,$param); return true; }
// WithAnnotations appends or replaces the annotations on the spec with the // provided annotations
func WithAnnotations(annotations map[string]string) SpecOpts { return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error { if s.Annotations == nil { s.Annotations = make(map[string]string) } for k, v := range annotations { s.Annotations[k] = v } return nil } }
Array to mapper criteria @param array $values @param boolean $qmMode force question mark placeholder @return string
public static function buildCriteria(array $values, $qmMode = false) { reset($values); $qmMode = $qmMode ?: is_numeric(key($values)); if ($qmMode) { $result = array_values($values); array_unshift($result, str_repeat('?,', count($values)-1).'?'); return $result; } $result = ['']; foreach ($values as $key => $value) { $key = ":$key"; $result[0] .= ($result[0]?',':'').$key; $result[$key] = $value; } return $result; }
// NewKey returns a new key that can be used to encrypt and decrypt messages.
func NewKey() (*[SecretKeyLength]byte, error) { // get 32-bytes of random from /dev/urandom bytes, err := randomProvider.Bytes(SecretKeyLength) if err != nil { return nil, fmt.Errorf("unable to generate random: %v", err) } return KeySliceToArray(bytes) }
Write data to the connection @param string $data
protected function write(string $data) { $this->clearTimeout(); $this->conn->write($data . static::NEW_LINE); $this->log('<-' . $data); $this->setTimeout(); }
Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arguments are supplied, these names will also be available within the session.
def interact(self, **local): import code code.interact(local=dict(sess=self, **local))
Set a new state to the underlying object @param string $state @throws SMException
protected function setState($state) { if (!in_array($state, $this->config['states'])) { throw new SMException(sprintf( 'Cannot set the state to "%s" to object "%s" with graph %s because it is not pre-defined.', $state, get_class($this->object), $this->config['graph'] )); } $accessor = new PropertyAccessor(); $accessor->setValue($this->object, $this->config['property_path'], $state); }
EVENTS Event handler for a touch start event. Stops the default click event from triggering and stores where we touched @inner @param {object} jqEvent The normalised jQuery event object.
function touchStart(jqEvent) { //If we already in a touch event (a finger already in use) then ignore subsequent ones.. if( getTouchInProgress() ) return; //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe if( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 ) return; //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; var ret, touches = event.touches, evt = touches ? touches[0] : event; phase = PHASE_START; //If we support touches, get the finger count if (touches) { // get the total number of fingers touching the screen fingerCount = touches.length; } //Else this is the desktop, so stop the browser from dragging content else { jqEvent.preventDefault(); //call this on jq event so we are cross browser } //clear vars.. distance = 0; direction = null; pinchDirection=null; duration = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom = 1; pinchDistance = 0; fingerData=createAllFingerData(); maximumsMap=createMaximumsData(); cancelMultiFingerRelease(); // check the number of fingers is what we are looking for, or we are capturing pinches if (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) { // get the coordinates of the touch createFingerData( 0, evt ); startTime = getTimeStamp(); if(fingerCount==2) { //Keep track of the initial pinch distance, so we can calculate the diff later //Store second finger data as start createFingerData( 1, touches[1] ); startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start); } if (options.swipeStatus || options.pinchStatus) { ret = triggerHandler(event, phase); } } else { //A touch with more or less than the fingers we are looking for, so cancel ret = false; } //If we have a return value from the users handler, then return and cancel if (ret === false) { phase = PHASE_CANCEL; triggerHandler(event, phase); return ret; } else { if (options.hold) { holdTimeout = setTimeout($.proxy(function() { //Trigger the event $element.trigger('hold', [event.target]); //Fire the callback if(options.hold) { ret = options.hold.call($element, event, event.target); } }, this), options.longTapThreshold ); } setTouchInProgress(true); } return null; }
// SetTagList sets the TagList field's value.
func (s *TagListMessage) SetTagList(v []*Tag) *TagListMessage { s.TagList = v return s }
// 修改默认或者说全局 appname(应用名)
func (l *Live) SetAppName(appname string) *Live { l.liveReq.AppName = appname return l }
/*[deutsch] <p>Rollt dieses zyklische Jahr um den angegebenen Betrag. </p> @param amount determines how many years/units this instance should be rolled @return changed copy of this instance
public CyclicYear roll(int amount) { if (amount == 0) { return this; } return CyclicYear.of(MathUtils.floorModulo(MathUtils.safeAdd(this.year - 1, amount), 60) + 1); }
Add a task to the executor, it is expected that this method is called on the ResultReceiver thread.
public void addTask (ExecutorTask task) { for (int ii=0, nn=_queue.size(); ii < nn; ii++) { ExecutorTask taskOnQueue = _queue.get(ii); if (taskOnQueue.merge(task)) { return; } } // otherwise, add it on _queue.add(task); // and perhaps start it going now if (!_executingNow) { checkNext(); } }
// List lists the buildclient using the OpenShift client.
func (c *ClientBuildConfigLister) List(label labels.Selector) ([]*buildv1.BuildConfig, error) { list, err := c.client.BuildConfigs(metav1.NamespaceAll).List(metav1.ListOptions{LabelSelector: label.String()}) return buildConfigListToPointerArray(list), err }
Return True if the media type is a valid form media type.
def is_form_media_type(media_type): base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING)) return (base_media_type == 'application/x-www-form-urlencoded' or base_media_type == 'multipart/form-data')
Saves relation between optimizer and search container @param \Magento\Framework\Model\AbstractModel $object Optimizer to save @return void
private function saveSearchContainerRelation(\Magento\Framework\Model\AbstractModel $object) { $searchContainers = $object->getSearchContainer(); if (is_array($searchContainers) && (count($searchContainers) > 0)) { $searchContainerLinks = []; $deleteCondition = OptimizerInterface::OPTIMIZER_ID . " = " . $object->getId(); foreach ($searchContainers as $searchContainer) { $searchContainerName = (string) $searchContainer; // Treat autocomplete apply_to like the quick search. if ($searchContainerName === 'catalog_product_autocomplete') { $searchContainerName = 'quick_search_container'; } $searchContainerData = $object->getData($searchContainerName); $applyTo = is_array($searchContainerData) ? ((bool) $searchContainerData['apply_to'] ?? false) : false; $searchContainerLinks[(string) $searchContainer] = [ OptimizerInterface::OPTIMIZER_ID => (int) $object->getId(), OptimizerInterface::SEARCH_CONTAINER => (string) $searchContainer, 'apply_to' => (int) $applyTo, ]; } $this->getConnection()->delete($this->getTable(OptimizerInterface::TABLE_NAME_SEARCH_CONTAINER), $deleteCondition); $this->getConnection()->insertOnDuplicate( $this->getTable(OptimizerInterface::TABLE_NAME_SEARCH_CONTAINER), $searchContainerLinks ); } }
// SetProcessingConfiguration sets the ProcessingConfiguration field's value.
func (s *ExtendedS3DestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *ExtendedS3DestinationUpdate { s.ProcessingConfiguration = v return s }
Pass through to provider CommentLookupSession.use_federated_book_view
def use_federated_book_view(self): """""" self._book_view = FEDERATED # self._get_provider_session('comment_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_federated_book_view() except AttributeError: pass
/*JWTBearerInterface
public function getClientKey($client_id, $subject) { if (isset($this->jwt[$client_id])) { $jwt = $this->jwt[$client_id]; if ($jwt) { if ($jwt["subject"] == $subject) { return $jwt["key"]; } } } return false; }
Return URL string of Atom link element under parent element. Link with no rel attribute is considered to be rel="alternate" @param parent Consider only children of this parent element @param rel Consider only links with this relationship
private String findAtomLink(final Element parent, final String rel) { String ret = null; final List<Element> linksList = parent.getChildren("link", ATOM_10_NS); if (linksList != null) { for (final Element element : linksList) { final Element link = element; final Attribute relAtt = getAttribute(link, "rel"); final Attribute hrefAtt = getAttribute(link, "href"); if (relAtt == null && "alternate".equals(rel) || relAtt != null && relAtt.getValue().equals(rel)) { ret = hrefAtt.getValue(); break; } } } return ret; }
Render page with assessment(s) result. @throws \common_exception_Error @throws \common_exception_MissingParameter @throws \oat\oatbox\service\ServiceNotFoundException
public function printReport() { if (!$this->hasRequestParameter('id')) { throw new \common_exception_MissingParameter('id'); } $idList = $this->getRequestParameter('id'); $context = $this->getRequestParameter('context'); if (!is_array($idList)) { $idList = [$idList]; } $result = []; /** @var ProctorService $deliveryService */ $deliveryService = ServiceManager::getServiceManager()->get(ProctorService::SERVICE_ID); $currentUser = \common_session_SessionManager::getSession()->getUser(); $deliveries = $deliveryService->getProctorableDeliveries($currentUser, $context); /** @var $assessmentResultsService AssessmentResultsService */ $assessmentResultsService = $this->getServiceManager()->get(AssessmentResultsService::SERVICE_ID); foreach ($idList as $deliveryExecutionId) { $deliveryExecution = ServiceProxy::singleton()->getDeliveryExecution($deliveryExecutionId); $delivery = $deliveryExecution->getDelivery(); if (!isset($deliveries[$delivery->getUri()])) { \common_Logger::i('Attempt to print assessment results for which the proctor ' . $currentUser->getIdentifier() . ' has no access.'); continue; } $deliveryData = $assessmentResultsService->getDeliveryData($deliveryExecution); if (!$deliveryData['end']) { continue; } $result[] = [ 'testTakerData' => $assessmentResultsService->getTestTakerData($deliveryExecution), 'testData' => $assessmentResultsService->getTestData($deliveryExecution), 'resultsData' => $assessmentResultsService->getResultsData($deliveryExecution), 'deliveryData' => $deliveryData, ]; } $this->setData('reports', $result); $this->setData('content-template', 'Reporting/print_report.tpl'); $this->setView('Reporting/layout.tpl'); }
// Provide returns the result of executing the constructor with argument values resolved from a dependency graph
func (p provider) Provide(g Graph) reflect.Value { fnType := reflect.TypeOf(p.constructor) argCount := fnType.NumIn() if fnType.IsVariadic() { argCount = len(p.argPtrs) } args := make([]reflect.Value, argCount, argCount) var inType reflect.Type for i := 0; i < argCount; i++ { arg := g.Resolve(p.argPtrs[i]) argType := arg.Type() if i < fnType.NumIn() { inType = fnType.In(i) } else { inType = fnType.In(fnType.NumIn() - 1) } if inType.Kind() == reflect.Slice { inType = inType.Elem() } if !argType.AssignableTo(inType) { if !argType.ConvertibleTo(inType) { panic(fmt.Sprintf( "arg %d of type %q cannot be assigned or converted to type %q for provider constructor (%s)", i, argType, inType, p.constructor, )) } arg = arg.Convert(inType) } args[i] = arg } return reflect.ValueOf(p.constructor).Call(args)[0] }
@param Request $request @param integer $id @return \Symfony\Component\HttpFoundation\JsonResponse @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
public function updateAction(Request $request, $id) { $this->checkCsrf(); $transUnit = $this->get('lexik_translation.data_grid.request_handler')->updateFromRequest($id, $request); return $this->get('lexik_translation.data_grid.formatter')->createSingleResponse($transUnit); }
// Ensure the directory exists or create it if needed.
func EnsureDir(dir string, mode os.FileMode) error { if fileOptions, err := os.Stat(dir); os.IsNotExist(err) { if errMake := os.MkdirAll(dir, mode); errMake != nil { return fmt.Errorf("Could not create directory %s. %v", dir, err) } } else if err != nil { return fmt.Errorf("Error asserting directory %s: %v", dir, err) } else if !fileOptions.IsDir() { return fmt.Errorf("Path already exists as a file: %s", dir) } return nil }
Update the given MySQL User. @param array $data @return MysqlUser
public function update(array $data) { return $this->forge->updateMysqlUser($this->serverId, $this->id, $data); }
// SetActivityFailedEventDetails sets the ActivityFailedEventDetails field's value.
func (s *HistoryEvent) SetActivityFailedEventDetails(v *ActivityFailedEventDetails) *HistoryEvent { s.ActivityFailedEventDetails = v return s }
Flushes the data buffers to disk. @param force force a synchronous flush (otherwise if the environment has the MDB_NOSYNC flag set the flushes will be omitted, and with MDB_MAPASYNC they will be asynchronous)
public void sync(final boolean force) { if (closed) { throw new AlreadyClosedException(); } final int f = force ? 1 : 0; checkRc(LIB.mdb_env_sync(ptr, f)); }
Handle the command. @var string
public function handle() { $indexConfigurator = $this->getIndexConfigurator(); if ($indexConfigurator && ! $this->alreadyExists($indexConfigurator)) { $this->call('make:index-configurator', [ 'name' => $indexConfigurator, ]); } $searchRule = $this->getSearchRule(); if ($searchRule && ! $this->alreadyExists($searchRule)) { $this->call('make:search-rule', [ 'name' => $searchRule, ]); } parent::handle(); }
Performs a search and returns the match, or null if no match was found or more than one match was found. @since 1.527
public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext); if(r.isEmpty()){ return null; } else if(1==r.size()){ return r.get(0); } else { // we have more than one suggested item, so return the item who's url // contains the query as this is probably the job's name return findClosestSuggestedItem(r, query); } }
r""" Initialize the solution vector (self.petsc_x), which is a dense matrix (1D vector) and defines the rhs vector (self.petsc_b) from the existing data.
def _initialize_b_x(self): """ # Get vector(s) compatible with the matrix, # i.e., with the same parallel layout. self.petsc_x, self.petsc_b = self.petsc_A.getVecs() # Set the solution vector to zeros. self.petsc_x.set(0) # Define the petsc rhs vector from the numpy one. # If the rhs is defined by blocks, use this: PETSc.Vec.setValuesBlocked(self.petsc_b, [sp.arange(self.m)], self.b)
Handles the creating or updating of a stack in CloudFormation. Also makes sure that we don't try to create or update a stack while it is already updating or creating.
def _launch_stack(self, stack, **kwargs): old_status = kwargs.get("status") wait_time = 0 if old_status is PENDING else STACK_POLL_TIME if self.cancel.wait(wait_time): return INTERRUPTED if not should_submit(stack): return NotSubmittedStatus() provider = self.build_provider(stack) try: provider_stack = provider.get_stack(stack.fqn) except StackDoesNotExist: provider_stack = None if provider_stack and not should_update(stack): stack.set_outputs( self.provider.get_output_dict(provider_stack)) return NotUpdatedStatus() recreate = False if provider_stack and old_status == SUBMITTED: logger.debug( "Stack %s provider status: %s", stack.fqn, provider.get_stack_status(provider_stack), ) if provider.is_stack_rolling_back(provider_stack): if 'rolling back' in old_status.reason: return old_status logger.debug("Stack %s entered a roll back", stack.fqn) if 'updating' in old_status.reason: reason = 'rolling back update' else: reason = 'rolling back new stack' return SubmittedStatus(reason) elif provider.is_stack_in_progress(provider_stack): logger.debug("Stack %s in progress.", stack.fqn) return old_status elif provider.is_stack_destroyed(provider_stack): logger.debug("Stack %s finished deleting", stack.fqn) recreate = True # Continue with creation afterwards # Failure must be checked *before* completion, as both will be true # when completing a rollback, and we don't want to consider it as # a successful update. elif provider.is_stack_failed(provider_stack): reason = old_status.reason if 'rolling' in reason: reason = reason.replace('rolling', 'rolled') status_reason = provider.get_rollback_status_reason(stack.fqn) logger.info( "%s Stack Roll Back Reason: " + status_reason, stack.fqn) return FailedStatus(reason) elif provider.is_stack_completed(provider_stack): stack.set_outputs( provider.get_output_dict(provider_stack)) return CompleteStatus(old_status.reason) else: return old_status logger.debug("Resolving stack %s", stack.fqn) stack.resolve(self.context, self.provider) logger.debug("Launching stack %s now.", stack.fqn) template = self._template(stack.blueprint) stack_policy = self._stack_policy(stack) tags = build_stack_tags(stack) parameters = self.build_parameters(stack, provider_stack) force_change_set = stack.blueprint.requires_change_set if recreate: logger.debug("Re-creating stack: %s", stack.fqn) provider.create_stack(stack.fqn, template, parameters, tags, stack_policy=stack_policy) return SubmittedStatus("re-creating stack") elif not provider_stack: logger.debug("Creating new stack: %s", stack.fqn) provider.create_stack(stack.fqn, template, parameters, tags, force_change_set, stack_policy=stack_policy) return SubmittedStatus("creating new stack") try: wait = stack.in_progress_behavior == "wait" if wait and provider.is_stack_in_progress(provider_stack): return WAITING if provider.prepare_stack_for_update(provider_stack, tags): existing_params = provider_stack.get('Parameters', []) provider.update_stack( stack.fqn, template, existing_params, parameters, tags, force_interactive=stack.protected, force_change_set=force_change_set, stack_policy=stack_policy, ) logger.debug("Updating existing stack: %s", stack.fqn) return SubmittedStatus("updating existing stack") else: return SubmittedStatus("destroying stack for re-creation") except CancelExecution: stack.set_outputs(provider.get_output_dict(provider_stack)) return SkippedStatus(reason="canceled execution") except StackDidNotChange: stack.set_outputs(provider.get_output_dict(provider_stack)) return DidNotChangeStatus()
Convert to EEML. Optional parameter describes the version of EEML to generate. Default (and currently only version implemented) is version 5.
def to_eeml(version = nil) if version.nil? || version == 5 # Check that we have some data items if size < 1 raise EEML::NoData.new('EEML requires at least one data item') end # Create EEML eeml = Builder::XmlMarkup.new eeml.instruct! eeml_options = {:xmlns => "http://www.eeml.org/xsd/005", :'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", :'xsi:schemaLocation' => "http://www.eeml.org/xsd/005 http://www.eeml.org/xsd/005/005.xsd"} eeml_options[:version] = version if version eeml.eeml(eeml_options) do env_options = {} env_options[:updated] = @updated_at.xmlschema if @updated_at env_options[:creator] = @creator if @creator env_options[:id] = @id if @id eeml.environment(env_options) do |env| env.title @title if @title env.feed @feed if @feed env.status @status.to_s if @status env.description @description if @description env.icon @icon if @icon env.website @website if @website env.email @email if @email if @location loc_options = {} loc_options[:domain] = @location.domain loc_options[:exposure] = @location.exposure if @location.exposure loc_options[:disposition] = @location.disposition if @location.disposition env.location(loc_options) do |loc| loc.name @location.name if @location.name loc.lat @location.lat if @location.lat loc.lon @location.lon if @location.lon loc.ele @location.ele if @location.ele end end @data_items.each_index do |i| env.data(:id => @data_items[i].id || i) do |data| @data_items[i].tags.each do |tag| data.tag tag end value_options = {} value_options[:maxValue] = @data_items[i].max_value if @data_items[i].max_value value_options[:minValue] = @data_items[i].min_value if @data_items[i].min_value data.value @data_items[i].value, value_options if @data_items[i].unit unit_options = {} unit_options[:symbol] = @data_items[i].unit.symbol if @data_items[i].unit.symbol unit_options[:type] = @data_items[i].unit.type if @data_items[i].unit.type data.unit @data_items[i].unit.name, unit_options end end end end end end end
Returns the calculated age the time of event. @param int $age The age from the database record @return string
private function calculateAge(int $age): string { if ((int) ($age / 365.25) > 0) { $result = (int) ($age / 365.25) . 'y'; } elseif ((int) ($age / 30.4375) > 0) { $result = (int) ($age / 30.4375) . 'm'; } else { $result = $age . 'd'; } return FunctionsDate::getAgeAtEvent($result); }
Option for the user to revert the changes made since it was last published
public function revert() { if ($this->data()->IsModifiedOnStage) { $this->data()->doRevertToLive(); } return $this->redirect($this->data()->Link() . '?stage=Live'); }
// SetOperation sets the Operation field's value.
func (s *DynamoDBAction) SetOperation(v string) *DynamoDBAction { s.Operation = &v return s }
Queue an "event" to be run on the GL rendering thread. @param r the runnable to be run on the GL rendering thread.
public void queueEvent(Runnable r) { synchronized (this) { mEventQueue.add(r); synchronized (sGLThreadManager) { mEventsWaiting = true; sGLThreadManager.notifyAll(); } } }
path doesnt handle ~ resolution, fallback to env variables, solution taken from https://github.com/nodejs/node-v0.x-archive/issues/2857
function tilda(cwd) { if (cwd.substring(0, 1) === '~') { cwd = (process.env.HOME || process.env.HOMEPATH || process.env.HOMEDIR || process.cwd()) + cwd.substr(1); } return path.resolve(cwd); }
This method finds the first parent class which is within the buildbot namespace it prepends the name with as many ">" as the class is subclassed
def getName(obj): # elastic search does not like '.' in dict keys, so we replace by / def sanitize(name): return name.replace(".", "/") if isinstance(obj, _BuildStepFactory): klass = obj.factory else: klass = type(obj) name = "" klasses = (klass, ) + inspect.getmro(klass) for klass in klasses: if hasattr(klass, "__module__") and klass.__module__.startswith("buildbot."): return sanitize(name + klass.__module__ + "." + klass.__name__) else: name += ">" return sanitize(type(obj).__name__)
Returns "a mark" to the current position of this node Cassandra log. This is for use with the from_mark parameter of watch_log_for_* methods, allowing to watch the log from the position when this method was called.
def mark_log(self, filename='system.log'): log_file = os.path.join(self.get_path(), 'logs', filename) if not os.path.exists(log_file): return 0 with open(log_file) as f: f.seek(0, os.SEEK_END) return f.tell()
A safe function for creating a directory tree.
def safe_makedirs(path): """""" try: os.makedirs(path) except OSError as err: if err.errno == errno.EEXIST: if not os.path.isdir(path): raise else: raise
It's kind of redundant to have the server return the foreign keys corresponding to the belongs_to associations (since they'll be in the URL anyway), so we'll try to inject them based on the attributes of the object we just used.
def load(attributes, remove_root=false) attributes = attributes ? attributes.stringify_keys : {} self.class.belongs_to_with_parents.each do |belongs_to_param| attributes["#{belongs_to_param}_id"] ||= prefix_options["#{belongs_to_param}_id".intern] # also set prefix attributes as real attributes. Otherwise, # belongs_to attributes will be stripped out of the response # even if we aren't actually using the association. @attributes["#{belongs_to_param}_id"] = attributes["#{belongs_to_param}_id"] end super(attributes, remove_root) end
Count records of model. @param string $alias Optional alias of count result @return int
public function count($alias = null) { if ($this->controller && $this->controller->hasMethod('count')) { return $this->controller->count($this, $alias); } throw $this->exception('The controller doesn\'t support count', 'NotImplemented') ->addMoreInfo('controller', $this->controller ? $this->controller->short_name : 'none'); }
Sets the StructTypeInfo that declares the total schema of the file in the configuration
public static void setSchemaTypeInfo(Configuration conf, StructTypeInfo schemaTypeInfo) { if (schemaTypeInfo != null) { conf.set(SCHEMA_TYPE_INFO, schemaTypeInfo.getTypeName()); LOG.debug("Set schema typeInfo on conf: {}", schemaTypeInfo); } }
where 语法见 @see WhereRule @param array|string|callable|null $conditions @param string $_ @return \PhpBoot\DB\rules\select\WhereRule
public function findWhere($conditions=null, $_=null) { $query = $this->db->select($this->getColumns()) ->from($this->entity->getTable()); $query->context->resultHandler = function ($result){ foreach ($result as &$i){ $i = $this->entity->make($i, false); } return $result; }; return call_user_func_array([$query, 'where'], func_get_args()); }
Source configuration file.
def source_file(pymux, variables): filename = os.path.expanduser(variables['<filename>']) try: with open(filename, 'rb') as f: for line in f: line = line.decode('utf-8') handle_command(pymux, line) except IOError as e: raise CommandException('IOError: %s' % (e, ))
Modifies the result of each promise from a scalar value to a object containing its fieldname
function wrap(fieldName, promise, args) { return promise(args).then((result) => ({ [fieldName]: result, })); }
Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`. Args: post_dict (dict): dictionary from :class:`PostData.get_POST_data()` Returns: str: Reponse from webform.
def _sendPostDict(post_dict): downer = Downloader() downer.headers["Referer"] = settings.EDEPOSIT_EXPORT_REFERER data = downer.download(settings.ALEPH_EXPORT_URL, post=post_dict) rheaders = downer.response_headers error_msg = rheaders.get("aleph-info", "").lower().strip() if "aleph-info" in rheaders and error_msg.startswith("error"): raise ExportRejectedException( "Export request was rejected by import webform: %s" % rheaders["aleph-info"] ) return data
// buildKubeletConfig is responsible for creating the kubelet configuration
func (b *KubeletBuilder) buildKubeletConfig() (*kops.KubeletConfigSpec, error) { if b.InstanceGroup == nil { glog.Fatalf("InstanceGroup was not set") } kubeletConfigSpec, err := b.buildKubeletConfigSpec() if err != nil { return nil, fmt.Errorf("error building kubelet config: %v", err) } // TODO: Memoize if we reuse this return kubeletConfigSpec, nil }
Verify credentials
def login(self, request): try: user = authenticate(request) if not user: raise AuthenticationFailed("User not authenticated.") if not user.is_active: raise AuthenticationFailed("This user has been disabled.") login(request, user) return Response(UserSerializer(user).data) except AuthError as ex: # This indicates an error that may require attention by the # Treeherder or Taskcluster teams. Logging this to New Relic to # increase visibility. newrelic.agent.record_exception() logger.exception("Error", exc_info=ex) raise AuthenticationFailed(str(ex))
Removes a key by adding a remove entry to the row. The remove is represented as a delta entry so checkpoints can be written asynchronously. @return false if the new record cannot fit into the block.
boolean remove(RowCursor cursor) { int rowHead = _rowHead; int blobTail = _blobTail; rowHead -= cursor.removeLength(); if (rowHead < blobTail) { return false; } byte []buffer = _buffer; // buffer[rowHead] = REMOVE; cursor.getRemove(buffer, rowHead); // cursor.getKey(buffer, rowHead + ColumnState.LENGTH); rowHead(rowHead); validateBlock(cursor.row()); return true; }
Retrieve model for route model binding @param mixed $value @return \Illuminate\Database\Eloquent\Model|null
public function resolveRouteBinding($value) { if (! (ctype_digit($value) || is_int($value))) { return null; } try { $value = App::make('fakeid')->decode((int) $value); } catch (Exception $e) { return null; } return $this->where($this->getRouteKeyName(), $value)->first(); }
// NewGrip takes the name for a logging instance and creates a new // Grip instance with configured with a local, standard output logging. // The default level is "Notice" and the threshold level is "info."
func NewGrip(name string) *Grip { sender, _ := send.NewNativeLogger(name, send.LevelInfo{ Threshold: level.Trace, Default: level.Trace, }) return &Grip{impl: sender} }
Set the state of the BFD session.
def _set_state(self, new_state, diag=None): old_state = self._session_state LOG.info("[BFD][%s][STATE] State changed from %s to %s.", hex(self._local_discr), bfd.BFD_STATE_NAME[old_state], bfd.BFD_STATE_NAME[new_state]) self._session_state = new_state if new_state == bfd.BFD_STATE_DOWN: if diag is not None: self._local_diag = diag self._desired_min_tx_interval = 1000000 self._is_polling = True self._update_xmit_period() elif new_state == bfd.BFD_STATE_UP: self._desired_min_tx_interval = self._cfg_desired_min_tx_interval self._is_polling = True self._update_xmit_period() self.app.send_event_to_observers( EventBFDSessionStateChanged(self, old_state, new_state))
/* TODO: Too general; this should be split into overloaded methods. Is that possible?
XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) { if (nameValue instanceof XMLName) { return ((XMLName)nameValue).toQname(); } else if (nameValue instanceof QName) { QName qname = (QName)nameValue; return qname.getDelegate(); } else if ( nameValue instanceof Boolean || nameValue instanceof Number || nameValue == Undefined.instance || nameValue == null ) { throw badXMLName(nameValue); } else { String local = null; if (nameValue instanceof String) { local = (String)nameValue; } else { local = ScriptRuntime.toString(nameValue); } return toNodeQName(cx, local, attribute); } }
Check whether order is cancelled. $param boolean $strict @return boolean
public function isCancelled( $strict = true ) { if( $strict ) { return $this->status == self::STATUS_CANCELLED; } return $this->status >= self::STATUS_CANCELLED; }
Internally called to reallocate the indexes. This method should be called when the filtered model changes its element size
protected void reallocateIndexes() { if (this.indexes == null || this.indexes.length != getFilteredModel().getSize()) { this.indexes = new int[getFilteredModel().getSize()]; } applyConstraint(); }
Convenience method, calls {@link #view(String, Object)} internally. The keys in the map are converted to String values. @param values map with values to pass to view.
protected void view(Map<String, Object> values){ for(String key:values.keySet() ){ view(key, values.get(key)); } }
handle commands from user
def process_stdin(line): '''''' if line is None: sys.exit(0) line = line.strip() if not line: return args = shlex.split(line) cmd = args[0] if cmd == 'help': k = command_map.keys() k.sort() for cmd in k: (fn, help) = command_map[cmd] print("%-15s : %s" % (cmd, help)) return if cmd == 'exit': mestate.exit = True return if not cmd in command_map: print("Unknown command '%s'" % line) return (fn, help) = command_map[cmd] try: fn(args[1:]) except Exception as e: print("ERROR in command %s: %s" % (args[1:], str(e)))
List all active quotes on an account
def cli(env): """""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
/* Check if reduced-form input >= 2^255-19
private static final boolean is_overflow(long10 x) { return ( ((x._0 > P26-19)) && ((x._1 & x._3 & x._5 & x._7 & x._9) == P25) && ((x._2 & x._4 & x._6 & x._8) == P26) ) || (x._9 > P25); }
put @param key @param value @return V
public V put(K key, V value) { if (isHighPrioEnabled) { return highPrioMap.put(key, value); } else { return lowPrioMap.put(key, value); } }
////////////////////////////////////////////////// Converts a single value into its Postgres format.
function formatValue(value, fm, cc) { if (typeof value === 'function') { return formatValue(resolveFunc(value, cc), fm, cc); } const ctf = getCTF(value); // Custom Type Formatting if (ctf) { fm |= ctf.rawType ? fmFlags.raw : 0; return formatValue(resolveFunc(ctf.toPostgres, value), fm, cc); } const isRaw = !!(fm & fmFlags.raw); fm &= ~fmFlags.raw; switch (fm) { case fmFlags.alias: return $as.alias(value); case fmFlags.name: return $as.name(value); case fmFlags.json: return $as.json(value, isRaw); case fmFlags.csv: return $as.csv(value); case fmFlags.value: return $as.value(value); default: break; } if (isNull(value)) { throwIfRaw(isRaw); return 'null'; } switch (typeof value) { case 'string': return $to.text(value, isRaw); case 'boolean': return $to.bool(value); case 'number': return $to.number(value); case 'symbol': throw new TypeError('Type Symbol has no meaning for PostgreSQL: ' + value.toString()); default: if (value instanceof Date) { return $to.date(value, isRaw); } if (value instanceof Array) { return $to.array(value); } if (value instanceof Buffer) { return $to.buffer(value, isRaw); } return $to.json(value, isRaw); } }
Парсит элемент и извлекает из него аргументы @param DOMElement $element @return void
protected function parseArgs(DOMElement $element) { $args = XmlUtil::getChildElements($element, 'arg'); foreach ($args as $arg) { $name = XmlUtil::getRequiredAttributeValue($arg, 'name'); $this->args[$name] = XmlUtil::getText($arg); } }
Returns a line formatted as comment. @param string $text @param array $style @return string
public function error(string $text, array $style = []): string { return $this->line($text, ['fg' => static::RED] + $style); }
Returns the current paths unique ID. @return string|null
public function getId() { if ($output = $this->execute('fsutil file queryfileid', $this->path)) { if ((bool) preg_match('/(\d{1}[x].*)/', $output[0], $matches)) { return $matches[0]; } } }
Register a new model (models)
def post(self): """""" self.set_header("Content-Type", "application/json") key = uuid.uuid4().hex metadata = json.loads(self.request.body.decode()) metadata["uuid"] = key self.database[key] = metadata result = json.dumps({"uuid": key}) self.write(result)
// SetName sets the Name field's value.
func (s *CreateRemoteAccessSessionInput) SetName(v string) *CreateRemoteAccessSessionInput { s.Name = &v return s }
// Metadata returns meta data about the overlay driver such as // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
func (d *Driver) Metadata(id string) (map[string]string, error) { dir := d.dir(id) if _, err := os.Stat(dir); err != nil { return nil, err } metadata := map[string]string{ "WorkDir": path.Join(dir, "work"), "MergedDir": path.Join(dir, "merged"), "UpperDir": path.Join(dir, "diff"), } lowerDirs, err := d.getLowerDirs(id) if err != nil { return nil, err } if len(lowerDirs) > 0 { metadata["LowerDir"] = strings.Join(lowerDirs, ":") } return metadata, nil }
@param WKBBuffer $buffer @param int $srid @return Geometry @throws GeometryIOException
protected function readGeometry(WKBBuffer $buffer, int $srid) : Geometry { $buffer->readByteOrder(); $this->readGeometryHeader($buffer, $geometryType, $hasZ, $hasM, $srid); $cs = new CoordinateSystem($hasZ, $hasM, $srid); switch ($geometryType) { case Geometry::POINT: return $this->readPoint($buffer, $cs); case Geometry::LINESTRING: return $this->readLineString($buffer, $cs); case Geometry::CIRCULARSTRING: return $this->readCircularString($buffer, $cs); case Geometry::COMPOUNDCURVE: return $this->readCompoundCurve($buffer, $cs); case Geometry::POLYGON: return $this->readPolygon($buffer, $cs); case Geometry::CURVEPOLYGON: return $this->readCurvePolygon($buffer, $cs); case Geometry::MULTIPOINT: return $this->readMultiPoint($buffer, $cs); case Geometry::MULTILINESTRING: return $this->readMultiLineString($buffer, $cs); case Geometry::MULTIPOLYGON: return $this->readMultiPolygon($buffer, $cs); case Geometry::GEOMETRYCOLLECTION: return $this->readGeometryCollection($buffer, $cs); case Geometry::POLYHEDRALSURFACE: return $this->readPolyhedralSurface($buffer, $cs); case Geometry::TIN: return $this->readTIN($buffer, $cs); case Geometry::TRIANGLE: return $this->readTriangle($buffer, $cs); } throw GeometryIOException::unsupportedWKBType($geometryType); }