comment
stringlengths
16
255
code
stringlengths
52
3.87M
// Validate inspects the fields of the type to determine if they are valid.
func (s *DvbTdtSettings) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DvbTdtSettings"} if s.RepInterval != nil && *s.RepInterval < 1000 { invalidParams.Add(request.NewErrParamMinValue("RepInterval", 1000)) } if invalidParams.Len() > 0 { return invalidParams } return nil }
// Add adds a new child provider for a specific digest
func (mp *MultiProvider) Add(dgst digest.Digest, p content.Provider) { mp.mu.Lock() defer mp.mu.Unlock() mp.sub[dgst] = p }
// AddPrefix adds a prefix-based tombstone key.
func (t *Tombstoner) AddPrefix(key []byte) error { return t.AddPrefixRange(key, math.MinInt64, math.MaxInt64) }
désactive la présentation d'une icône pour délencher la suppression du fichier des fichiers téléchargés @return ODDragNDrop
public function disThumbRmove() { $properties = $this->getProperties(); $properties['thumbRmove'] = self::BOOLEAN_FALSE; $this->setProperties($properties); return $this; }
Sets an image with a given image mode to the drawer item @param image Image to set @param imageMode Image mode to set
public DrawerItem setImage(Drawable image, int imageMode) { mImage = image; setImageMode(imageMode); notifyDataChanged(); return this; }
Retrieve the tag string for an element node.
function getElementTag(node) { if (node.openingElement && t.isJSXIdentifier(node.openingElement.name)) { return node.openingElement.name.name; } else { error(node.openingElement, "Unable to parse opening tag."); } }
Returns an array of users in the given conversation. @return moodle_recordset A moodle_recordset instance.
private function get_unique_users() : moodle_recordset { global $DB; $subsql = 'SELECT DISTINCT(useridto) as id FROM {message_email_messages} WHERE id <= ?'; $sql = "SELECT * FROM {user} u WHERE id IN ($subsql)"; return $DB->get_recordset_sql($sql, [$this->maxid]); }
// SetOverrideDynamicGroups sets the OverrideDynamicGroups field's value.
func (s *AddThingToThingGroupInput) SetOverrideDynamicGroups(v bool) *AddThingToThingGroupInput { s.OverrideDynamicGroups = &v return s }
Render basics of textarea
public function renderBasic() { $html = "<textarea rows='$this->rows'"; $html .= " " . $this->getCompiledAttributes("form-control"); $html .= ">"; $html .= $this->value; $html .= "</textarea>"; return $html; }
Registers a bundle as the main bundle for a model. Used when we need to lookup urls by a model.
def register_model(self, model, bundle): if model in self._model_registry: raise AlreadyRegistered('The model %s is already registered' \ % model) if bundle.url_params: raise Exception("A primary model bundle cannot have dynamic \ url_parameters") self._model_registry[model] = bundle
Default material deep orange transparent style for SuperToasts. @return A new Style
public static Style deepOrange() { final Style style = new Style(); style.color = PaletteUtils.getSolidColor(PaletteUtils.MATERIAL_DEEP_ORANGE); return style; }
Create a rest session based on request credentials @param \common_http_Request $request @return \common_session_RestSession|\common_session_Session @throws LoginFailedException
public function getSession(\common_http_Request $request) { $authAdapter = new \tao_models_classes_HttpBasicAuthAdapter($request); $user = $authAdapter->authenticate(); return new \common_session_RestSession($user); }
rm -rf commande like. @param type $path @return boolean
public static function delete($path) { $files = self::getContent($path); foreach ($files as $file) { if (is_dir($path.DIRECTORY_SEPARATOR.$file)) { self::delete($path.DIRECTORY_SEPARATOR.$file); } else { @unlink($path.DIRECTORY_SEPARATOR.$file); } } return @rmdir($path); }
Method called to reuse a pooled instance. @returns Chained pooled instance that should now be head of the reuse chain
private void relink(SimpleOutputElement parent, String prefix, String localName, String uri) { super.relink(parent); mParent = parent; mPrefix = prefix; mLocalName = localName; mURI = uri; mNsMapping = parent.mNsMapping; mNsMapShared = (mNsMapping != null); mDefaultNsURI = parent.mDefaultNsURI; mRootNsContext = parent.mRootNsContext; }
Create an handler for at specific level.
def _create_handler(self, handler_class, level): """""" if handler_class == logging.StreamHandler: handler = handler_class() handler.setLevel(level) elif handler_class == logging.handlers.SysLogHandler: handler = handler_class(address='/dev/log') handler.setLevel(level) elif handler_class == logging.handlers.TimedRotatingFileHandler: handler = handler_class(self.filename, when='midnight') handler.setLevel(level) elif handler_class == AlkiviEmailHandler: handler = handler_class(mailhost='127.0.0.1', fromaddr="%s@%s" % (USER, HOST), toaddrs=self.emails, level=self.min_log_level_to_mail) # Needed, we want all logs to go there handler.setLevel(0) formatter = self.get_formatter(handler) handler.setFormatter(formatter) self.handlers.append(handler) self.logger.addHandler(handler)
Hang up a phone call. @throws IOException unexpected error.
public void hangUp() throws Exception { final Map<String, Object> params = new HashMap<String, Object>(); params.put("state", "completed"); final String uri = getUri(); client.post(uri, params); final JSONObject jsonObject = toJSONObject(client.get(uri, null)); updateProperties(jsonObject); }
Returns the mean pixel intensity value. @param img Input image. Not modified. @return Mean pixel intensity value
public static float mean( InterleavedF32 img ) { return sum(img)/(float)(img.width*img.height*img.numBands); }
close socket, immediately.
def shutdown(self): """""" if self.sock: self.sock.close() self.sock = None self.connected = False
Create/cache thumbnail. @Route("/{id}/thumbnail/{x}/{y}", name="file_thumbnail", methods={"GET"})
public function thumbnailAction(Request $request, $access, $id, $x, $y) { $sf = $this->container->get('sakonnin.files'); if (is_numeric($id)) { $repo = $em->getRepository('BisonLabSakonninBundle:SakonninFile'); $file->find($id); } else { $sfile = $sf->getFiles(['fileid' => $id]); } if (!$sfile->getThumbnailable()) $this->returnError($request, 'Not an image'); // TODO: Add access control. // Gotta get the thumbnail then. $thumbfile = $sf->getThumbnailFilename($sfile, $x, $y); $response = new BinaryFileResponse($thumbfile); return $response; }
Creates an array of cacheable and normalized message headers. @param MessageInterface $message @return array
private function persistHeaders(MessageInterface $message) { // Clone the response to not destroy any necessary headers when caching $headers = array_diff_key($message->getHeaders(), self::$noCache); // Cast the headers to a string foreach ($headers as &$value) { $value = implode(', ', $value); } return $headers; }
Dump profile content to disk
def on_app_shutdown(self, app): '''''' if self.filewatcher: self.filewatcher.stop() if self.profile: self.upload_page.on_destroy() self.download_page.on_destroy()
Cancel notifications by its tag. @param tag
public void cancel(String tag) { List<NotificationEntry> entries = mCenter.getEntries(ID, tag); if (entries != null && !entries.isEmpty()) { for (NotificationEntry entry : entries) { cancel(entry); } } }
For authenticated users, add the start-menu style navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.startMenu}
def render_startmenu(self, ctx, data): if self.username is None: return '' translator = self._getViewerPrivateApplication() pageComponents = translator.getPageComponents() return startMenu(translator, pageComponents.navigation, ctx.tag)
Aggregate object/objects in database an execute callback. @param {Object} req Request @param {Object} res Response @param {Object} options {model, group, callback}
function (req, res, options) { if (!options) { options = {}; } options.operation = 'AGGREGATE'; options.res = res; exports.aggregate.before(req, res, options); vulpejs.models.aggregate({ model: req.params.model, aggregate: req.params.aggregate, callback: { success: function (results) { if (options && options.callback) { vulpejs.utils.execute(options.callback, results); } else { exports.aggregate.after(req, res, results); res.json({ items: results, }); } }, error: function (error) { vulpejs.log.error('AGGREGATE', error); res.status(500).end(); }, }, }); }
// Reset restores all point properties to defaults and removes all Pushed points. // // This does not affect matrix and color mask set by SetMatrix and SetColorMask.
func (imd *IMDraw) Reset() { imd.points = imd.points[:0] imd.Color = pixel.Alpha(1) imd.Picture = pixel.ZV imd.Intensity = 0 imd.Precision = 64 imd.EndShape = NoEndShape }
Returns an array representation of this request. @return array Array representation of this request.
public function toArray() { return array_filter( array( 'method' => $this->getMethod(), 'url' => $this->getUrl(), 'headers' => $this->getHeaders(), 'body' => $this->getBody(), 'post_files' => $this->getPostFiles(), 'post_fields' => $this->getPostFields(), ) ); }
Given an error bundle, a list of overlays that are present in the current package or subpackage are returned.
def get_applicable_overlays(self, error_bundle): content_paths = self.get_triples(subject='content') if not content_paths: return set() # Create some variables that will store where the applicable content # instruction path references and where it links to. chrome_path = '' content_root_path = '/' # Look through each of the listed packages and paths. for path in content_paths: chrome_name = path['predicate'] if not path['object']: continue path_location = path['object'].strip().split()[0] # Handle jarred paths differently. if path_location.startswith('jar:'): if not error_bundle.is_nested_package: continue # Parse out the JAR and it's location within the chrome. split_jar_url = path_location[4:].split('!', 2) # Ignore invalid/unsupported JAR URLs. if len(split_jar_url) != 2: continue # Unpack the JAR URL. jar_path, package_path = split_jar_url # Ignore the instruction if the JAR it points to doesn't match # up with the current subpackage tree. if jar_path != error_bundle.package_stack[0]: continue chrome_path = self._url_chunk_join(chrome_name, package_path) # content_root_path stays at the default: / break else: # If we're in a subpackage, a content instruction referring to # the root of the package obviously doesn't apply. if error_bundle.is_nested_package: continue chrome_path = self._url_chunk_join(chrome_name, 'content') content_root_path = '/%s/' % path_location.strip('/') break if not chrome_path: return set() applicable_overlays = set() chrome_path = 'chrome://%s' % self._url_chunk_join(chrome_path + '/') for overlay in self.get_triples(subject='overlay'): if not overlay['object']: error_bundle.error( err_id=('chromemanifest', 'get_applicable_overalys', 'object'), error='Overlay instruction missing a property.', description='When overlays are registered in a chrome ' 'manifest file, they require a namespace and ' 'a chrome URL at minimum.', filename=overlay['filename'], line=overlay['line'], context=self.context) #TODO(basta): Update this! continue overlay_url = overlay['object'].split()[0] if overlay_url.startswith(chrome_path): overlay_relative_path = overlay_url[len(chrome_path):] applicable_overlays.add('/%s' % self._url_chunk_join(content_root_path, overlay_relative_path)) return applicable_overlays
This method checks if the domain exists for the user. If the domain was not found, it will be created using the domainId. @param domainId The domainId which will be used for finding o creating the domain the user. @return a the found or created domain.
private IDomain createDomainIfNotExist(String domainId){ IDomain foundDomain=findDomainByID(domainId); if(foundDomain==null){ foundDomain=user.createDomain(domainName); } return foundDomain; }
Assumes that a specific OS is used. @param string $pattern @param string $message @return void @throws AssumptionViolatedException
public static function assumeOperatingSystem($pattern, $message = ''): void { $regEx = sprintf('/%s/i', addcslashes($pattern, '/')); assumeThat(PHP_OS, matchesPattern($regEx), $message); }
Resolve the current request. @return \Bugsnag\Request\RequestInterface
public function resolve() { if (isset($_SERVER['REQUEST_METHOD'])) { if (strtoupper($_SERVER['REQUEST_METHOD']) === 'GET') { $params = static::getInputParams($_SERVER, $_GET, false); } else { $params = static::getInputParams($_SERVER, $_POST, true); } return new PhpRequest($_SERVER, empty($_SESSION) ? [] : $_SESSION, empty($_COOKIE) ? [] : $_COOKIE, static::getRequestHeaders($_SERVER), $params); } if (PHP_SAPI === 'cli' && isset($_SERVER['argv'])) { return new ConsoleRequest($_SERVER['argv']); } return new NullRequest(); }
Convert placeholders used in the template string back to the AST nodes they reference.
function convertPlaceholders (value) { // Probably AST nodes. if (typeof value !== 'string') { return [value] } const items = value.split(placeholderRe) let placeholder = true return items.map((item) => { placeholder = !placeholder return placeholder ? expressions[item] : t.stringLiteral(item) }) }
Return the primary value for the given header, if any. <p> Will return the first value in case of multiple values. @param sName the name of the header @return the associated header value, or <code>null</code> if none
@Nullable public String getHeader (@Nullable final String sName) { final ICommonsOrderedSet <String> aSet = m_aHeaders.get (_unifyHeaderName (sName)); return aSet == null ? null : aSet.getFirst (); }
// SetAgentPresence signals that the agent for unit u is alive. // It returns the started pinger.
func (u *Unit) SetAgentPresence() (*presence.Pinger, error) { presenceCollection := u.st.getPresenceCollection() recorder := u.st.getPingBatcher() m, err := u.st.Model() if err != nil { return nil, errors.Trace(err) } p := presence.NewPinger(presenceCollection, m.ModelTag(), u.globalAgentKey(), func() presence.PingRecorder { return u.st.getPingBatcher() }) err = p.Start() if err != nil { return nil, err } // Make sure this Agent status is written to the database before returning. recorder.Sync() return p, nil }
Gets an ElementRef for this element. Must have a page set. If id has not yet been set, one will be generated. @throws IllegalStateException if page not set
public ElementRef getElementRef() throws IllegalStateException { Page p = page; if(p == null) throw new IllegalStateException("page not set"); PageRef pageRef = p.getPageRef(); String i = getId(); if(i == null) throw new IllegalStateException("page not set so no id generated"); ElementRef er = elementRef; if( er == null // Make sure object still valid || !er.getPageRef().equals(pageRef) || !er.getId().equals(i) ) { er = new ElementRef(pageRef, i); elementRef = er; } return er; }
// PrintStyles prints all style combinations to the terminal.
func PrintStyles() { // for compatibility with Windows, not needed for *nix stdout := colorable.NewColorableStdout() bgColors := []string{ "", ":black", ":red", ":green", ":yellow", ":blue", ":magenta", ":cyan", ":white", } keys := make([]string, 0, len(Colors)) for k := range Colors { keys = append(keys, k) } sort.Sort(sort.StringSlice(keys)) for _, fg := range keys { for _, bg := range bgColors { fmt.Fprintln(stdout, padColor(fg, []string{"" + bg, "+b" + bg, "+bh" + bg, "+u" + bg})) fmt.Fprintln(stdout, padColor(fg, []string{"+s" + bg, "+i" + bg})) fmt.Fprintln(stdout, padColor(fg, []string{"+uh" + bg, "+B" + bg, "+Bb" + bg /* backgrounds */, "" + bg + "+h"})) fmt.Fprintln(stdout, padColor(fg, []string{"+b" + bg + "+h", "+bh" + bg + "+h", "+u" + bg + "+h", "+uh" + bg + "+h"})) } } }
Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular
def norm(x, encoding="latin1"): "" if not isinstance(x, basestring): x = unicode(x) elif isinstance(x, str): x = x.decode(encoding, 'ignore') return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore')
An LDA object. @constructor @param {...number[][]} classes - Each parameter is a 2d class array. In each class array, rows are samples, columns are variables. @example let classifier = new LDA(class1, class2, class3);
function LDA(...classes) { // Compute pairwise LDA classes (needed for multiclass LDA) if(classes.length < 2) { throw new Error('Please pass at least 2 classes'); } let numberOfPairs = classes.length * (classes.length - 1) / 2; let pair1 = 0; let pair2 = 1; let pairs = new Array(numberOfPairs); for(let i = 0; i < numberOfPairs; i++){ pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2); pair2++; if(pair2 == classes.length) { pair1++; pair2 = pair1 + 1; } } this.pairs = pairs; this.numberOfClasses = classes.length; }
// Stops a virtual machine.
func (s *VirtualMachineService) StopVirtualMachine(p *StopVirtualMachineParams) (*StopVirtualMachineResponse, error) { resp, err := s.cs.newRequest("stopVirtualMachine", p.toURLValues()) if err != nil { return nil, err } var r StopVirtualMachineResponse if err := json.Unmarshal(resp, &r); err != nil { return nil, err } // If we have a async client, we need to wait for the async result if s.cs.async { b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout) if err != nil { if err == AsyncTimeoutErr { return &r, err } return nil, err } b, err = getRawValue(b) if err != nil { return nil, err } if err := json.Unmarshal(b, &r); err != nil { return nil, err } } return &r, nil }
Returns the id of a metadata
def getMetadataId(self, metadata): return str(datamodel.VariantSetMetadataCompoundId( self.getCompoundId(), 'metadata:' + metadata.key))
Set the window length from the training parameters file. @param params the properties file
public static void setWindow(final TrainingParameters params) { if (leftWindow == -1 || rightWindow == -1) { leftWindow = getWindowRange(params).get(0); rightWindow = getWindowRange(params).get(1); } }
Callback for "country-get" command
public function cmdGetCountry() { $result = $this->getListCountry(); $this->outputFormat($result); $this->outputFormatTableCountry($result); $this->output(); }
@param Stream $stream @return string
private function parseTypeIdentifier(Stream $stream) { $identifier = $this->parseIdentifier($stream); if ($stream->current()->equals(Token::TYPE_SYMBOL, '.')) { $stream->expects(Token::TYPE_SYMBOL, '.'); $identifier = sprintf('%s.%s', $identifier, $this->parseIdentifier($stream)); } return $identifier; }
Removes all punctuation characters from a string.
def _strip_punctuation(s): if type(s) is str and not PYTHON_3: # Bytestring (default in Python 2.x). return s.translate(string.maketrans("",""), string.punctuation) else: # Unicode string (default in Python 3.x). translate_table = dict((ord(char), u'') for char in u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~') return s.translate(translate_table)
@param string $symbol @throws Exception\UnknownSymbolException
private function checkSymbol($symbol) { if (!in_array($symbol, [self::NONE, self::X, self::O])) { throw new Exception\UnknownSymbolException($symbol); } }
Builds a schema object
public function build($class) { if(!isset($this->_properties)) throw new Exception("A schema must have properties"); return new Schema($class, array( 'properties' => $this->_properties, 'relationships' => $this->_relationships, 'getters' => $this->_getters, 'setters' => $this->_setters, 'events' => $this->_events )); }
Converts the collimator attribute to proper DICOM format. @param [Symbol] axis a representation for the axis of interest (x or y) @return [Float] the DICOM-formatted collimator attribute
def dcm_collimator1(axis) value = self.send("collimator_#{axis}1").to_f * 10 mode = self.send("field_#{axis}_mode") if mode && mode.upcase == 'SYM' && value > 0 -value else value end end
// Error can be either of the following types: // // - InvalidObjectFault // - RuntimeFault
func (service *VboxPortType) IPerformanceCollectordisableMetrics(request *IPerformanceCollectordisableMetrics) (*IPerformanceCollectordisableMetricsResponse, error) { response := new(IPerformanceCollectordisableMetricsResponse) err := service.client.Call("", request, response) if err != nil { return nil, err } return response, nil }
Run the migrations.
public function up() { Schema::create(config('cortex.foundation.tables.activity_log'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('log_name'); $table->string('description'); $table->integer('subject_id')->nullable(); $table->string('subject_type')->nullable(); $table->integer('causer_id')->nullable(); $table->string('causer_type')->nullable(); $table->{$this->jsonable()}('properties')->nullable(); $table->timestamps(); // Indexes $table->index('log_name'); }); }
The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.
def _get_metadata_for_region(region_code): """""" country_calling_code = country_code_for_region(region_code) main_country = region_code_for_country_code(country_calling_code) # Set to a default instance of the metadata. This allows us to # function with an incorrect region code, even if formatting only # works for numbers specified with "+". return PhoneMetadata.metadata_for_region(main_country, _EMPTY_METADATA)
Opens a socket suitable for sending/receiving ICMP echo requests/responses.
def _open_icmp_socket(self, family): try: proto = socket.IPPROTO_ICMP if family == socket.AF_INET \ else _IPPROTO_ICMPV6 return socket.socket(family, socket.SOCK_RAW, proto) except socket.error as e: if e.errno == 1: raise MultiPingError("Root privileges required for sending " "ICMP") # Re-raise any other error raise
Init websocket server and push server if enabled.
private function initWebsocketServer() { $websocketBind = $this->sandstoneApplication['sandstone.websocket.server']['bind']; $websocketPort = $this->sandstoneApplication['sandstone.websocket.server']['port']; $socket = new ReactSocketServer("$websocketBind:$websocketPort", $this->loop); new IoServer( new HttpServer( new WsServer( new ServerProtocol( new WebsocketApplication( $this->sandstoneApplication ) ) ) ), $socket ); }
Добавляет компонент к списку дочерних Иерархия компонентов должна строго соответствовать иерархии вложеных тэгов (с аттрибутами zippy) в HTML шаблоне
public function add(HtmlComponent $component) { if (isset($this->components[$component->id])) { throw new ZE(sprintf(ERROR_COMPONENT_ALREADY_EXISTS, $component->id, $this->id)); } if (property_exists($this, $component->id)) { $id = strlen($this->id) > 0 ? $this->id : get_class($this); throw new ZE(sprintf(ERROR_COMPONENT_AS_PROPERTY, $component->id, $id)); } $this->components[$component->id] = $component; $component->setOwner($this); $component->onAdded(); return $component; }
Deletes configuration value by its associated key @param string $key @throws \RuntimeException if attempted to remove by non-existing key @return boolean
public function remove($key) { $this->load(); if ($this->exists($key)) { unset($this->config[$key]); return true; } else { throw new RuntimeException(sprintf('Attempted to read non-existing key "%s"', $key)); } }
/* returns container object
function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }
Receive the updated counter.
function (err, updatedIdentityCounter) { if (err) return next(err); // If there are no errors then go ahead and set the document's field to the current count. doc[settings.field] = updatedIdentityCounter.count; // Continue with default document save functionality. next(); }
Set the draggable view portion. Use to null, to allow the whole panel to be draggable @param dragView A view that will be used to drag the panel.
public void setDragView(View dragView) { if (mDragView != null) { mDragView.setOnClickListener(null); } mDragView = dragView; if (mDragView != null) { mDragView.setClickable(true); mDragView.setFocusable(false); mDragView.setFocusableInTouchMode(false); mDragView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isEnabled()) return; if (!isPanelExpanded()) { expandPanel(mAnchorPoint); } else { collapsePanel(); } } });; } }
Render a dump for a resource @param mixed $data @param string $name @access private @static
private static function _resource($data, $name) { $html = '<li class="krumo-child"> <div class="krumo-element" onMouseOver="krumo.over(this);" onMouseOut="krumo.out(this);"> <a class="krumo-name">%s</a> <em class="krumo-type">Resource</em> %s<strong class="krumo-resource">%s</strong> </div></li>'; $html = sprintf($html, $name, static::get_separator(), get_resource_type($data)); echo $html; }
// NewIssue creates a new Issue
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue { var code string fobj := ctx.FileSet.File(node.Pos()) name := fobj.Name() start, end := fobj.Line(node.Pos()), fobj.Line(node.End()) line := strconv.Itoa(start) if start != end { line = fmt.Sprintf("%d-%d", start, end) } // #nosec if file, err := os.Open(fobj.Name()); err == nil { defer file.Close() s := (int64)(fobj.Position(node.Pos()).Offset) // Go bug, should be int64 e := (int64)(fobj.Position(node.End()).Offset) // Go bug, should be int64 code, err = codeSnippet(file, s, e, node) if err != nil { code = err.Error() } } return &Issue{ File: name, Line: line, RuleID: ruleID, What: desc, Confidence: confidence, Severity: severity, Code: code, } }
// Disconnect implements Recorder.
func (r *recorder) Disconnect(server string, id uint64) { r.mu.Lock() defer r.mu.Unlock() if !r.enabled { return } if pos := r.findIndex(server, id); pos >= 0 { if pos == 0 { r.entries = r.entries[1:] } else { r.entries = append(r.entries[0:pos], r.entries[pos+1:]...) } } }
Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.
def begin(self, service_endpoint): """""" if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) request = AuthRequest(service_endpoint, assoc) request.return_to_args[self.openid1_nonce_query_arg_name] = mkNonce() if request.message.isOpenID1(): request.return_to_args[self.openid1_return_to_identifier_name] = \ request.endpoint.claimed_id return request
Checks if sink stream is good for write. @return bool
function isGood() { $meta = stream_get_meta_data($this->stream); $mode = $meta['mode']; return false === strpos($mode, 'r') || true === strpos($mode, 'r+'); }
Attaches a stage and assigns a fallback to the attached stage. @param callable $stage @param callable|null $fallback @return void
public function attach(callable $stage, callable $fallback = null) { $this->storage->attach( $this->marshalClosure($stage), [ 'fallback' => is_callable($fallback) ? $this->marshalClosure($fallback) : null ] ); }
xx-x-xx or xxxx-xx-x
function(v,node){ var format = this.__dataset(node,'format')||'yyyy-MM-dd'; return !v||(!isNaN(this.__doParseDate(v)) && _u._$format(this.__doParseDate(v),format) == v); }
// AddDepend add dependent module
func (t *Module) AddDepend(modules ...*Module) *Module { t.Depend = append(t.Depend, modules...) return t }
Return a list of <code>Point</code> objects detailing the path from the first node (the given node's ultimate parent) to the ending node (the given node itself.) @param n the ending node in the path. @return the list detailing the path.
protected static List<Point> getNodePath (Node n) { Node cur = n; ArrayList<Point> path = Lists.newArrayList(); while (cur != null) { // add to the head of the list since we're traversing from // the end to the beginning path.add(0, new Point(cur.x, cur.y)); // advance to the next node in the path cur = cur.parent; } return path; }
Adds item to the tree @param string @param mixed @return array
public function addItem($path, $object = array(), $class = null) { $path = explode('/', $path); $object['class'] = $class; $args = array(); foreach($path as $key) { $args[] = $key; $args[] = 'children'; } //soft inject $tree = eden('registry', $this->tree); $last = count($args); foreach($object as $key => $value) { $args[$last - 1] = $key; $args[$last] = $value; $tree->callArray('set', $args); } $this->tree = $tree->getArray(); return $this; }
<p> The list of available IP address ranges, specified as IPv4 CIDR blocks. </p> @return The list of available IP address ranges, specified as IPv4 CIDR blocks.
public java.util.List<String> getManagementCidrRanges() { if (managementCidrRanges == null) { managementCidrRanges = new com.amazonaws.internal.SdkInternalList<String>(); } return managementCidrRanges; }
Takes the help text supplied as a doc string and extraxts the description and any param arguments.
def parser_help_text(help_text): """""" if help_text is None: return None, {} main_text = '' params_help = {} for line in help_text.splitlines(): line = line.strip() match = re.search(r':\s*param\s*(?P<param>\w+)\s*:(?P<help>.*)$', line) if match: params_help[match.group('param')] = match.group('help').strip() else: main_text += line + ' ' main_text = main_text.strip() return main_text, params_help
// Creates a fid for the specified user that points to the root // of the file server's file tree. Returns a Fid pointing to the root, // if successful, or an Error.
func (clnt *Clnt) Attach(afid *Fid, user User, aname string) (*Fid, error) { var afno uint32 if afid != nil { afno = afid.Fid } else { afno = NOFID } fid := clnt.FidAlloc() tc := clnt.NewFcall() err := PackTattach(tc, fid.Fid, afno, user.Name(), aname, uint32(user.Id()), clnt.Dotu) if err != nil { return nil, err } rc, err := clnt.Rpc(tc) if err != nil { return nil, err } fid.Qid = rc.Qid fid.User = user fid.walked = true return fid, nil }
Renders checkbox list. @param string $name the name of input @param mixed $value the value of input @param array $options the HTMl options of input @return string
protected function renderCheckboxList($name, $value, $options) { $options['tabindex'] = self::TABINDEX; if (!array_key_exists('unselect', $options)) { $options['unselect'] = ''; } $options['item'] = function ($index, $label, $name, $checked, $value) use ($options) { $content = Html::checkbox($name, $checked, [ 'label' => $label, 'value' => $value, 'data-id' => ArrayHelper::getValue($options, 'id'), 'tabindex' => self::TABINDEX ]); return Html::tag('div', $content, ['class' => 'checkbox']); }; $input = Html::checkboxList($name, $value, $this->prepareItems($this->items), $options); return Html::tag('div', $input, ['class' => 'checkbox-list']); }
// SetOwnerId sets the OwnerId field's value.
func (s *ResolverRule) SetOwnerId(v string) *ResolverRule { s.OwnerId = &v return s }
/* (non-Javadoc) @see com.ibm.ws.javaee.ddmodel.DDParser.Parsable#describe(com.ibm.ws.javaee.ddmodel.DDParser.Diagnostics)
@Override public void describe(DDParser.Diagnostics diag) { diag.describeIfSet("class-name", className); diag.describeIfSet("name", name); diag.describeIfSet("actions", actions); }
// ListTypes lists all types in the process matching filter.
func (s *RPCServer) ListTypes(arg ListTypesIn, out *ListTypesOut) error { tps, err := s.debugger.Types(arg.Filter) if err != nil { return err } out.Types = tps return nil }
Return original querystring but containing only managed keys :return dict: dict of managed querystring parameter
def querystring(self): return {key: value for (key, value) in self.qs.items() if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')}
construct `$` map (from id annotations)
function applyIdToMap(inst, map, node, nodeInfo) { if (nodeInfo.id) { map[nodeInfo.id] = node; } }
Get the register info matching the flag. Raises ValueError if more than one are found.
def get_single_by_flags(self, flags): """""" regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
Create a session for the user, and then return the key.
def create_session(username, password): user = User.objects.get_user_by_password(username, password) auth_session_engine = get_config('auth_session_engine') if not user: raise InvalidInput('Username or password incorrect') session_key = random_string(15) while auth_session_engine.get(session_key): session_key = random_string(15) auth_session_engine.set(session_key, user.username, get_config('auth_session_expire')) return {'session_key': session_key, 'user': user}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*TaskStatus) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _TaskStatus_OneofMarshaler, _TaskStatus_OneofUnmarshaler, _TaskStatus_OneofSizer, []interface{}{ (*TaskStatus_Container)(nil), } }
### .init() Widget initialization @throws CException
public function init() { if (!$this->model instanceof CActiveRecord) { throw new CException(Yii::t('zii', '"model" attribute must be an CActiveRecord type of component')); } if (!$this->grid instanceof CGridView) { throw new CException(Yii::t('zii', '"grid" attribute must be an CGridView type of component')); } if (!$this->redirectRoute === null) { throw new CException(Yii::t('zii', '"redirectRoute" cannot be empty')); } $this->registry .= '-' . $this->grid->id; $this->jsonStorage = new JSONStorage(); $this->jsonStorage->addRegistry($this->registry); $this->filteredBy = array_filter( $this->model->getAttributes(), function ($i) { return $i != null; } ); $this->checkRequestRemovalFilter(); $this->checkRequestFilters(); $this->registerClientScript(); }
// Called to package the app
func packageApp(c *model.CommandConfig) (err error) { // Determine the run mode. mode := DefaultRunMode if len(c.Package.Mode) >= 0 { mode = c.Package.Mode } appImportPath := c.ImportPath revel_paths, err := model.NewRevelPaths(mode, appImportPath, "", model.NewWrappedRevelCallback(nil, c.PackageResolver)) if err != nil { return } // Remove the archive if it already exists. destFile := filepath.Join(c.AppPath, filepath.Base(revel_paths.BasePath)+".tar.gz") if c.Package.TargetPath != "" { if filepath.IsAbs(c.Package.TargetPath) { destFile = c.Package.TargetPath } else { destFile = filepath.Join(c.AppPath, c.Package.TargetPath) } } if err := os.Remove(destFile); err != nil && !os.IsNotExist(err) { return utils.NewBuildError("Unable to remove target file", "error", err, "file", destFile) } // Collect stuff in a temp directory. tmpDir, err := ioutil.TempDir("", filepath.Base(revel_paths.BasePath)) utils.PanicOnError(err, "Failed to get temp dir") // Build expects the command the build to contain the proper data if len(c.Package.Mode) >= 0 { c.Build.Mode = c.Package.Mode } c.Build.TargetPath = tmpDir c.Build.CopySource = c.Package.CopySource buildApp(c) // Create the zip file. archiveName, err := utils.TarGzDir(destFile, tmpDir) if err != nil { return } fmt.Println("Your archive is ready:", archiveName) return }
Set the conditions to join on. @param string $foreignKey @param string $key @return $this
public function on($foreignKey, $key = null) { if (is_array($foreignKey)) { $this->_conditions = array_replace($this->_conditions, $foreignKey); } else { $this->_conditions[$foreignKey] = $key; } return $this; }
Seed content types @return void
private function seedContentTypes() { ContentType::firstOrCreate(['name' => 'content', 'handler' => Gzero\Cms\Handlers\Content\ContentHandler::class]); ContentType::firstOrCreate(['name' => 'category', 'handler' => Gzero\Cms\Handlers\Content\CategoryHandler::class]); }
// ToSlice returns the elements of the current set as a slice
func (set LiteralFieldSet) ToSlice() []LiteralField { var s []LiteralField for v := range set { s = append(s, v) } return s }
Imports workspace. @param SessionInterface $session @param string $path @param string $fileName
private function import(SessionInterface $session, $path, $fileName) { if ($session->nodeExists($path)) { $session->getNode($path)->remove(); $session->save(); } $session->importXML( PathHelper::getParentPath($path), $fileName, ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW ); $session->save(); }
Checks the image size and its compatibility with classifier's receptive field. At this moment it is required that image size = K * receptive_field. This will be relaxed in future with the introduction of padding.
def _check_image(self, X): if (len(X.shape) < 3) or (len(X.shape) > 4): raise ValueError('Input has to have shape [n_samples, n_pixels_y, n_pixels_x] ' 'or [n_samples, n_pixels_y, n_pixels_x, n_bands].') self._samples = X.shape[0] self._image_size = X.shape[1:3] if (self._image_size[0] % self.receptive_field[0]) or (self._image_size[0] % self.receptive_field[0]): raise ValueError('Image (%d,%d) and receptive fields (%d,%d) mismatch.\n' 'Resize your image to be divisible with receptive field.' % (self._image_size[0], self._image_size[0], self.receptive_field[0], self.receptive_field[1]))
// StdinPipe returns a pipe that will be connected to the // remote command's standard input when the command starts.
func (s *Session) StdinPipe() (io.WriteCloser, error) { if s.Stdin != nil { return nil, errors.New("ssh: Stdin already set") } if s.started { return nil, errors.New("ssh: StdinPipe after process started") } s.stdinpipe = true return &sessionStdin{s.ch, s.ch}, nil }
增加一个 @param $node_name @param $uid @throws \Server\Asyn\MQTT\Exception
public function th_addUid($node_name, $uid) { if (!isset($this->map[$node_name])) { $this->map[$node_name] = new Set(); } $this->map[$node_name]->add($uid); if (Start::isLeader()) { get_instance()->pub('$SYS/uidcount', $this->countOnline()); } }
Contains childrenEntities @param Entity[] $childrenEntities @return bool
public function containsChildrenEntities(array $childrenEntities) { foreach ($childrenEntities as $childrenEntity) { if (!$this->childrenEntities->contains($childrenEntity)) { return false; } } return true; }
This script removes all tables associated with Trump. It's written for PostgreSQL, but should be very easy to adapt to other databases.
def UninstallTrump(RemoveDataTables=True, RemoveOverrides=True, RemoveFailsafes=True): ts = ['_symbols', '_symbol_validity', '_symbol_tags', '_symbol_aliases', '_feeds', '_feed_munging', '_feed_munging_args', '_feed_sourcing', '_feed_validity', '_feed_meta', '_feed_tags', '_feed_handle', '_index_kwargs', '_indicies', '_symbol_handle', '_symboldatadef'] if RemoveOverrides: ts.append('_overrides') if RemoveFailsafes: ts.append('_failsafes') engine = create_engine(ENGINE_STR) if RemoveDataTables: results = engine.execute("SELECT name FROM _symbols;") datatables = [row['name'] for row in results] ts = ts + datatables drops = "".join(['DROP TABLE IF EXISTS "{}" CASCADE;'.format(t) for t in ts]) engine.execute(drops)
Delete children that are no longer contained in list of collection items. @param resource Parent resource @param data List of collection items
public static void deleteChildrenNotInCollection(Resource resource, ConfigurationCollectionPersistData data) { Set<String> collectionItemNames = data.getItems().stream() .map(item -> item.getCollectionItemName()) .collect(Collectors.toSet()); for (Resource child : resource.getChildren()) { if (!collectionItemNames.contains(child.getName()) && !StringUtils.equals(JCR_CONTENT, child.getName())) { deletePageOrResource(child); } } }
--- CALL SERVICE ---
@Override public Promise call(String name, Tree params, Options opts, PacketStream stream, Context parent) { String targetID; int remaining; if (opts == null) { targetID = null; remaining = 0; } else { targetID = opts.nodeID; remaining = opts.retryCount; } return call(name, params, opts, stream, parent, targetID, remaining); }
Executes download request :param request: A request :type request: DownloadRequest :return: Response of the request :rtype: requests.Response
def _do_request(request): if request.request_type is RequestType.GET: return requests.get(request.url, headers=request.headers) if request.request_type is RequestType.POST: return requests.post(request.url, data=json.dumps(request.post_values), headers=request.headers) raise ValueError('Invalid request type {}'.format(request.request_type))
@param $data @return PatternException
protected function newInvalidToUrl($data) { switch (\gettype($data)) { case 'string': $type = \sprintf('(string) %s', \var_export($data, true)); break; case 'object': $type = \sprintf('(object) %s', \get_class($data)); break; case 'integer': case 'double': case 'float': $type = \sprintf('(%s) %s', \gettype($data), \var_export($data, true)); break; default: $type = \gettype($data); break; } return new PatternException( \sprintf('Value %s cannot be converted to url param (%s)', $type, static::class), PatternException::CODE_TO_URL ); }
Test if host data should trigger a check. Args: artifact: An artifact name. os_name: An OS string. cpe: A CPE string. label: A label string. Returns: A list of conditions that match.
def Match(self, artifact=None, os_name=None, cpe=None, label=None): return [ c for c in self.conditions if c.Match(artifact, os_name, cpe, label) ]
Create polymorphic functions @package polymorphic @copyright Konfirm ⓒ 2015-2019 @author Rogier Spieker (rogier+npm@konfirm.eu) @license MIT
function polymorphic() { var registry = []; /** * Determine if somewhere in the prototype chains the variable extends an Object with given name * @name isExtendOf * @access internal * @param string name * @param object variable * @return bool extends */ function isExtendOf(name, variable) { var offset = typeof variable === 'object' && variable ? Object.getPrototypeOf(variable) : null, pattern = offset ? new RegExp('^' + name + '$') : null; // It is not quite feasible to compare the inheritance using `instanceof` (all constructors would have to // be registered somehow then) we simply compare the constructor function names. // As a side effect, this enables polymorphic to compare against the exact type (unless a developer has // altered the constructor name, which is not protected from overwriting) while (offset && offset.constructor) { if (pattern.test(offset.constructor.name)) { return true; } offset = Object.getPrototypeOf(offset); } return false; } /** * Map the param property of given candidate to contain only the values and resolve any references to other arguments * @name parameterize * @access internal * @param Object candidate * @return Object candidate (with resolved params) */ function parameterize(candidate) { candidate.param = candidate.param.map(function(param) { var value; if ('value' in param) { value = param.value; } else if ('reference' in param) { value = candidate.param.reduce(function(p, c) { return c !== param && !p && param.reference === c.name && 'value' in c ? c.value : p; }, null); } return value; }); return candidate; } /** * Filter given list so only matching signatures are kept * @name matchSignature * @access internal * @param array candidates * @param array arguments * @return array filtered candidates */ function matchSignature(list, arg) { var types = arg.map(function(variable) { return new RegExp('^(' + type(variable) + ')'); }); return list.filter(function(config) { var variadic = false, result; // result is true if no more arguments are provided than the signature allows OR the last // argument in the signature is variadic result = arg.length <= config.arguments.length || (config.arguments[config.arguments.length - 1] && config.arguments[config.arguments.length - 1].type === '...'); // test each given argument agains the configured signatures if (result) { arg.forEach(function(value, index) { var expect = config.arguments[index] ? config.arguments[index].type : null; // look at ourself and ahead - if there is a following item, and it is variadic, it may be // left out entirely (zero or more) if (isTypeAtIndex('...', config.arguments, index)) { variadic = true; } // the result remains valid as long as the values match the given signature // (type matches or it is variadic) result = result && (variadic || types[index].test(expect) || (expect[expect.length - 1] !== '!' && isExtendOf(expect, value))); }); } return result; }); } /** * Map the registered values to a new object containing the specifics we use to determine the best * @name prepare * @access internal * @param array candidates * @param array arguments * @return array mapped candidates */ function prepare(list, arg) { return list.map(function(config) { var item = { // the function to call call: config.call, // all configured arguments arguments: config.arguments, // the calculated specificity specificity: config.arguments.map(function(argument, index) { var value = 'value' in argument, specificity = 0; // if a argument not a variadic one and the value is specified if (argument.type !== '...' && index < arg.length) { ++specificity; // bonus points if the exact type matches (explicit by type) // OR there is no default value (explicitly provided) if (Number(argument.type === type(arg[index], true) || isExtendOf(argument.type, arg[index]) || !value)) { ++specificity; } // extra bonus points if the type is explicity the same (in case of inheritance) if (new RegExp('^' + type(arg[index], true) + '!$').test(argument.type)){ ++specificity; } } return specificity; }).join(''), // the parameters with which the `call` may be executed param: config.arguments.map(function(argument, index) { var result = {}; result.name = argument.name; // if a variadic type is encountered, the remainder of the given arguments becomes the value if (argument.type === '...') { result.value = arg.slice(index); } else if (index < arg.length && typeof arg[index] !== 'undefined' && arg[index] !== null) { result.value = arg[index]; } else if ('value' in argument) { result.value = argument.value; } else if ('reference' in argument) { result.reference = argument.reference; } return result; }) }; return item; }); } /** * Prioritize the items in the list * @name prepare * @access internal * @param array candidates * @param array arguments * @return array prioritized candidates * @note the list should contain pre-mapped items (as it works on specificity mostly) */ function prioritize(list, arg) { return list.sort(function(a, b) { var typing = function(item, index) { return +(item.type === type(arg[index], true)); }; // if the calculated specificity is not equal it has precedence if (a.specificity !== b.specificity) { // the shortest specificity OR ELSE the highest specificity wins return a.specificity.length - b.specificity.length || b.specificity - a.specificity; } // if the specificity is equal, we want to prioritize on the more explicit types return b.arguments.map(typing).join('') - a.arguments.map(typing).join(''); }); } /** * Compare the type of the argument at a specific position within a collection * @name isTypeAtIndex * @access internal * @param string type * @param array arguments * @param int index * @return boolean type at index */ function isTypeAtIndex(type, list, index) { return list.length > index && 'type' in list[index] ? list[index].type === type : false; } /** * Determine the proper delegate handler for given arguments * @name delegate * @access internal * @param array arguments * @return mixed handler result */ function delegate(arg) { // create a list of possible candidates based on the given arguments var candidate = matchSignature(registry, arg); // prepare the configured signatures/arguments based on the arguments actually recieved candidate = prepare(candidate, arg); // prioritize the candidates candidate = prioritize(candidate, arg); // and finally, filter any candidate which does not fully comply with the signature based on the - now - parameters candidate = candidate.filter(function(item) { var variadic = false, min = item.arguments.map(function(argument, index) { variadic = isTypeAtIndex('...', item.arguments, index) || isTypeAtIndex('...', item.arguments, index + 1); return +(!(variadic || 'value' in argument || 'reference' in argument)); }).join('').match(/^1+/); return arg.length >= (min ? min[0].length : 0); }); return candidate.length ? parameterize(candidate[0]) : false; } /** * Cast variable to given type * @name cast * @access internal * @param string type * @param string value * @return mixed value */ function cast(type, variable) { var result = variable; switch (type) { case 'number': result = +result; break; case 'int': result = parseInt(result, 10); break; case 'float': result = parseFloat(result); break; case 'bool': case 'boolean': result = ['true', '1', 1].indexOf(result) >= 0; break; } return result; } /** * Create a string matching various number types depending on given variable * @name numberType * @access internal * @param string type * @param number variable * @param bool explicit typing * @return string types */ function numberType(type, variable, explicit) { // if the integer value is identical to the float value, it is an integer return (parseInt(variable, 10) === parseFloat(variable) ? 'int' : 'float') + (explicit ? '' : '|' + type); } /** * Create a string matching various object types (object constructor name if explicit) * @name objectType * @access internal * @param string type * @param object variable * @param bool explicit typing * @return string types */ function objectType(type, variable, explicit) { // array get some special treatment by indicating it is not an object but instead an array // this also goes for inherited types if (variable instanceof Array) { type = 'array'; } return variable ? variable.constructor.name + (explicit ? '' : '|' + type) : 'null'; } /** * Create a string matching 'boolean' type and - if not explicit - its shorthand version 'bool' * @name booleanType * @access internal * @param string type * @param bool explicit typing * @return string types */ function booleanType(type, explicit) { return type + (explicit ? '' : '|bool'); } /** * Create a string matching undefined (and any string having one or more alphatical characters if not explicit) * @name undefinedType * @access internal * @param string type * @param bool explicit typing * @return string types */ function undefinedType(type, explicit) { return type + (explicit ? '' : '|[a-z]+'); } /** * Determine the type and create a string ready for use in regular expressions * @name type * @access internal * @param mixed variable * @param bool explicit * @return string type */ function type(variable, explicit) { var result = typeof variable; switch (result) { case 'number': result = numberType(result, variable, explicit); break; case 'object': result = objectType(result, variable, explicit); break; case 'boolean': result = booleanType(result, explicit); break; case 'undefined': result = undefinedType(result, explicit); break; } return result; } /** * Process the expression match result and prepare the argument object * @name prepareArgument * @access internal * @param RegExpMatch match * @param string defaultname * @result Object argument */ function prepareArgument(match, name) { var result = { type: match ? match[1] : false, name: match ? match[2] : name }; if (match) { if (match[4] === '@') { result.reference = match[5]; } else if (match[3] === '=') { result.value = cast(result.type, match[5]); } } return result; } /** * Parse given signature string and create an array containing all argument options for the signature * @name parse * @access internal * @param string signature * @return array options */ function parse(signature) { var pattern = /^(?:void|([a-zA-Z]+!?|\.{3})(?:[:\s]+([a-zA-Z]+)(?:(=)(@)?(.*))?)?)?$/; return signature.split(/\s*,\s*/).map(function(argument, index, all) { var result = prepareArgument(argument.match(pattern), 'var' + (index + 1)); if (result.type === false) { throw new Error('polymorphic: invalid argument "' + argument + '" in signature "' + signature + '"'); } else if (result.type === '...' && index < all.length - 1) { throw new Error('polymorphic: variadic argument must be at end of signature "' + signature + '"'); } return result; }).filter(function(argument) { // a type is undefined if it was declared as 'void' or '' (an empty string) return argument.type !== undefined; }); } /** * The main result function, this is the function actually being returned by `polymorphic` * @name result * @access internal * @param * [one or more arguments] * @return mixed handler result * @throws polymorph: signature not found "<resolved pattern>" */ function polymorph() { var arg = Array.prototype.slice.call(arguments), candidate = delegate(arg); if (!candidate) { throw new Error('polymorph: signature not found "' + arg.map(function(variable) { return type(variable); }).join(', ') + '"'); } return candidate.call.apply(this, candidate.param); } /** * Add one or more signatures and a handler for those signatures * @name signature * @access public * @param string signature1 * @param string signatureN [optional - any number of signature can be provided for a handler] * @param function handler * @return void * @throws polymorphic.signature: expected one or more signatures * polymorphic.signature: expected final argument to be a callback */ polymorph.signature = function() { var arg = Array.prototype.slice.call(arguments), call = arg.length && typeof arg[arg.length - 1] === 'function' ? arg.pop() : null; if (!arg.length) { throw new Error('polymorphic.signature: expected one or more signatures'); } else if (!call) { throw new Error('polymorphic.signature: expected final argument to be a callback'); } arg.forEach(function(signature) { registry.push({ signature: signature, arguments: parse(signature), call: call }); }); }; return polymorph; }
Private: Send a chunk. Used by the higher-level methods type - the chunk type content = nil - the actual content
def send_chunk(type, content = nil) chunk = Chunk.new(type, content).to_s socket.write chunk end
'WHERE' only support 'AND'
public function delete($table, array $where) { $keys = array_keys($where); $values = array_values($where); $replace = function ($key) { return $key . "=?"; }; $where = implode(' AND ', array_map($replace, $keys)); $sql = "DELETE FROM {$table} WHERE {$where}"; return $this->query($sql, $values); }
// Focus focuses the provided group. // This skips all specs in the suite except the group and other focused specs. // // Valid Options: // Sequential, Random, Reverse, Parallel // Local, Global, Flat, Nested
func (g G) Focus(text string, f func(), opts ...Option) { g(text, f, append(opts, func(c *config) { c.focus = true })...) }
//export diffForEachHunkCb
func diffForEachHunkCb(delta *C.git_diff_delta, hunk *C.git_diff_hunk, handle unsafe.Pointer) int { payload := pointerHandles.Get(handle) data, ok := payload.(*diffForEachData) if !ok { panic("could not retrieve data for handle") } data.LineCallback = nil if data.HunkCallback != nil { cb, err := data.HunkCallback(diffHunkFromC(hunk)) if err != nil { data.Error = err return -1 } data.LineCallback = cb } return 0 }
/* (non-Javadoc) @see com.ibm.ws.sib.msgstore.cache.xalist.Task#commitStage1(com.ibm.ws.sib.msgstore.Transaction)
public final void commitInternal(final PersistentTransaction transaction) throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "commitInternal", transaction); getLink().commitRemove(transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "commitInternal"); }