comment
stringlengths
16
255
code
stringlengths
52
3.87M
Bootstrap the application services.
public function boot() { if ( ! $this->app->routesAreCached()) { require __DIR__ . '/routes.php'; } $this->publishes([ __DIR__ . '/../config/config.php' => config_path('laravelimage.php'), ]); $this->registerBladeExtensions(); }
Retrieve related objects. @param key {string} The relation key to fetch models for. @param options {object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'. @return {xhr} An array or request objects
function( key, options ) { options || ( options = {} ); var rel = this.getRelation( key ), keyContents = rel && rel.keyContents, toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) { var id = _.isString( item ) || _.isNumber( item ) ? item : item[ rel.relatedModel.prototype.idAttribute ]; return id && !Backbone.Relational.store.find( rel.relatedModel, id ); }, this ); if ( toFetch && toFetch.length ) { // Create a model for each entry in 'keyContents' that is to be fetched var models = _.map( toFetch, function( item ) { if ( typeof( item ) === 'object' ) { var model = new rel.relatedModel( item ); } else { var attrs = {}; attrs[ rel.relatedModel.prototype.idAttribute ] = item; var model = new rel.relatedModel( attrs ); } return model; }, this ); // Try if the 'collection' can provide a url to fetch a set of models in one request. if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) { var setUrl = rel.related.url( models ); } // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. // To make sure it can, test if the url we got by supplying a list of models to fetch is different from // the one supplied for the default fetch action (without args to 'url'). if ( setUrl && setUrl !== rel.related.url() ) { var opts = _.defaults( { error: function() { var args = arguments; _.each( models, function( model ) { model.destroy(); options.error && options.error.apply( model, args ); }) }, url: setUrl }, options, { add: true } ); var requests = [ rel.related.fetch( opts ) ]; } else { var requests = _.map( models, function( model ) { var opts = _.defaults( { error: function() { model.destroy(); options.error && options.error.apply( model, arguments ); } }, options ); return model.fetch( opts ); }, this ); } } return _.isUndefined( requests ) ? [] : requests; }
Parse, extract and load assets from the stylesheet content @param string $css the stylesheet content
private function loadStyleSheetAsset($css){ $imageRe = "/url\\s*\\(['|\"]?([^)]*\.(png|jpg|jpeg|gif|svg))['|\"]?\\)/mi"; $importRe = "/@import\\s*(url\\s*\\()?['\"]?([^;]*)['\"]/mi"; $fontFaceRe = "/@font-face\\s*\\{(.*)?\\}/mi"; $fontRe = "/url\\s*\\(['|\"]?([^)'|\"]*)['|\"]?\\)/i"; //extract images preg_match_all($imageRe, $css, $matches); if(isset($matches[1])){ foreach($matches[1] as $match){ $this->addAsset('img', $match); } } //extract @import preg_match_all($importRe, $css, $matches); if(isset($matches[2])){ foreach($matches[2] as $match){ $this->addAsset('css', $match); } } //extract fonts preg_match_all($fontFaceRe, $css, $matches); if(isset($matches[1])){ foreach($matches[1] as $faceMatch){ preg_match_all($fontRe, $faceMatch, $fontMatches); if(isset($fontMatches[1])){ foreach($fontMatches[1] as $fontMatch){ $this->addAsset('font', $fontMatch); } } } } }
Function executed when running the script with the -install switch
def install(): """""" # Create Spyder start menu folder # Don't use CSIDL_COMMON_PROGRAMS because it requres admin rights # This is consistent with use of CSIDL_DESKTOPDIRECTORY below # CSIDL_COMMON_PROGRAMS = # C:\ProgramData\Microsoft\Windows\Start Menu\Programs # CSIDL_PROGRAMS = # C:\Users\<username>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs start_menu = osp.join(get_special_folder_path('CSIDL_PROGRAMS'), 'Spyder (Py%i.%i %i bit)' % (sys.version_info[0], sys.version_info[1], struct.calcsize('P')*8)) if not osp.isdir(start_menu): os.mkdir(start_menu) directory_created(start_menu) # Create Spyder start menu entries python = osp.abspath(osp.join(sys.prefix, 'python.exe')) pythonw = osp.abspath(osp.join(sys.prefix, 'pythonw.exe')) script = osp.abspath(osp.join(sys.prefix, 'scripts', 'spyder')) if not osp.exists(script): # if not installed to the site scripts dir script = osp.abspath(osp.join(osp.dirname(osp.abspath(__file__)), 'spyder')) workdir = "%HOMEDRIVE%%HOMEPATH%" import distutils.sysconfig lib_dir = distutils.sysconfig.get_python_lib(plat_specific=1) ico_dir = osp.join(lib_dir, 'spyder', 'windows') # if user is running -install manually then icons are in Scripts/ if not osp.isdir(ico_dir): ico_dir = osp.dirname(osp.abspath(__file__)) desc = 'The Scientific Python Development Environment' fname = osp.join(start_menu, 'Spyder (full).lnk') create_shortcut(python, desc, fname, '"%s"' % script, workdir, osp.join(ico_dir, 'spyder.ico')) file_created(fname) fname = osp.join(start_menu, 'Spyder-Reset all settings.lnk') create_shortcut(python, 'Reset Spyder settings to defaults', fname, '"%s" --reset' % script, workdir) file_created(fname) current = True # only affects current user root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("", EWS)), "", 0, winreg.REG_SZ, '"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix)) winreg.SetValueEx(winreg.CreateKey(root, KEY_C1 % ("NoCon", EWS)), "", 0, winreg.REG_SZ, '"%s" "%s\Scripts\spyder" "%%1"' % (pythonw, sys.prefix)) # Create desktop shortcut file desktop_folder = get_special_folder_path("CSIDL_DESKTOPDIRECTORY") fname = osp.join(desktop_folder, 'Spyder.lnk') desc = 'The Scientific Python Development Environment' create_shortcut(pythonw, desc, fname, '"%s"' % script, workdir, osp.join(ico_dir, 'spyder.ico')) file_created(fname)
Get the min and max values for a response body group @param string $group The name of the group @throws InvalidArgumentException @return array An array with two keys, min and max, which represents the min and max values for $group
protected function getResponseCodeGroupRange($group) { switch ($group) { case 'informational': $min = 100; $max = 199; break; case 'success': $min = 200; $max = 299; break; case 'redirection': $min = 300; $max = 399; break; case 'client error': $min = 400; $max = 499; break; case 'server error': $min = 500; $max = 599; break; default: throw new InvalidArgumentException(sprintf('Invalid response code group: %s', $group)); } return [ 'min' => $min, 'max' => $max, ]; }
Check if a piece of text is in the list of countries
def is_country(self, text): """""" ct_list = self._just_cts.keys() if text in ct_list: return True else: return False
Handle the drag end. Apply the correct positioning to the draggable element
function () { var element = this.getElement(); // This is to handle if there is a scroll element.onselectstart = Aria.returnTrue; if (this.overlay) { // remove overlay here this.overlay.$dispose(); this.overlay = null; } if (this.proxy && this.proxy.overlay) { element.style.top = (this._elementInitialPosition.top + this._movableGeometry.y - this._movableInitialGeometry.y) + "px"; element.style.left = (this._elementInitialPosition.left + this._movableGeometry.x - this._movableInitialGeometry.x) + "px"; this.proxy.$dispose(); this.proxy = null; } this.$raiseEvent("dragend"); }
// Field is the field to be used for random number generation. // This parameter is compulsory when a Seed is set and ignored // otherwise. Note that documents that have the same value for a // field will get the same score.
func (fn *RandomFunction) Field(field string) *RandomFunction { fn.field = field return fn }
Expects an exception with an authorization_paramaters field in its raw_json
def session_hook(exception): safeprint( "The resource you are trying to access requires you to " "re-authenticate with specific identities." ) params = exception.raw_json["authorization_parameters"] message = params.get("session_message") if message: safeprint("message: {}".format(message)) identities = params.get("session_required_identities") if identities: id_str = " ".join(identities) safeprint( "Please run\n\n" " globus session update {}\n\n" "to re-authenticate with the required identities".format(id_str) ) else: safeprint( 'Please use "globus session update" to re-authenticate ' "with specific identities".format(id_str) ) exit_with_mapped_status(exception.http_status)
Adds a value to a writer if value is not <code>null</code>. @param writer writer to add object to. @param field field name to set. @param value field value. @throws JSONException if io error occurs.
public static void addIfNotNull(JSONWriter writer, String field, Boolean value) throws JSONException { if (value == null) return; writer.key(field); writer.value(value); }
Read a duration. @param units duration units @param duration duration value @return Duration instance
private Duration getDuration(TimeUnit units, Double duration) { Duration result = null; if (duration != null) { double durationValue = duration.doubleValue() * 100.0; switch (units) { case MINUTES: { durationValue *= MINUTES_PER_DAY; break; } case HOURS: { durationValue *= HOURS_PER_DAY; break; } case DAYS: { durationValue *= 3.0; break; } case WEEKS: { durationValue *= 0.6; break; } case MONTHS: { durationValue *= 0.15; break; } default: { throw new IllegalArgumentException("Unsupported time units " + units); } } durationValue = Math.round(durationValue) / 100.0; result = Duration.getInstance(durationValue, units); } return result; }
Initializes the found DFU device so that we can program it.
def init(): """""" global __dev, __cfg_descr devices = get_dfu_devices(idVendor=__VID, idProduct=__PID) if not devices: raise ValueError('No DFU device found') if len(devices) > 1: raise ValueError("Multiple DFU devices found") __dev = devices[0] __dev.set_configuration() # Claim DFU interface usb.util.claim_interface(__dev, __DFU_INTERFACE) # Find the DFU configuration descriptor, either in the device or interfaces __cfg_descr = None for cfg in __dev.configurations(): __cfg_descr = find_dfu_cfg_descr(cfg.extra_descriptors) if __cfg_descr: break for itf in cfg.interfaces(): __cfg_descr = find_dfu_cfg_descr(itf.extra_descriptors) if __cfg_descr: break # Get device into idle state for attempt in range(4): status = get_status() if status == __DFU_STATE_DFU_IDLE: break elif (status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE): abort_request() else: clr_status()
Executes the command @param InputInterface $input Command input @param OutputInterface $output Command output
protected function execute( InputInterface $input, OutputInterface $output ) { Log::instance()->setOutput( $output ); $repository = RepositoryManager::instance()->setup( $input->getArgument( 'repository' ) ); if ( ! $repository ) { Log::instance()->write( 'Repository not configured. Before creating the repository, you must configure. Run `wpsnapshots configure ' . $repository . '`', 0, 'error' ); return 1; } $create_s3 = $repository->getS3()->createBucket(); $s3_setup = true; if ( true !== $create_s3 ) { if ( 'BucketExists' === $create_s3 || 'BucketAlreadyOwnedByYou' === $create_s3 || 'BucketAlreadyExists' === $create_s3 ) { Log::instance()->write( 'S3 already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create S3 bucket.', 0, 'error' ); $s3_setup = false; } } $create_db = $repository->getDB()->createTables(); $db_setup = true; if ( true !== $create_db ) { if ( 'ResourceInUseException' === $create_db ) { Log::instance()->write( 'DynamoDB table already setup.', 0, 'warning' ); } else { Log::instance()->write( 'Could not create DynamoDB table.', 0, 'error' ); $db_setup = false; } } if ( ! $db_setup || ! $s3_setup ) { Log::instance()->write( 'Repository could not be created.', 0, 'error' ); return 1; } else { Log::instance()->write( 'Repository setup!', 0, 'success' ); } }
Generate the final CSS string
def create_css(self, rules): style = rules[0].legacy_compiler_options.get( 'style', self.compiler.output_style) debug_info = self.compiler.generate_source_map if style == 'legacy': sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', False, '', '\n', '\n', '\n', debug_info elif style == 'compressed': sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = False, '', '', False, '', '', '', '', False elif style == 'compact': sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', '', False, '\n', ' ', '\n', ' ', debug_info elif style == 'expanded': sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', False, '\n', '\n', '\n', '\n', debug_info else: # if style == 'nested': sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg = True, ' ', ' ', True, '\n', '\n', '\n', ' ', debug_info return self._create_css(rules, sc, sp, tb, nst, srnl, nl, rnl, lnl, dbg)
Stores the members of the set resulting from the intersection of all the given sets.
function sinterstore(destination /* key-1, key-N, req*/) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args[args.length - 1] : null; var list = this.sinter.apply(this, args); if(list.length) { this.setKey( destination, new Set(list), undefined, undefined, undefined, req); } return list.length; }
Adds a header entry value to the header. For example use this to set the source RPM package name on your RPM @param tag the header tag to set @param value the value to set the header entry with
public void addHeaderEntry( final Tag tag, final String value) { format.getHeader().createEntry(tag, value); }
to join the data that does not fit into memory. @param masterLabels label of master data @param masterColumns master column's @param dataColumns data column's @param masterPath master data HDFS path @return this @throws DataFormatException
public SimpleJob setBigJoin(String[] masterLabels, String[] masterColumns, String[] dataColumns, String masterPath) throws DataFormatException { String separator = conf.get(SEPARATOR); return setBigJoin(masterLabels, masterColumns, dataColumns, masterPath, separator); }
Gets information from the #WINDOWS file. Checks the #WINDOWS file to see if it has any info that was not found in #SYSTEM (topics, index or default page.
def GetWindowsInfo(self): ''' ''' result, ui = chmlib.chm_resolve_object(self.file, '/#WINDOWS') if (result != chmlib.CHM_RESOLVE_SUCCESS): return -1 size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, 8) if (size < 8): return -2 buff = array.array('B', text) num_entries = self.GetDWORD(buff, 0) entry_size = self.GetDWORD(buff, 4) if num_entries < 1: return -3 size, text = chmlib.chm_retrieve_object(self.file, ui, 8l, entry_size) if (size < entry_size): return -4 buff = array.array('B', text) toc_index = self.GetDWORD(buff, 0x60) idx_index = self.GetDWORD(buff, 0x64) dft_index = self.GetDWORD(buff, 0x68) result, ui = chmlib.chm_resolve_object(self.file, '/#STRINGS') if (result != chmlib.CHM_RESOLVE_SUCCESS): return -5 size, text = chmlib.chm_retrieve_object(self.file, ui, 0l, ui.length) if (size == 0): return -6 if (not self.topics): self.topics = self.GetString(text, toc_index) if not self.topics.startswith("/"): self.topics = "/" + self.topics if (not self.index): self.index = self.GetString(text, idx_index) if not self.index.startswith("/"): self.index = "/" + self.index if (dft_index != 0): self.home = self.GetString(text, dft_index) if not self.home.startswith("/"): self.home = "/" + self.home
Search and load every installed plugin through entry points.
def load_installed_plugins(): """""" providers = {} checkers = {} for entry_point in pkg_resources.iter_entry_points(group='archan'): obj = entry_point.load() if issubclass(obj, Provider): providers[entry_point.name] = obj elif issubclass(obj, Checker): checkers[entry_point.name] = obj return collections.namedtuple( 'Plugins', 'providers checkers')( providers=providers, checkers=checkers)
Parse the request command input. Input: Request Handle Output: Request Handle updated with parsed input. Return code - 0: ok, non-zero: error
def parseCmdline(rh): rh.printSysLog("Enter powerVM.parseCmdline") if rh.totalParms >= 2: rh.userid = rh.request[1].upper() else: # Userid is missing. msg = msgs.msg['0010'][1] % modId rh.printLn("ES", msg) rh.updateResults(msgs.msg['0010'][0]) rh.printSysLog("Exit powerVM.parseCmdLine, rc: " + rh.results['overallRC']) return rh.results['overallRC'] if rh.totalParms == 2: rh.subfunction = rh.userid rh.userid = '' if rh.totalParms >= 3: rh.subfunction = rh.request[2].upper() # Verify the subfunction is valid. if rh.subfunction not in subfuncHandler: # Subfunction is missing. subList = ', '.join(sorted(subfuncHandler.keys())) msg = msgs.msg['0011'][1] % (modId, subList) rh.printLn("ES", msg) rh.updateResults(msgs.msg['0011'][0]) # Parse the rest of the command line. if rh.results['overallRC'] == 0: rh.argPos = 3 # Begin Parsing at 4th operand generalUtils.parseCmdline(rh, posOpsList, keyOpsList) waiting = 0 if rh.results['overallRC'] == 0: if rh.subfunction == 'WAIT': waiting = 1 if rh.parms['desiredState'] not in vmOSUpDownStates: # Desired state is not: down, off, on or up. msg = msgs.msg['0013'][1] % (modId, rh.parms['desiredState'], ", ".join(vmOSUpDownStates)) rh.printLn("ES", msg) rh.updateResults(msgs.msg['0013'][0]) if (rh.results['overallRC'] == 0 and 'wait' in rh.parms): waiting = 1 if 'desiredState' not in rh.parms: if rh.subfunction in ['ON', 'RESET', 'REBOOT']: rh.parms['desiredState'] = 'up' else: # OFF and SOFTOFF default to 'off'. rh.parms['desiredState'] = 'off' if rh.results['overallRC'] == 0 and waiting == 1: if rh.subfunction == 'ON' or rh.subfunction == 'RESET': if ('desiredState' not in rh.parms or rh.parms['desiredState'] not in vmOSUpStates): # Desired state is not: on or up. msg = msgs.msg['0013'][1] % (modId, rh.parms['desiredState'], ", ".join(vmOSUpStates)) rh.printLn("ES", msg) rh.updateResults(msgs.msg['0013'][0]) if rh.results['overallRC'] == 0: if 'maxWait' not in rh.parms: rh.parms['maxWait'] = 300 if 'poll' not in rh.parms: rh.parms['poll'] = 15 rh.parms['maxQueries'] = (rh.parms['maxWait'] + rh.parms['poll'] - 1) / rh.parms['poll'] # If we had to do some rounding, give a warning # out to the command line user that the wait # won't be what they expected. if rh.parms['maxWait'] % rh.parms['poll'] != 0: msg = msgs.msg['0017'][1] % (modId, rh.parms['maxWait'], rh.parms['poll'], rh.parms['maxQueries'] * rh.parms['poll'], rh.parms['maxQueries']) rh.printLn("W", msg) rh.printSysLog("Exit powerVM.parseCmdLine, rc: " + str(rh.results['overallRC'])) return rh.results['overallRC']
Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value.
def thread_data(name, value=NOTHING, ct=None): ''' ''' ct = ct or current_thread() if is_mainthread(ct): loc = process_data() elif not hasattr(ct, '_pulsar_local'): ct._pulsar_local = loc = {} else: loc = ct._pulsar_local if value is not NOTHING: if name in loc: if loc[name] is not value: raise RuntimeError( '%s is already available on this thread' % name) else: loc[name] = value return loc.get(name)
// SetNextToken sets the NextToken field's value.
func (s *ListRobotApplicationsInput) SetNextToken(v string) *ListRobotApplicationsInput { s.NextToken = &v return s }
-- delete ------------------------
@Override public boolean delete(Object bean) throws OptimisticLockException { methodCalls.add(MethodCall.of("bean").with("bean", bean)); capturedBeans.addDeleted(bean); if (persistDeletes) { return delete.delete(bean, null); } return true; }
// Next returns true if there are any values remaining in the iterator.
func (k *tsmBatchKeyIterator) Next() bool { RETRY: // Any merged blocks pending? if len(k.merged) > 0 { k.merged = k.merged[1:] if len(k.merged) > 0 { return true } } // Any merged values pending? if k.hasMergedValues() { k.merge() if len(k.merged) > 0 || k.hasMergedValues() { return true } } // If we still have blocks from the last read, merge them if len(k.blocks) > 0 { k.merge() if len(k.merged) > 0 || k.hasMergedValues() { return true } } // Read the next block from each TSM iterator for i, v := range k.buf { if len(v) != 0 { continue } iter := k.iterators[i] if iter.Next() { key, minTime, maxTime, typ, _, b, err := iter.Read() if err != nil { k.err = err } var blk *block if cap(k.buf[i]) > len(k.buf[i]) { k.buf[i] = k.buf[i][:len(k.buf[i])+1] blk = k.buf[i][len(k.buf[i])-1] if blk == nil { blk = &block{} k.buf[i][len(k.buf[i])-1] = blk } } else { blk = &block{} k.buf[i] = append(k.buf[i], blk) } blk.minTime = minTime blk.maxTime = maxTime blk.key = key blk.typ = typ blk.b = b blk.readMin = math.MaxInt64 blk.readMax = math.MinInt64 // This block may have ranges of time removed from it that would // reduce the block min and max time. blk.tombstones = iter.r.TombstoneRange(key, blk.tombstones[:0]) blockKey := key for bytes.Equal(iter.PeekNext(), blockKey) { iter.Next() key, minTime, maxTime, typ, _, b, err := iter.Read() if err != nil { k.err = err } var blk *block if cap(k.buf[i]) > len(k.buf[i]) { k.buf[i] = k.buf[i][:len(k.buf[i])+1] blk = k.buf[i][len(k.buf[i])-1] if blk == nil { blk = &block{} k.buf[i][len(k.buf[i])-1] = blk } } else { blk = &block{} k.buf[i] = append(k.buf[i], blk) } blk.minTime = minTime blk.maxTime = maxTime blk.key = key blk.typ = typ blk.b = b blk.readMin = math.MaxInt64 blk.readMax = math.MinInt64 blk.tombstones = iter.r.TombstoneRange(key, blk.tombstones[:0]) } } if iter.Err() != nil { k.err = iter.Err() } } // Each reader could have a different key that it's currently at, need to find // the next smallest one to keep the sort ordering. var minKey []byte var minType byte for _, b := range k.buf { // block could be nil if the iterator has been exhausted for that file if len(b) == 0 { continue } if len(minKey) == 0 || bytes.Compare(b[0].key, minKey) < 0 { minKey = b[0].key minType = b[0].typ } } k.key = minKey k.typ = minType // Now we need to find all blocks that match the min key so we can combine and dedupe // the blocks if necessary for i, b := range k.buf { if len(b) == 0 { continue } if bytes.Equal(b[0].key, k.key) { k.blocks = append(k.blocks, b...) k.buf[i] = k.buf[i][:0] } } if len(k.blocks) == 0 { return false } k.merge() // After merging all the values for this key, we might not have any. (e.g. they were all deleted // through many tombstones). In this case, move on to the next key instead of ending iteration. if len(k.merged) == 0 { goto RETRY } return len(k.merged) > 0 }
Determines if a file is dirty @private @param {!File} file - file to test @return {boolean} true if the file is dirty, false otherwise
function _isOpenAndDirty(file) { // working set item might never have been opened; if so, then it's definitely not dirty var docIfOpen = DocumentManager.getOpenDocumentForPath(file.fullPath); return (docIfOpen && docIfOpen.isDirty); }
Get this object properties REST: GET /hosting/web/{serviceName}/envVar/{key} @param serviceName [required] The internal name of your hosting @param key [required] Name of the variable
public OvhEnvVar serviceName_envVar_key_GET(String serviceName, String key) throws IOException { String qPath = "/hosting/web/{serviceName}/envVar/{key}"; StringBuilder sb = path(qPath, serviceName, key); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhEnvVar.class); }
Send the given notification immediately. @param \Illuminate\Support\Collection|array|mixed $notifiables @param mixed $notification @param array|null $channels @return void
public function sendNow($notifiables, $notification, array $channels = null) { $notifiables = $this->formatNotifiables($notifiables); $original = clone $notification; foreach ($notifiables as $notifiable) { if (empty($viaChannels = $channels ?: $notification->via($notifiable))) { continue; } $this->withLocale($this->preferredLocale($notifiable, $notification), function () use ($viaChannels, $notifiable, $original) { $notificationId = Str::uuid()->toString(); foreach ((array) $viaChannels as $channel) { $this->sendToNotifiable($notifiable, $notificationId, clone $original, $channel); } }); } }
// NewPrefixV0 returns a CIDv0 prefix with the specified multihash type. // DEPRECATED: Use V0Builder
func NewPrefixV0(mhType uint64) Prefix { return Prefix{ MhType: mhType, MhLength: mh.DefaultLengths[mhType], Version: 0, Codec: DagProtobuf, } }
This method is intended for internal use only. Returns the marshaled request configured with additional parameters to enable operation dry-run.
@Override public Request<DescribeSecurityGroupsRequest> getDryRunRequest() { Request<DescribeSecurityGroupsRequest> request = new DescribeSecurityGroupsRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
This will fail if there are duplicate beans in the Spring context. Beans that are configured in the bootstrap context will not be considered duplicate beans.
public void assertUniqueBeans(Set<String> ignoredDuplicateBeanNames) { for (BeanohBeanFactoryMethodInterceptor callback : callbacks) { Map<String, List<BeanDefinition>> beanDefinitionMap = callback .getBeanDefinitionMap(); for (String key : beanDefinitionMap.keySet()) { if (!ignoredDuplicateBeanNames.contains(key)) { List<BeanDefinition> definitions = beanDefinitionMap .get(key); List<String> resourceDescriptions = new ArrayList<String>(); for (BeanDefinition definition : definitions) { String resourceDescription = definition .getResourceDescription(); if (resourceDescription == null) { resourceDescriptions.add(definition.getBeanClassName()); }else if (!resourceDescription .endsWith("-BeanohContext.xml]")) { if(!resourceDescriptions.contains(resourceDescription)){ resourceDescriptions.add(resourceDescription); } } } if (resourceDescriptions.size() > 1) { throw new DuplicateBeanDefinitionException("Bean '" + key + "' was defined " + resourceDescriptions.size() + " times.\n" + "Either remove duplicate bean definitions or ignore them with the 'ignoredDuplicateBeanNames' method.\n" + "Configuration locations:" + messageUtil.list(resourceDescriptions)); } } } } }
测试是否以数字开头,负数也是数字,但是不支持科学表达式模型 @return if matches a digit character
public boolean matchesDigit() { return !isEmpty() && (Character.isDigit(queue.charAt(pos)) || queue.charAt(pos) == '-' && remainingLength() >= 2 && Character.isDigit(queue.charAt(pos + 1))); }
// Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled.
func (c *ServerGetBotConfigCall) Context(ctx context.Context) *ServerGetBotConfigCall { c.ctx_ = ctx return c }
Checks the selector value. @param $value @return bool
public function checkValue(&$value) { if (is_string($value)) { $value = Placeholder::replaceStringsAndComments($value); $value = Placeholder::removeCommentPlaceholders($value, true); $value = preg_replace('/[ ]+/', ' ', $value); $value = Placeholder::replaceStringPlaceholders($value, true); return true; } else { throw new \InvalidArgumentException( "Invalid type '" . gettype($value). "' for argument 'value' given." ); } }
Cleans the text from mentions, by providing a context message. @param \CharlotteDunois\Yasmin\Models\Message $message @param string $text @return string
static function cleanContent(\CharlotteDunois\Yasmin\Models\Message $message, string $text) { /** @var \CharlotteDunois\Yasmin\Interfaces\ChannelInterface $channel */ foreach($message->mentions->channels as $channel) { $text = \str_replace('<#'.$channel->getId().'>', '#'.$channel->name, $text); } /** @var \CharlotteDunois\Yasmin\Models\Role $role */ foreach($message->mentions->roles as $role) { $text = \str_replace($role->__toString(), $role->name, $text); } /** @var \CharlotteDunois\Yasmin\Models\User $user */ foreach($message->mentions->users as $user) { $guildCheck = ($message->channel instanceof \CharlotteDunois\Yasmin\Interfaces\GuildChannelInterface && $message->channel->getGuild()->members->has($user->id)); $text = \preg_replace('/<@!?'.$user->id.'>/', ($guildCheck ? $message->channel->getGuild()->members->get($user->id)->displayName : $user->username), $text); } return $text; }
Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes.
def iterclass(cls): for field in dir(cls): if hasattr(cls, field): value = getattr(cls, field) yield field, value
Convert datetime.datetime to timestamp :param obj: value to (possibly) convert
def json_encode_default(obj): ''' ''' if isinstance(obj, (datetime, date)): result = dt2ts(obj) else: result = json_encoder.default(obj) return to_encoding(result)
Attempt to immediately acquire a shared read lock. @param locker object which might be write or upgrade lock owner @return true if acquired
public final boolean tryLockForRead(L locker) { int state = mState; if (state >= 0) { // no write lock is held if (isReadWriteFirst() || isReadLockHeld(locker)) { do { if (incrementReadLocks(state)) { adjustReadLockCount(locker, 1); return true; } // keep looping on CAS failure if a reader or upgrader mucked with the state } while ((state = mState) >= 0); } } else if (mOwner == locker) { // keep looping on CAS failure if a reader or upgrader mucked with the state while (!incrementReadLocks(state)) { state = mState; } adjustReadLockCount(locker, 1); return true; } return false; }
Get a specific attribute for this tag. @param string @attribute @return string|null
public function getAttribute($attribute) { return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null; }
Initialize JSON structure. @return Path @deprecated
public function initializeStructure() { $structure = [ 'id' => $this->getId(), 'name' => $this->getName(), 'description' => $this->getDescription(), 'manualProgressionAllowed' => $this->manualProgressionAllowed, 'steps' => [], ]; $this->setStructure(json_encode($structure)); return $this; }
Emits the record clicked signal for the given item, provided the signals are not currently blocked. :param item | <QTreeWidgetItem>
def emitRecordMiddleClicked(self, item): # emit that the record has been double clicked if isinstance(item, XOrbRecordItem) and not self.signalsBlocked(): self.recordMiddleClicked.emit(item.record())
// ReturnSubs returns substitutions to the pool. USE WITH CAUTION.
func ReturnSubs(sub Subs) { switch s := sub.(type) { case mSubs: for k := range s { delete(s, k) } mSubPool.Put(sub) case *sSubs: size := cap(s.s) - 2 if size > 0 && size < poolSize+1 { // reset to empty for i := range s.s { s.s[i] = Substitution{} } s.s = s.s[:size] sSubPool[size-1].Put(sub) } } }
Converts the RP Record to a String
String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(mailbox); sb.append(" "); sb.append(textDomain); return sb.toString(); }
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TopologySpec) DeepCopyInto(out *TopologySpec) { *out = *in if in.Bastion != nil { in, out := &in.Bastion, &out.Bastion *out = new(BastionSpec) (*in).DeepCopyInto(*out) } if in.DNS != nil { in, out := &in.DNS, &out.DNS *out = new(DNSSpec) **out = **in } return }
Returns the shipment state label. @param string|ShipmentInterface $stateOrShipment @return string
public function getShipmentStateLabel($stateOrShipment) { $state = $stateOrShipment instanceof ShipmentInterface ? $stateOrShipment->getState() : $stateOrShipment; return $this->translator->trans(ShipmentStates::getLabel($state)); }
print header row allows user to override
def print_header_row r, c, len, value, color, attr #acolor = $promptcolor @graphic.printstring r, c+@left_margin, "%-*s" % [len-@left_margin ,value], color, attr end
Ensure that datetime fields are correctly formatted. @param string $type @param string $value @return string|FragmentInterface|\DateTime @throws DefaultValueException
protected function formatDatetime(string $type, $value) { if ($value === 'current_timestamp()') { $value = self::DATETIME_NOW; } return parent::formatDatetime($type, $value); }
// SetTrainingStartTime sets the TrainingStartTime field's value.
func (s *TrainingJob) SetTrainingStartTime(v time.Time) *TrainingJob { s.TrainingStartTime = &v return s }
Maps this exception to a response object. @return Response this exception maps to.
public static Response toResponse(Response.Status status, String wwwAuthHeader) { Response.ResponseBuilder rb = Response.status(status); if (wwwAuthHeader != null) { rb.header("WWW-Authenticate", wwwAuthHeader); } return rb.build(); }
Calls the post init hubs :param dict parser_result: Dictionary with the parsed arguments
def post_setup_plugins(parser_result): if not isinstance(parser_result, dict): parser_result = vars(parser_result) plugins.run_post_inits(parser_result)
// Convert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec is an autogenerated conversion function.
func Convert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec(in *kops.LyftVPCNetworkingSpec, out *LyftVPCNetworkingSpec, s conversion.Scope) error { return autoConvert_kops_LyftVPCNetworkingSpec_To_v1alpha1_LyftVPCNetworkingSpec(in, out, s) }
Application booted, let's dispatch the routes. @return callable
protected function dispatchToRouter() : Closure { return function ($request) { return $this->router->setContainer($this->container)->dispatch($request); }; }
// SetOutputArtifactDetails sets the OutputArtifactDetails field's value.
func (s *ActionType) SetOutputArtifactDetails(v *ArtifactDetails) *ActionType { s.OutputArtifactDetails = v return s }
Calls a JavaScript method on the object. @param method The name of the method. @param returnType The return type. @param args Method arguments. @param <T> Java type for the return value. @return A return value.
@Nullable protected final <T> T jsiiCall(final String method, final Class<T> returnType, @Nullable final Object... args) { return JsiiObjectMapper.treeToValue(JsiiObject.engine.getClient() .callMethod(this.objRef, method, JsiiObjectMapper.valueToTree(args)), returnType); }
Relay chat messages to and from clients.
def chat(ws): lag_tolerance_secs = float(request.args.get("tolerance", 0.1)) client = Client(ws, lag_tolerance_secs=lag_tolerance_secs) client.subscribe(request.args.get("channel")) gevent.spawn(client.heartbeat) client.publish()
call api, handle error, return response @param Message $req @param String $method @param String $uri @param function $handler function($response, $bizerror, $common) create response oject or throw biz error exception @return Message $result
public function callApi(Message $req, $method, $uri, $handler) { // check handler, php before 5.4 doesn't support Type Hinting of callable if (!is_callable($handler)) { throw new GeneralException("Can not find response handler."); } $data = [ 'json' => (object) $req->to_array(), 'http_errors' => false, ]; $response = $this->request($method, $uri, $data); $rawContent = $response->getBody()->getContents(); $content = json_decode($rawContent, true); if (!$content) { throw new GeneralException("Response is not json data: " . $rawContent); } $statusCode = $response->getStatusCode(); switch ($statusCode) { case 200: // happy path if (isset($content)) { return $handler($content, "", ""); } else { throw new GeneralException("Cannot find response body: " . $rawContent); } break; case 400: // biz error if (isset($content)) { return $handler("", $content, ""); } throw new GeneralException("Cannot find Biz Error body: " . $rawContent); break; case 420: // common error if (isset($content)) { return $handler("", "", $content); } throw new GeneralException("Cannot find Common Error body: " . $rawContent); break; case 500: // internal error throw new InternalServerErrorException("Internal server error: " . $rawContent); break; } }
Execute an Http GET request. @param $path @param array $parameters @return mixed
protected function get($path, array $parameters = array()) { if (count($parameters) > 0) { $path .= '?' . http_build_query($parameters); } $response = $this->client->getHttpClient()->get($path); return $this->parseResponse($response); }
Deletes the expired contexts. @return int[] The number of deleted contexts.
public function process_approved_deletions() : array { $this->trace->output('Checking requirements'); if (!$this->check_requirements()) { $this->trace->output('Requirements not met. Cannot process expired retentions.', 1); return [0, 0]; } $this->trace->output('Fetching all approved and expired contexts for deletion.'); $expiredcontexts = expired_context::get_records(['status' => expired_context::STATUS_APPROVED]); $this->trace->output('Done.', 1); $totalprocessed = 0; $usercount = 0; $coursecount = 0; foreach ($expiredcontexts as $expiredctx) { $context = \context::instance_by_id($expiredctx->get('contextid'), IGNORE_MISSING); if (empty($context)) { // Unable to process this request further. // We have no context to delete. $expiredctx->delete(); continue; } $this->trace->output("Deleting data for " . $context->get_context_name(), 2); if ($this->delete_expired_context($expiredctx)) { $this->trace->output("Done.", 3); if ($context instanceof \context_user) { $usercount++; } else { $coursecount++; } $totalprocessed++; if ($totalprocessed >= $this->get_delete_limit()) { break; } } } return [$coursecount, $usercount]; }
Sets id @param string $id id @return $this
public function setId($id) { if (!is_null($id) && (!preg_match("/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/", $id))) { throw new \InvalidArgumentException("invalid value for $id when calling StackService., must conform to the pattern /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/."); } $this->container['id'] = $id; return $this; }
Set the Trigger's {@link JobDataMap}, adding any values to it that were already set on this TriggerBuilder using any of the other 'usingJobData' methods. @return the updated TriggerBuilder @see ITrigger#getJobDataMap()
@Nonnull public TriggerBuilder <T> usingJobData (final JobDataMap newJobDataMap) { // add any existing data to this new map newJobDataMap.putAll (m_aJobDataMap); m_aJobDataMap = newJobDataMap; // set new map as the map to use return this; }
// SetFlow sets the Flow field's value.
func (s *CreateFlowOutput) SetFlow(v *Flow) *CreateFlowOutput { s.Flow = v return s }
<pre> Performs generic data validation for the operation to be performed </pre>
protected void validate(String operationType) throws Exception { super.validate(operationType); MPSString id_validator = new MPSString(); id_validator.setConstraintIsReq(MPSConstants.DELETE_CONSTRAINT, true); id_validator.setConstraintIsReq(MPSConstants.MODIFY_CONSTRAINT, true); id_validator.validate(operationType, id, "\"id\""); MPSString name_validator = new MPSString(); name_validator.setConstraintCharSetRegEx(MPSConstants.GENERIC_CONSTRAINT,"[ a-zA-Z0-9_#.:@=-]+"); name_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128); name_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1); name_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true); name_validator.validate(operationType, name, "\"name\""); MPSString type_validator = new MPSString(); type_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128); type_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1); type_validator.validate(operationType, type, "\"type\""); MPSBoolean is_default_validator = new MPSBoolean(); is_default_validator.validate(operationType, is_default, "\"is_default\""); MPSString username_validator = new MPSString(); username_validator.setConstraintCharSetRegEx(MPSConstants.GENERIC_CONSTRAINT,"[ a-zA-Z0-9_#.:@=-]+"); username_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 127); username_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1); username_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true); username_validator.validate(operationType, username, "\"username\""); MPSString password_validator = new MPSString(); password_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 127); password_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1); password_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true); password_validator.validate(operationType, password, "\"password\""); MPSString snmpversion_validator = new MPSString(); snmpversion_validator.validate(operationType, snmpversion, "\"snmpversion\""); MPSString snmpcommunity_validator = new MPSString(); snmpcommunity_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 31); snmpcommunity_validator.validate(operationType, snmpcommunity, "\"snmpcommunity\""); MPSString snmpsecurityname_validator = new MPSString(); snmpsecurityname_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 31); snmpsecurityname_validator.validate(operationType, snmpsecurityname, "\"snmpsecurityname\""); MPSString snmpsecuritylevel_validator = new MPSString(); snmpsecuritylevel_validator.validate(operationType, snmpsecuritylevel, "\"snmpsecuritylevel\""); MPSString snmpauthprotocol_validator = new MPSString(); snmpauthprotocol_validator.validate(operationType, snmpauthprotocol, "\"snmpauthprotocol\""); MPSString snmpauthpassword_validator = new MPSString(); snmpauthpassword_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 31); snmpauthpassword_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 8); snmpauthpassword_validator.validate(operationType, snmpauthpassword, "\"snmpauthpassword\""); MPSString snmpprivprotocol_validator = new MPSString(); snmpprivprotocol_validator.validate(operationType, snmpprivprotocol, "\"snmpprivprotocol\""); MPSString snmpprivpassword_validator = new MPSString(); snmpprivpassword_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 31); snmpprivpassword_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 8); snmpprivpassword_validator.validate(operationType, snmpprivpassword, "\"snmpprivpassword\""); }
return quality score format - might return several if ambiguous.
def guessFormat(self): '''''' c = [ord(x) for x in self.quals] mi, ma = min(c), max(c) r = [] for entry_format, v in iteritems(RANGES): m1, m2 = v if mi >= m1 and ma < m2: r.append(entry_format) return r
Bail to send new saved data back to our modal handler. @param int $item_id Item ID. @param string $item_title Item title. @param object $field_args Field arguments.
public function admin_modal_bail( $item_id, $item_title, $field_args ) { $model_data = $this->build_dfv_field_item_data_recurse_item( $item_id, $item_title, $field_args ); ?> <script type="text/javascript"> window.parent.jQuery( window.parent ).trigger( 'dfv:modal:update', <?php echo wp_json_encode( $model_data, JSON_HEX_TAG ); ?> ); </script> <?php die(); }
Is the given line a diff header line. diff --git a/some/file b/some/file @param string $line @return bool
private function isHeaderLine(string $line): bool { $matches = []; if (preg_match('#^diff --git [a|b|c|i|w|o]/(.*) [a|b|c|i|w|o]/(.*)#', $line, $matches)) { $this->appendCollectedFileAndChanges(); $this->currentOperation = File::OP_MODIFIED; $this->currentFileName = $matches[2]; return true; } return false; }
// SetTimeoutSeconds sets the TimeoutSeconds field's value.
func (s *SendCommandInput) SetTimeoutSeconds(v int64) *SendCommandInput { s.TimeoutSeconds = &v return s }
Returns a route definition by the name of the route. @param string $name The name of the route @return RouteDefinition The route definition with the given name
public function getRouteDefinitionByName(string $name): RouteDefinition { if (!isset($this->routesByName[$name])) { throw new \InvalidArgumentException("Invalid route name '$name'"); } return $this->getRouteDefinition($this->routesByName[$name]); }
// NewRegexpWithLimit creates a new Regular Expression automaton with // the specified expression. The size of the compiled finite state // automaton exceeds the user specified size, ErrCompiledTooBig will be // returned.
func NewWithLimit(expr string, size uint) (*Regexp, error) { parsed, err := syntax.Parse(expr, syntax.Perl) if err != nil { return nil, err } return NewParsedWithLimit(expr, parsed, size) }
Returns the GA4GH protocol representation of this read group's ReadStats.
def getStats(self): stats = protocol.ReadStats() stats.aligned_read_count = self.getNumAlignedReads() stats.unaligned_read_count = self.getNumUnalignedReads() # TODO base_count requires iterating through all reads return stats
// PubSubHandler is a webhook that stores the builds coming in from pubsub.
func PubSubHandler(ctx *router.Context) { statusCode := pubSubHandlerImpl(ctx.Context, ctx.Request) ctx.Writer.WriteHeader(statusCode) }
Returns the WKB representation of this geometry. @noproxy @return string
public function asBinary() : string { static $wkbWriter; if ($wkbWriter === null) { $wkbWriter = new WKBWriter(); } return $wkbWriter->write($this); }
Returns all the values joined together. :return <int>
def all(self): out = 0 for key, value in self.items(): out |= value return out
// ReadLine awaits a single line from the client.
func (c *Conn) ReadLine() (text string, ok bool) { ok = c.RwcScanner.Scan() return c.RwcScanner.Text(), ok }
Given a value of type <code>A</code>, produced an instance of this tuple with each slot set to that value. @param a the value to fill the tuple with @param <A> the value type @return the filled tuple @see Tuple2#fill
public static <A> Tuple7<A, A, A, A, A, A, A> fill(A a) { return tuple(a, a, a, a, a, a, a); }
@param string $id @param array $data @param array $headers @throws Exception @return array|string
public function reactivate(string $id, array $data, array $headers = []) { $url = $this->url('subscriptions/%s/reactivate', $id); return $this->post($url, $data, $headers); }
Link given $zone with the zone given in $zoneData.
private function linkZone(Zone $zone, array $zoneData): void { $linkedZoneLayout = $this->layoutService->loadLayout($zoneData['layout_id']); $linkedZone = $linkedZoneLayout->getZone($zoneData['identifier']); $this->layoutService->linkZone($zone, $linkedZone); }
Creates a Diffie-Hellman key pair. @return dh keypair
protected KeyPair generateKeyPair() { KeyPair keyPair = null; DHParameterSpec keySpec = new DHParameterSpec(DH_MODULUS, DH_BASE); try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH"); keyGen.initialize(keySpec); keyPair = keyGen.generateKeyPair(); keyAgreement = KeyAgreement.getInstance("DH"); // key agreement is initialized with "this" ends private key keyAgreement.init(keyPair.getPrivate()); } catch (Exception e) { log.error("Error generating keypair", e); } return keyPair; }
Create a package finder appropriate to this install command. This method is meant to be overridden by subclasses, not called directly.
def _build_package_finder(self, options, index_urls): return PackageFinder(find_links=options.find_links, index_urls=index_urls, use_mirrors=options.use_mirrors, mirrors=options.mirrors)
Generates the data that powers the index page
protected function generateIndex() { /** * Handle missing index.html. Solves https://github.com/drupal-pattern-lab/patternlab-php-core/issues/14 * Could also be used to re-add missing styleguidekit assets with a few edits? * * 1. @TODO: Figure out a better way to future-proof path resolution for styleguidekit `dist` folder * 2. Recusirively copy files from styleguidekit to publicDir via https://stackoverflow.com/a/7775949 * 3. Make sure we only try to create new directories if they don't already exist * 4. Only copy files if they are missing (vs changed, etc) */ if (!file_exists(Config::getOption("publicDir")."/index.html")) { $index = Console::getHumanReadablePath(Config::getOption("publicDir")).DIRECTORY_SEPARATOR."index.html"; Console::writeWarning($index . " is missing. No biggie. Grabbing a fresh copy from your StyleguideKit..."); $baseDir = Config::getOption("baseDir") . '/vendor'; $finder = new Finder(); // Locate the current theme's styleguidekit assets via the patternlab-styleguidekit `type` in composer.json $finder->files()->name("composer.json")->in($baseDir)->contains('patternlab-styleguidekit')->sortByName(); foreach ($finder as $file) { $src = dirname($file->getRealPath()) . DIRECTORY_SEPARATOR . 'dist'; /* [1] */ $dest= Config::getOption("publicDir"); if (is_dir($src)){ if(!is_dir($dest)) { mkdir($dest, 0755); } foreach ( /* [2] */ $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item ) { if ($item->isDir()) { if(!is_dir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) { /* [3] */ mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName()); } } else { if(!file_exists($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) { /* [4] */ copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName()); } } } } } } // set-up the dispatcher $dispatcherInstance = Dispatcher::getInstance(); // note the start of the operation $dispatcherInstance->dispatch("builder.generateIndexStart"); // default var $dataDir = Config::getOption("publicDir")."/styleguide/data"; // double-check that the data directory exists if (!is_dir($dataDir)) { FileUtil::makeDir($dataDir); } $output = ""; // load and write out the config options $config = array(); $exposedOptions = Config::getOption("exposedOptions"); foreach ($exposedOptions as $exposedOption) { $config[$exposedOption] = Config::getOption($exposedOption); } $output .= "var config = ".json_encode($config).";\n"; // load the ish Controls $ishControls = array(); $controlsToHide = array(); $ishControlsHide = Config::getOption("ishControlsHide"); if ($ishControlsHide) { foreach ($ishControlsHide as $controlToHide) { $controlsToHide[$controlToHide] = "true"; } } $ishControls["ishControlsHide"] = $controlsToHide; $output .= "var ishControls = ".json_encode($ishControls).";\n"; // load and write out the items for the navigation $niExporter = new NavItemsExporter(); $navItems = $niExporter->run(); $output .= "var navItems = ".json_encode($navItems).";\n"; // load and write out the items for the pattern paths $patternPaths = array(); $ppdExporter = new PatternPathDestsExporter(); $patternPaths = $ppdExporter->run(); $output .= "var patternPaths = ".json_encode($patternPaths).";\n"; // load and write out the items for the view all paths $viewAllPaths = array(); $vapExporter = new ViewAllPathsExporter(); $viewAllPaths = $vapExporter->run($navItems); $output .= "var viewAllPaths = ".json_encode($viewAllPaths).";\n"; // gather plugin package information $packagesInfo = array(); $componentDir = Config::getOption("componentDir"); if (!is_dir($componentDir)) { mkdir($componentDir); } $componentPackagesDir = $componentDir."/packages"; if (!is_dir($componentDir."/packages")) { mkdir($componentDir."/packages"); } $finder = new Finder(); $finder->files()->name("*.json")->in($componentPackagesDir); $finder->sortByName(); foreach ($finder as $file) { $filename = $file->getFilename(); if ($filename[0] != "_") { $javascriptPaths = array(); $packageInfo = json_decode(file_get_contents($file->getPathname()),true); foreach ($packageInfo["templates"] as $templateKey => $templatePath) { $templatePathFull = $componentDir."/".$packageInfo["name"]."/".$templatePath; $packageInfo["templates"][$templateKey] = (file_exists($templatePathFull)) ? file_get_contents($templatePathFull) : ""; } foreach ($packageInfo["javascripts"] as $key => $javascriptPath) { $javascriptPaths[] = "patternlab-components/".$packageInfo["name"]."/".$javascriptPath; } $packageInfo["javascripts"] = $javascriptPaths; $packagesInfo[] = $packageInfo; } } $output .= "var plugins = ".json_encode($packagesInfo).";"; // write out the data file_put_contents($dataDir."/patternlab-data.js",$output); // Structuring all the same data that went into `patternlab-data.js` and putting it into `patternlab-data.json` too $allPlData = array( 'config' => $config, 'ishControls' => $ishControls, 'navItems' => $navItems, 'patternPaths' => $patternPaths, 'viewAllPaths' => $viewAllPaths, 'plugins' => $packagesInfo, ); file_put_contents($dataDir."/patternlab-data.json", json_encode($allPlData)); // note the end of the operation $dispatcherInstance->dispatch("builder.generateIndexEnd"); }
Parses a complex fault geometry node returning both the attributes and parameters in a dictionary
def parse_complex_fault_geometry(node): assert "complexFaultGeometry" in node.tag # Get general attributes geometry = {"intermediateEdges": []} for subnode in node: crds = subnode.nodes[0].nodes[0].text if "faultTopEdge" in subnode.tag: geometry["faultTopEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["upperSeismoDepth"] = numpy.min( geometry["faultTopEdge"][:, 2]) elif "faultBottomEdge" in subnode.tag: geometry["faultBottomEdge"] = numpy.array( [[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)]) geometry["lowerSeismoDepth"] = numpy.max( geometry["faultBottomEdge"][:, 2]) elif "intermediateEdge" in subnode.tag: geometry["intermediateEdges"].append( numpy.array([[crds[i], crds[i + 1], crds[i + 2]] for i in range(0, len(crds), 3)])) else: pass geometry["dip"] = None return geometry
Compute distance matrix from contact data by applying a negative power law (alpha) to its nonzero pixels, then interpolating on the zeroes using a shortest-path algorithm.
def to_distance(matrix, alpha=1): matrix = np.array(matrix) try: import scipy.sparse except ImportError as e: print("Scipy not found.") print(str(e)) raise if callable(alpha): distance_function = alpha else: try: a = np.float64(alpha) def distance_function(x): return 1 / (x ** (1 / a)) except TypeError: print("Alpha parameter must be callable or an array-like") raise if hasattr(matrix, 'getformat'): distances = scipy.sparse.coo_matrix(matrix) distances.data = distance_function(distances.data) else: distances = np.zeros(matrix.shape) distances[matrix != 0] = distance_function(1 / matrix[matrix != 0]) return scipy.sparse.csgraph.floyd_warshall(distances, directed=False)
The wrapper for creating shell instances. @param string $className Shell class name. @param \Cake\Console\ConsoleIo $io The IO wrapper for the created shell class. @return \Cake\Console\Shell|\Cake\Console\Command
protected function createShell($className, ConsoleIo $io) { $shell = $this->factory->create($className); if ($shell instanceof Shell) { $shell->setIo($io); } return $shell; }
count ``` $db->count(); ``` @param string $table @param array|string $wheres @return int @throws \RuntimeException
public function count(string $table, $wheres) { list($where, $bindings) = $this->handleWheres($wheres); $sql = "SELECT COUNT(*) AS total FROM {$table} WHERE {$where}"; $result = $this->fetchObject($sql, $bindings); return $result ? (int)$result->total : 0; }
Return the extra classes as concatenated strings @return String $classes
protected function getTableExtraClassesString() { $classes_html = ''; if( ! empty($this->table_extra_classes) ) { foreach($this->table_extra_classes as $class) { $classes_html.= "{$class} "; } } return $classes_html; }
// ContentTypeHandler wraps and returns a http.Handler, validating the request // content type is compatible with the contentTypes list. It writes a HTTP 415 // error if that fails. // // Only PUT, POST, and PATCH requests are considered.
func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") { h.ServeHTTP(w, r) return } for _, ct := range contentTypes { if isContentType(r.Header, ct) { h.ServeHTTP(w, r) return } } http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType) }) }
Notify all listeners that a property has changed. @param property the property whose value has changed
private void firePropertyChanged(T property) { PropertyEvent<T> event = null; for (PropertyListener<T> l : listeners) { if (event == null) { event = new PropertyEvent<T>(this, property); } l.changed(event); } }
/ perform extra validation before submission
function validation($data, $files) { global $COURSE; $errors = parent::validation($data, $files); if (array_key_exists('idnumber', $data)) { if ($data['id']) { $grade_item = new grade_item(array('id'=>$data['id'], 'courseid'=>$data['courseid'])); } else { $grade_item = null; } if (!grade_verify_idnumber($data['idnumber'], $COURSE->id, $grade_item, null)) { $errors['idnumber'] = get_string('idnumbertaken'); } } return $errors; }
Additionally encodes headers. :return:
def as_dict(self): data = super(BaseEmail, self).as_dict() data["Headers"] = [{"Name": name, "Value": value} for name, value in data["Headers"].items()] for field in ("To", "Cc", "Bcc"): if field in data: data[field] = list_to_csv(data[field]) data["Attachments"] = [prepare_attachments(attachment) for attachment in data["Attachments"]] return data
Splits a line at the first occurrence of : @param {string} line @return {Array.<string>} @private
function splitLine(line) { var idx = String(line).indexOf(':'); if (!line || idx < 0) { return null; } return [line.slice(0, idx), line.slice(idx + 1)]; }
Helper to cast string to datetime using :member:`parse_format`. :param value: String representing a datetime :type value: str :return: datetime
def get_parsed_value(self, value): def get_parser(parser_desc): try: return parser_desc['parser'] except TypeError: try: return get_parser(self.date_parsers[parser_desc]) except KeyError: return parser_desc except KeyError: pass parser = get_parser(self.parse_format) if parser is None: try: return dateutil_parse(value) except ValueError: return None if callable(parser): return parser(value) return datetime.strptime(value, parser)
<code>.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig crypto_replace_ffx_fpe_config = 4; </code>
public com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfigOrBuilder getCryptoReplaceFfxFpeConfigOrBuilder() { if (transformationCase_ == 4) { return (com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig) transformation_; } return com.google.privacy.dlp.v2.CryptoReplaceFfxFpeConfig.getDefaultInstance(); }
List all file `filename` breakpoints
def get_file_breaks(self, filename): """""" return [ breakpoint for breakpoint in self.breakpoints if breakpoint.on_file(filename) ]
Add an edge for every attribute the given artifact provides. This method adds a directed edge from the artifact node to every attribute this artifact provides. Args: rdf_artifact: The artifact object.
def _AddProvidesEdges(self, rdf_artifact): for attribute in rdf_artifact.provides: self._AddEdge(rdf_artifact.name, attribute)
// AllCols indicates that all columns should be use
func (engine *Engine) AllCols() *Session { session := engine.NewSession() session.isAutoClose = true return session.AllCols() }
Converts the given Metric into datapoints that can be sent to SignalFx. @param metric The {@link Metric} containing the timeseries of each combination of label values. @return A list of datapoints for the corresponding metric timeseries of this metric.
static List<DataPoint> adapt(Metric metric) { MetricDescriptor metricDescriptor = metric.getMetricDescriptor(); MetricType metricType = getType(metricDescriptor.getType()); if (metricType == null) { return Collections.emptyList(); } DataPoint.Builder shared = DataPoint.newBuilder(); shared.setMetric(metricDescriptor.getName()); shared.setMetricType(metricType); ArrayList<DataPoint> datapoints = Lists.newArrayList(); for (TimeSeries timeSeries : metric.getTimeSeriesList()) { DataPoint.Builder builder = shared.clone(); builder.addAllDimensions( createDimensions(metricDescriptor.getLabelKeys(), timeSeries.getLabelValues())); List<Point> points = timeSeries.getPoints(); datapoints.ensureCapacity(datapoints.size() + points.size()); for (Point point : points) { datapoints.add(builder.setValue(createDatum(point.getValue())).build()); } } return datapoints; }
Returns a contentset options according to the layout zone. @param \StdClass $zone @return array
private function getZoneOptions(\stdClass $zone) { $options = array( 'parameters' => array( 'class' => array( 'type' => 'scalar', 'options' => array('default' => 'row'), ), ), ); if (true === property_exists($zone, 'accept') && true === is_array($zone->accept) && 0 < count($zone->accept) && $zone->accept[0] != '') { $options['accept'] = $zone->accept; $func = function (&$item, $key) { $item = ('' == $item) ? null : 'BackBee\ClassContent\\'.$item; }; array_walk($options['accept'], $func); } if (true === property_exists($zone, 'maxentry') && 0 < $zone->maxentry) { $options['maxentry'] = $zone->maxentry; } return $options; }
Returns a list of pairs (leaf_name, distance)
def _parse_leaves(self, leaves) -> List[Tuple[str, int]]: """""" return [(self._leaf_name(leaf), 0) for leaf in leaves]
------------------------------------------------------------------------------
function onRequestGetAgents(session, channel, message) { var agents = session.getAgents() var infos = agents.map(function(agent){ return agent.info }) channel.sendMessage({ type: "response", name: message.name, from: message.to, id: message.id, body: infos }) }
Does our comparison need a container? EG: "[* TO *]"? If so, return the opening container brace. @param string $comparison @return string @throws InvalidArgumentException
protected function getOpenComparisonContainer($comparison) { switch ($comparison) { case SearchCriterion::GREATER_EQUAL: case SearchCriterion::LESS_EQUAL: case SearchCriterion::ISNULL: case SearchCriterion::ISNOTNULL: return '['; case SearchCriterion::GREATER_THAN: case SearchCriterion::LESS_THAN: return '{'; default: throw new InvalidArgumentException('Invalid comparison for RangeCriterion'); } }
Generates an unique auth code. Implementing classes may want to override this function to implement other auth code generation schemes. @return An unique auth code. @ingroup oauth2_section_4
protected function generateAuthorizationCode() { $tokenLen = 40; if (function_exists('random_bytes')) { $randomData = random_bytes(100); } elseif (function_exists('openssl_random_pseudo_bytes')) { $randomData = openssl_random_pseudo_bytes(100); } elseif (function_exists('mcrypt_create_iv')) { $randomData = mcrypt_create_iv(100, MCRYPT_DEV_URANDOM); } elseif (@file_exists('/dev/urandom')) { // Get 100 bytes of random data $randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true); } else { $randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true); } return substr(hash('sha512', $randomData), 0, $tokenLen); }
Recovers a RingSet corresponding to a AtomContainer that has been stored by storeRingSystem(). @param mol The IAtomContainer for which to recover the IRingSet.
private IRingSet recoverRingSystem(IAtomContainer mol) { IRingSet ringSet = mol.getBuilder().newInstance(IRingSet.class); for (Integer[] bondNumbers : listOfRings) { IRing ring = mol.getBuilder().newInstance(IRing.class, bondNumbers.length); for (int bondNumber : bondNumbers) { IBond bond = mol.getBond(bondNumber); ring.addBond(bond); if (!ring.contains(bond.getBegin())) ring.addAtom(bond.getBegin()); if (!ring.contains(bond.getEnd())) ring.addAtom(bond.getEnd()); } ringSet.addAtomContainer(ring); } return ringSet; }