comment
stringlengths
16
255
code
stringlengths
52
3.87M
// acquireChan wraps a signal chan with a func that can be used with rateLimit. // should only be called by rate limiting funcs (that implement deadlock avoidance).
func acquireChan(tokenCh <-chan struct{}) func(context.Context, bool) bool { if tokenCh == nil { // always false: acquire never succeeds; panic if told to block (to avoid deadlock) return func(ctx context.Context, block bool) bool { if block { select { case <-ctx.Done(): default: panic("deadloc...
Collects garbage - removes files from the file system. @return \Zend\Stdlib\ResponseInterface
public function collectAction() { // @todo json $service = $this->getGarbageCollector(); if ($service->collect()) { return $this->redirect()->toRoute('sc-admin/content-manager'); } return $this->redirect() ->toRoute( 'sc-admin/file/dele...
// Str2JSType extract a JavaScript type from a string
func Str2JSType(s string) JSType { var ( output JSType ) s = strings.TrimSpace(s) // santize the given string switch { case isBool(s): output = Bool case isFloat(s): output = Float case isInt(s): output = Int case isNull(s): output = Null default: output = String // if all alternatives have been el...
The parser fires this each time one path has been parsed @param string $path xml path which parsing has ended
public function after_path($path) { $toprocess = false; // If the path being closed matches (same or parent) the first path in the stack // we process pending startend notifications until one matching end is found if ($element = reset($this->startendinfo)) { $elepath = $eleme...
// sendCommand is an auxiliary function to send commands to the AIP1640Driver module
func (a *AIP1640Driver) sendCommand(cmd byte) { a.pinData.Off() a.send(cmd) a.pinData.On() }
// MULTI-SOURCE - Type D: copy([](f|d...), d) -> []B // prepareCopyURLsTypeE - prepares target and source clientURLs for copying.
func prepareCopyURLsTypeD(sourceURLs []string, targetURL string, isRecursive bool, encKeyDB map[string][]prefixSSEPair) <-chan URLs { copyURLsCh := make(chan URLs) go func(sourceURLs []string, targetURL string, copyURLsCh chan URLs) { defer close(copyURLsCh) for _, sourceURL := range sourceURLs { for cpURLs :=...
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceStrategyOptions.
func (in *SourceStrategyOptions) DeepCopy() *SourceStrategyOptions { if in == nil { return nil } out := new(SourceStrategyOptions) in.DeepCopyInto(out) return out }
/* $order array of the fields and the order
public function selectAll($where=false, $order=false, $limit=false) { $clause = false; $values = array(); if ( is_array($where) ) { $retval = self::extractWhere($where, $clause, $values); if ( is_string($retval) ) throw new \Exception($val); } $orderby = '...
Write current root class hierarchy with resolved generics. Use custom writer to modify type rendering (on each line). @param typeWriter custom type writer @return current hierarchy with resolved generics
public String toStringHierarchy(final TypeWriter typeWriter) { final StringBuilder res = new StringBuilder(types.size() * 50); writeHierarchy(root, "", "", res, typeWriter); return res.toString(); }
Start application.
def main(args=None): """""" parser = _parser() # Python 2 will error 'too few arguments' if no subcommand is supplied. # No such error occurs in Python 3, which makes it feasible to check # whether a subcommand was provided (displaying a help message if not). # argparse internals vary significa...
Displace this atom in place
def displace!(x,y,z) self.x += x self.y += y self.z += z end
--------------------------------------------------------- private functions /* get message or service definition class
function getMessageFromPackage(messageType, type, callback) { var packageName = getPackageNameFromMessageType(messageType); var messageName = getMessageNameFromMessageType(messageType); packages.findPackage(packageName, function(error, directory) { var filePath; filePath = path.join(directory, type, messa...
Figure out the sections in drbdadm status
def _analyse_status_type(line): ''' ''' spaces = _count_spaces_startswith(line) if spaces is None: return '' switch = { 0: 'RESOURCE', 2: {' disk:': 'LOCALDISK', ' role:': 'PEERNODE', ' connection:': 'PEERNODE'}, 4: {' peer-disk:': 'PEERDISK'} } ret = ...
Build the client from a dsn Examples: udp+influxdb://username:pass@localhost:4444/databasename @param string $dsn @return Client|Database @throws ClientException
public static function fromDSN($dsn) { $connParams = parse_url($dsn); $schemeInfo = explode('+', $connParams['scheme']); $modifier = null; $scheme = $schemeInfo[0]; $dbName = isset($connParams['path']) ? substr($connParams['path'], 1) : null; if (isset($schemeInfo[1]...
@param InputInterface $input @param OutputInterface $output @return bool|int|null
protected function execute(InputInterface $input, OutputInterface $output) { $this->init($input); $function = $input->getArgument('function'); $idChart = $input->getOption('idChart'); switch ($function) { case 'maj-player': if ($idChart) { ...
Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
@XmlElementDecl(namespace = "http://www.drugbank.ca", name = "rs-id", scope = SnpAdverseDrugReactionType.class) public JAXBElement<String> createSnpAdverseDrugReactionTypeRsId(String value) { return new JAXBElement<String>(_SnpAdverseDrugReactionTypeRsId_QNAME, String.class, SnpAdverseDrugReactionType.class...
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
public EClass getGCBEZ() { if (gcbezEClass == null) { gcbezEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(488); } return gcbezEClass; }
Get a firmware image with provided image_id. :param str image_id: The firmware ID for the image to retrieve (Required) :return: FirmwareImage
def get_firmware_image(self, image_id): api = self._get_api(update_service.DefaultApi) return FirmwareImage(api.firmware_image_retrieve(image_id))
/* (non-Javadoc) @see com.ibm.ws.sib.processor.runtime.SIMPTopicSpaceControllable#deleteLocalSubscriptionControlByID(java.lang.String)
public void deleteLocalSubscriptionControlByID(String id) throws SIMPInvalidRuntimeIDException, SIMPControllableNotFoundException, SIMPException, SIDurableSubscriptionNotFoundException, SIDestinationLockedException, SIResourceException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnable...
使用账号密码方式登录授权 @param string $username 用户名 @param string $password 密码 @return void
public function login($username, $password) { $response = $this->http->get($this->getUrl('oauth2/access_token'), array( 'grant_type' => 'password ', 'username' => $username, 'password' => $password, 'client_id' => $this->appid, 'client_secret' => $this->appSecret, )); $this->result = $response-...
Automatically generated run method @param Request $request @return Response
public function run(Request $request) { $id = $this->getParam('id'); $sport = SportQuery::create() ->leftJoinGroup() ->leftJoinSkill() ->findOneById($id); $pictures = PictureQuery::create() ->useSkillQuery() ->filterBySportId($id) ->endUse() ->count(); $videos = VideoQuery::create() -...
把资源存放到当前上下文 @param IPoolResource $resource @return void
private static function pushResourceToRequestContext(IPoolResource $resource) { $poolResources = RequestContext::get('poolResources', []); $instance = $resource->getInstance(); $poolResources[spl_object_hash($instance)] = $resource; RequestContext::set('poolResources', $poolResources...
Emit an alert monitor.down, which is in the OK state. @param ctx Rule evaluation context.
@Override public void transform(Context<MutableTimeSeriesCollectionPair> ctx) { DateTime now = ctx.getTSData().getCurrentCollection().getTimestamp(); ctx.getTSData().getCurrentCollection().addMetrics(MONITOR_GROUP, get_metrics_(now, ctx)); ctx.getAlertManager().accept(new Alert(now, MONITO...
MySQL SELECT Query/Statement. @param string $table @param array $column @param array $arrayWhere @param string $other @return self type: array/error
public function select($table = '', $column = [], $arrayWhere = [], $other = '') { // handle column array data if (!is_array($column)) { $column = []; } // get field if pass otherwise use * $sField = count($column) > 0 ? implode(', ', $column) : '*'; // ch...
Is required to repaint the control or its snippet? @param string snippet name @return bool
public function isControlInvalid($snippet = NULL) { if ($snippet === NULL) { if (count($this->invalidSnippets) > 0) { return TRUE; } else { $queue = [$this]; do { foreach (array_shift($queue)->getComponents() as $component) { if ($component instanceof IRenderable) { if ($componen...
This method removes the option-bar widget from DOM and re-attaches it at it's original position.<p> Use to avoid mouse-over and mouse-down malfunction.<p>
private void resetOptionbar() { if (m_elementOptionBar != null) { if (getWidgetIndex(m_elementOptionBar) >= 0) { m_elementOptionBar.removeFromParent(); } updateOptionBarPosition(); insert(m_elementOptionBar, 0); } }
// GetBucketNotification - get bucket notification at a given path.
func (c Client) GetBucketNotification(bucketName string) (bucketNotification BucketNotification, err error) { // Input validation. if err := s3utils.CheckValidBucketName(bucketName); err != nil { return BucketNotification{}, err } notification, err := c.getBucketNotification(bucketName) if err != nil { return ...
Get the documentation name. @return string
protected function getDocName() { $name = $this->option('name') ?: $this->name; if (! $name) { $this->comment('A name for the documentation was not supplied. Use the --name option or set a default in the configuration.'); exit; } return $name; }
run all patterns in the playbook
def run(self): ''' ''' plays = [] matched_tags_all = set() unmatched_tags_all = set() # loop through all patterns and run them self.callbacks.on_start() for (play_ds, play_basedir) in zip(self.playbook, self.play_basedirs): play = Play(self, play_ds,...
Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format
def call(self, jsondata): result = yield self.call_py(jsondata) if result is None: defer.returnValue(None) else: defer.returnValue(json.dumps(result))
// RemoveAllBlocksForController removes all the blocks for the controller. // It does not prevent new blocks from being added during / after // removal.
func (st *State) RemoveAllBlocksForController() error { blocks, err := st.AllBlocksForController() if err != nil { return errors.Trace(err) } ops := []txn.Op{} for _, blk := range blocks { ops = append(ops, txn.Op{ C: blocksC, Id: blk.Id(), Remove: true, }) } // Use runRawTransaction as...
/* (non-Javadoc) @see org.mobicents.isup.messages.ISUPMessage#decodeOptionalBody(byte[], byte)
protected void decodeOptionalBody(ISUPParameterFactory parameterFactory, byte[] parameterBody, byte parameterCode) throws ParameterException { switch (parameterCode & 0xFF) { case CauseIndicators._PARAMETER_CODE: CauseIndicators cpn = parameterFactory.createCauseIndicato...
handle layout command
def cmd_layout(self, args): '''''' from MAVProxy.modules.lib import win_layout if len(args) < 1: print("usage: layout <save|load>") return if args[0] == "load": win_layout.load_layout(self.mpstate.settings.vehicle_name) elif args[0] == "save": ...
Get the filename and key of the config name @param $name @return array
public function getInfo($name) { $keys = explode('.', $name); if (is_array($keys)) { $file = array_shift($keys); $key = implode('.', $keys); } else { $file = $name; $key = null; } return ['file' => $file, 'key' => $key]; }
// SetOptions sets the Options field's value.
func (s *IndexFieldStatus) SetOptions(v *IndexField) *IndexFieldStatus { s.Options = v return s }
Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return:
def is_muted(what): state = False for item in solo: if item not in what: state = True else: state = False break for item in mute: if item in what: state = True break return state
// Validate inspects the fields of the type to determine if they are valid.
func (s *JobOperation) Validate() error { invalidParams := request.ErrInvalidParams{Context: "JobOperation"} if s.LambdaInvoke != nil { if err := s.LambdaInvoke.Validate(); err != nil { invalidParams.AddNested("LambdaInvoke", err.(request.ErrInvalidParams)) } } if s.S3PutObjectAcl != nil { if err := s.S3Pu...
Differential cross section dsigma/dEg = Amax(Tp) * F(Tp,Egamma)
def _diffsigma(self, Ep, Egamma): Tp = Ep - self._m_p diffsigma = self._Amax(Tp) * self._F(Tp, Egamma) if self.nuclear_enhancement: diffsigma *= self._nuclear_factor(Tp) return diffsigma
// MarshalBinary implements encoding BinaryMarshaler interface
func (l *Locale) MarshalBinary() ([]byte, error) { obj := new(LocaleEncoding) obj.DefaultDomain = l.defaultDomain obj.Domains = make(map[string][]byte) for k, v := range l.Domains { var err error obj.Domains[k], err = v.MarshalBinary() if err != nil { return nil, err } } obj.Lang = l.lang obj.Path = l...
Function to publish staging or prod version from local tree, or to promote staging to prod, per passed arg. @param {string} pubScope the scope to publish to.
function mdlPublish(pubScope) { let cacheTtl = null; let src = null; let dest = null; if (pubScope === 'staging') { // Set staging specific vars here. cacheTtl = 0; src = 'dist/*'; dest = bucketStaging; } else if (pubScope === 'prod') { // Set prod specific vars here. cacheTtl = 60; ...
Generates chunks of audio that represent the wakeword stream
def generate_wakeword_pieces(self, volume): """""" while True: target = 1 if random() > 0.5 else 0 it = self.pos_files_it if target else self.neg_files_it sample_file = next(it) yield self.layer_with(self.normalize_volume_to(load_audio(sample_file), volume...
Called by TransitionManager to play the transition. This calls createAnimators() to set things up and create all of the animations and then runAnimations() to actually start the animations.
void playTransition(@NonNull ViewGroup sceneRoot) { mStartValuesList = new ArrayList<TransitionValues>(); mEndValuesList = new ArrayList<TransitionValues>(); matchStartAndEnd(mStartValues, mEndValues); ArrayMap<Animator, AnimationInfo> runningAnimators = getRunningAnimators(); s...
Gets the after advice result. @param <T> the generic type @param aspectId the aspect id @return the after advice result
@SuppressWarnings("unchecked") public <T> T getAfterAdviceResult(String aspectId) { return (aspectAdviceResult != null ? (T)aspectAdviceResult.getAfterAdviceResult(aspectId) : null); }
将Json转换成对象. @param json @param valueType @return
@Override public <T> T toObject(String json, Class<T> clazz) { return toObject(json, clazz, false); }
Adds a command to the library @return Application
public function add($command) { $tasks = $this->prepper ->load(get_class($command)) ->describe(); $this->library->add(['task' => $tasks, 'class' => $command]); return $this; }
Warn等级日志,小于Error @param log 日志对象 @param format 格式文本,{} 代表变量 @param arguments 变量对应的参数
public static void warn(Log log, String format, Object... arguments) { warn(log, null, format, arguments); }
sets paragraph format @param PHPRtfLite_ParFormat $parFormat
public function setParFormat(PHPRtfLite_ParFormat $parFormat) { $this->_rtf->registerParFormat($parFormat); $this->_parFormat = $parFormat; }
Performs a pre-processing operation on the input string in the given input language @param input The input text @param inputLanguage The language of the input @return The post-processed text
public final String apply(String input, Language inputLanguage) { if (input != null && Config.get(this.getClass(), inputLanguage, "apply").asBoolean(true)) { return performNormalization(input, inputLanguage); } return input; }
Requests permissions immediately, <b>must be invoked during initialization phase of your application</b>.
@Override @NonNull @CheckReturnValue public Observable<Permission> requestEach(@NonNull final String... permissions) { return Observable.just(TRIGGER) .compose(ensureEach(permissions)); }
Retrieve the information for a zone entity.
def get(self, zone_id): """""" path = '/'.join(['zone', zone_id]) return self.rachio.get(path)
Counts additional occurrences of a property as property in references. @param usageStatistics statistics object where count is stored @param property the property to count @param count the number of times to count the property
private void countPropertyReference(UsageStatistics usageStatistics, PropertyIdValue property, int count) { addPropertyCounters(usageStatistics, property); usageStatistics.propertyCountsReferences.put(property, usageStatistics.propertyCountsReferences.get(property) + count); }
Retrieve all data of repository, paginated @param int $per_page @param array $columns @param string $page_name @param int|null $page @return \Illuminate\Contracts\Pagination\Paginator
public function simplePaginate($per_page = null, $columns = ['*'], $page_name = 'page', $page = null) { $this->newQuery(); // Get the default per page when not set $per_page = $per_page ?: config('repositories.per_page', 15); return $this->query->simplePaginate($per_page, $columns,...
Private function to get the common type from the information of the field @param string $fieldName @param string $nativeType @return string
private function getCommonType($fieldName, $nativeType) { static $types = [ // integers 'int' => CommonTypes::TINT, 'tinyint' => CommonTypes::TINT, 'smallint' => CommonTypes::TINT, 'bigint' => CommonTypes::TINT, // floats 'f...
Filters a context This will return a new context with only the resources that are actually available for use. Uses tags and command line options to make determination.
def filtered_context(context): """""" ctx = Context(context.opt) for resource in context.resources(): if resource.child: continue if resource.filtered(): ctx.add(resource) return ctx
Runs this {@see DayEnumExample}. @param integer $argc The number of arguments. @param string[] $argv The arguments. @return integer Always `0`.
public static function main($argc, array $argv = []) { $firstDay = new self(DayEnum::MONDAY()); $firstDay->tellItLikeItIs(); $thirdDay = new self(DayEnum::WEDNESDAY()); $thirdDay->tellItLikeItIs(); $fifthDay = new self(DayEnum::FRIDAY()); $fifthDay->tellItLikeItIs(); ...
@param int $level @throws \OutOfBoundsException
private function checkLevel(int $level) { if ($level <= 0 || $level > self::MAX_LEVEL_DEPTH) { throw new OutOfBounds( sprintf('Administrative level should be an integer in [1,%d], %d given', self::MAX_LEVEL_DEPTH, $level) ); } }
Filters out boolish items that resemble none "truthy" values. @return array
public static function compact($array, $reindex = false) { $out = array_filter($array, function ($item) { return false !== (bool)$item; }); return false !== $reindex && self::isList($out) ? array_values($out) : $out; }
Handles adding a contact. @param int $userid The id of the user who requested to be a contact @param int $contactid The id of the contact
public static function add_contact(int $userid, int $contactid) { global $DB; $messagecontact = new \stdClass(); $messagecontact->userid = $userid; $messagecontact->contactid = $contactid; $messagecontact->timecreated = time(); $messagecontact->id = $DB->insert_record('m...
Marshall the given parameter object.
public void marshall(ExportSnapshotRecord exportSnapshotRecord, ProtocolMarshaller protocolMarshaller) { if (exportSnapshotRecord == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(exportSnapshotRecor...
Validates that x is a multiple of the reference (`x % ref == 0`)
def is_multiple_of(ref): def is_multiple_of_ref(x): if x % ref == 0: return True else: raise IsNotMultipleOf(wrong_value=x, ref=ref) # raise Failure('x % {ref} == 0 does not hold for x={val}'.format(ref=ref, val=x)) is_multiple_of_ref.__name__ = 'is_mult...
// AddFunc takes a function and runs it repeatedly, adding the return values // as fields. // The function should return error when it has exhausted its values
func (f *fieldHolder) AddFunc(fn func() (string, interface{}, error)) error { for { key, rawVal, err := fn() if err != nil { // fn is done giving us data break } f.AddField(key, rawVal) } return nil }
Deregister removed documents. @param RemoveEvent $event
public function handleRemove(RemoveEvent $event) { $document = $event->getDocument(); $this->documentRegistry->deregisterDocument($document); }
// CheckAddresses returns the uri scheme if the address is valid.
func CheckAddresses(uriList []string, schemes []string) (scheme string) { count := len(uriList) if count < 1 { panic(ErrURIListEmpty) } u, err := url.Parse(uriList[0]) if err != nil { panic(err) } scheme = u.Scheme if sort.SearchStrings(schemes, scheme) == len(schemes) { panic(errors.New("This client desn...
// SetBudgetName sets the BudgetName field's value.
func (s *Budget) SetBudgetName(v string) *Budget { s.BudgetName = &v return s }
redis key: records:tablename: id1 | id2 | id3... eg: the user has three primarykeys id1=1,id2=2,id3=3, so the redisKey is 'records:user:1|2|3'. @return redis key
private String redisKey(ModelExt<?> m) { Table table = m.table(); StringBuilder key = new StringBuilder(); key.append(RECORDS); key.append(table.getName()); key.append(":"); //fetch primary keys' values String[] primaryKeys = table.getPrimaryKey(); //format key for (int idx = 0; idx < primaryKeys.leng...
Return a deferred.
def delete(self, **params): """""" d = self.request('delete', self.instance_url(), params) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
file can be null, meaning stdin
function readSpecFile(file, options) { if (options.verbose > 1) { file ? console.error('GET ' + file) : console.error('GET <stdin>'); } if (!file) { // standard input return readFileStdinAsync(); } else if (file && file.startsWith('http')) { // remote file return ...
Returns the renderer for the given format. @param string $format @throws \AltThree\Badger\Exceptions\InvalidRendererException @return \AltThree\Badger\Render\RenderInterface
protected function getRendererForFormat(string $format) { if (!isset($this->renderers[$format])) { throw new InvalidRendererException('No renders found for the given format: '.$format); } return $this->renderers[$format]; }
Preprocess string to transform all diacritics and remove other special characters than appropriate :param string: :return:
def preprocess(string): string = unicode(string, encoding="utf-8") # convert diacritics to simpler forms string = regex1.sub(lambda x: accents[x.group()], string) # remove all rest of the unwanted characters return regex2.sub('', string).encode('utf-8')
Build a summary list of all the methods in this context
def build_method_summary_list(path_prefix="") collect_methods unless @methods meths = @methods.sort res = [] meths.each do |meth| res << { "name" => CGI.escapeHTML(meth.name), "aref" => "#{path_prefix}\##{meth.aref}" } end res end
Returns the first subset of a given set in this UBTree. @param set the set to search for @return the first subset which is found for the given set or {@code null} if there is none
public SortedSet<T> firstSubset(SortedSet<T> set) { if (this.rootNodes.isEmpty() || set == null || set.isEmpty()) { return null; } return firstSubset(set, this.rootNodes); }
Extracts task enterprise column values. @param id task unique ID @param task task instance @param taskVarData task var data @param metaData2 task meta data
private void processTaskEnterpriseColumns(Integer id, Task task, Var2Data taskVarData, byte[] metaData2) { if (metaData2 != null) { int bits = MPPUtility.getInt(metaData2, 29); task.set(TaskField.ENTERPRISE_FLAG1, Boolean.valueOf((bits & 0x0000800) != 0)); task.set(TaskField.EN...
Parse service name from request @return string|boolean
protected function fetchService() { $service = $this->getRouteParam('service'); $service = $this->parseCanonicalName($service, true); if (preg_match($this->servicePattern, $service)) { return $service; } else { return false; } }
// SetIdentityAttributeValues sets the IdentityAttributeValues field's value.
func (s *TypedLinkSpecifier) SetIdentityAttributeValues(v []*AttributeNameAndValue) *TypedLinkSpecifier { s.IdentityAttributeValues = v return s }
This is more expensive than normal.
@Override public void clear() { // iterate over all keys in originalMap and set them to null in deltaMap for (K key : originalMap.keySet()) { deltaMap.put(key, ErasureUtils.<Collection<V>>uncheckedCast(removedValue)); } }
// removeOpcode will remove any opcode matching ``opcode'' from the opcode // stream in pkscript
func removeOpcode(pkscript []parsedOpcode, opcode byte) []parsedOpcode { retScript := make([]parsedOpcode, 0, len(pkscript)) for _, pop := range pkscript { if pop.opcode.value != opcode { retScript = append(retScript, pop) } } return retScript }
Set language. @param \BlackForest\PiwikBundle\Entity\PiwikLanguage|null $language @return PiwikVisit
public function setLanguage(\BlackForest\PiwikBundle\Entity\PiwikLanguage $language = null) { $this->language = $language; return $this; }
:nocov: @visibility private
def inspect ['{config', *each.map{|key, value| " "+qualified_key(*key)+" => "+value.inspect },'}'].join("\n") end
// SetBudgetName sets the BudgetName field's value.
func (s *DeleteSubscriberInput) SetBudgetName(v string) *DeleteSubscriberInput { s.BudgetName = &v return s }
Get the extension that matches given mimetype. @param string $mimetype @return mixed null when not found, extension (string) when found.
public function getExtension($mimetype) { if (!($extension = array_search($mimetype, $this->mainMimeTypes))) { $extension = array_search($mimetype, $this->mimeTypes); } return !$extension ? null : $extension; }
Public API for generating a URL pathname from a path and parameters.
function generatePath(path = "/", params = {}) { return path === "/" ? path : compilePath(path)(params, { pretty: true }); }
// SetScheduleTimezone sets the ScheduleTimezone field's value.
func (s *GetMaintenanceWindowOutput) SetScheduleTimezone(v string) *GetMaintenanceWindowOutput { s.ScheduleTimezone = &v return s }
Get a dimension. @param Image $image The source image. @param string $field The requested field. @return double|null The dimension.
public function getDimension(Image $image, $field) { if ($this->{$field}) { return (new Dimension($image, $this->getDpr()))->get($this->{$field}); } }
Remove HashTable item @param PHPExcel_IComparable $pSource Item to remove @throws PHPExcel_Exception
public function remove(PHPExcel_IComparable $pSource = null) { $hash = $pSource->getHashCode(); if (isset($this->_items[$hash])) { unset($this->_items[$hash]); $deleteKey = -1; foreach ($this->_keyMap as $key => $value) { if ($deleteKey >= 0) { $this->_keyMap[$key - 1] = $value; } if ($v...
Loop forever, pushing out stats.
def run(self): """""" self.graphite.start() while True: log.debug('Graphite pusher is sleeping for %d seconds', self.period) time.sleep(self.period) log.debug('Pushing stats to Graphite') try: self.push() log.debug('Done pushing stats to Graphite') except: ...
// CheckShell checks that a shell is supported, and returns the correct command name
func CheckShell(shell string) (string, error) { if _, ok := ValidShells[shell]; !ok { return "", fmt.Errorf("unsupported shell: %q", shell) } switch shell { case "powershell": if _, err := exec.LookPath("powershell"); err == nil { return "powershell", nil } else if _, err := exec.LookPath("pwsh"); err == n...
// Roll updates the checksum of the window from the entering byte. You // MUST initialize a window with Write() before calling this method.
func (d *Adler32) Roll(b byte) { // This check costs 10-15% performance. If we disable it, we crash // when the window is empty. If we enable it, we are always correct // (an empty window never changes no matter how much you roll it). //if len(d.window) == 0 { // return //} // extract the entering/leaving bytes ...
Delete a single item with the given ID
def delete(self, id): '''''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) return None
// Refer to the Mailgun documentation for more information.
func (m *Message) SetTrackingOpens(trackingOpens bool) { m.trackingOpens = trackingOpens m.trackingOpensSet = true }
// Not reverses the results of its given child matcher. // // Example usage: // Not(Eq(5)).Matches(4) // returns true // Not(Eq(5)).Matches(5) // returns false
func Not(x interface{}) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} }
Set limit on the number of propagations.
def prop_budget(self, budget): if self.minisat: pysolvers.minisatgh_pbudget(self.minisat, budget)
设置缓存 @param string $key @param mixed $value @param int $expire -1 永不过期 0默认配置 @throws \Error
public static function set($key, $value, $expire = 0) { try { self::getCache()->set($key, $value, $expire); self::release(); } catch (\RuntimeException $e) { self::release(); throw $e; } catch (\Error $e) { self::release(); ...
Outputs the FontAwesomeText object as an HTML string @access protected @return string HTML string of text element
protected function output() { $attrs = ''; $classes = 'fa-layers-text'; $transforms = ''; if (!empty($this->classes) && count($this->classes) > 0) { $classes .= ' ' . implode(' ', $this->classes); } if (!empty($this->attributes) && count($this->attribu...
Return a single frame.
@SuppressWarnings("unused") // called through reflection by RequestServer public FramesV3 fetch(int version, FramesV3 s) { FramesV3 frames = doFetch(version, s); // Summary data is big, and not always there: null it out here. You have to call columnSummary // to force computation of the summary data. ...
Performs all data validation that is appicable to the data value itself @param object - the data value @throws DataValidationException if any of the data constraints are violated
@SuppressWarnings("unchecked") public void postValidate(Object object) throws DataValidationException { if (_values != null || _ranges != null) { if (_values != null) for (Object value: _values) { if (value.equals(object)) return; } if (_ranges != ...
@param ContentInterface $content @return array
protected function extractMediasFromContentType(ContentTypeInterface $contentType) { $mediaIds = array(); $fields = $contentType->getFields(); foreach ($fields as $field) { if ($this->isMediaAttribute($field->getDefaultValue())) { $mediaIds[] = $field->getDefault...
Setter for **self.__splitters** attribute. :param value: Attribute value. :type value: tuple or list
def splitters(self, value): if value is not None: assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format( "splitters", value) for element in value: assert type(element) is unicode, "'{0}' attribute: '{...
Assign float value to inputOutput SFFloat field named speed. Note that our implementation with ExoPlayer that pitch and speed will be set to the same value. @param newValue
public void setSpeed(float newValue) { if (newValue < 0) newValue = 0; this.pitch.setValue( newValue ); this.speed.setValue( newValue ); }
set loglevel based on NODE_DEBUG env variable and create exported methods
function initialize() { var flags = []; Object.keys( levels ).forEach(function( type, level ) { var method = type.toLowerCase(); exports[ method ] = log.bind( exports, type, level, false ); exports[ method ].json = log.bind( exports, type, level, true ); if ( new RegExp( '\\b' + type + '\\b', 'i' )...
Create presets of an image @param string $path
public static function createPresets($path = null, $callback = null) { $moufManager = MoufManager::getMoufManager(); $instances = $moufManager->findInstances('Mouf\\Utils\\Graphics\\MoufImagine\\Controller\\ImagePresetController'); foreach ($instances as $instanceName) { $instance = ...