query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
This filter sorts nodes in a flat group into "required", "default", and "banned" subgroups based on the presence of plus and minus nodes.
def do_minus(self, parser, group): '''This filter sorts nodes in a flat group into "required", "default", and "banned" subgroups based on the presence of plus and minus nodes. ''' grouper = group.__class__() next_not = None for node in group: if isins...
csn
Main method of the class, which handles the process of creating the tests @param requirementsFolder , it is the folder where the plain text given by the client is stored @param platformName , to choose the MAS platform (JADE, JADEX, etc.) @param src_test_dir , the folder where our classes are created @param tests_pack...
public static void generateJavaFiles(String requirementsFolder, String platformName, String src_test_dir, String tests_package, String casemanager_package, String loggingPropFile) throws Exception { File reqFolder = new File(requirementsFolder); if (reqFolder.isDirec...
csn
// forwardServer is used to forward an RPC call to a particular server
func (r *rpcHandler) forwardServer(server *serverParts, method string, args interface{}, reply interface{}) error { // Handle a missing server if server == nil { return errors.New("must be given a valid server address") } return r.connPool.RPC(r.config.Region, server.Addr, server.MajorVersion, method, args, reply...
csn
Get the node for a path @param array $nodes An array of nodes @param string $path The path representing a node. A path is a set of labels concatenated by '/' @return boolean|array False if the node is not found or a reference to the node represented by the $path
private function &findNodeFromPath( &$nodes, $path ) { $pathsParts = explode( '/', $path ); $node = null; for ( $i = 0; $i < count( $pathsParts ); $i++ ) { if ( ! isset( $nodes[ $pathsParts[ $i ] ] ) ) { $node = false; break; } $node =& $nodes[ $pathsParts[ $i ] ]; if (...
csn
Update blockMap by the given LogEntry
private synchronized void updateBlockInfo(LogEntry e) { BlockScanInfo info = blockMap.get(new Block(e.blockId, 0, e.genStamp)); if(info != null && e.verificationTime > 0 && info.lastScanTime < e.verificationTime) { delBlockInfo(info); info.lastScanTime = e.verificationTime; info....
csn
Defines a new class by setting a contextual name @param {String} name New class contextual name @param {Function} Super Super class @param {Object} definition Class definition @return {Function} New class constructor
function _gpfDefineCore (name, Super, definition) { var NewClass = _gpfDefineFactory(name, Super, definition); _gpfDefineUpdateContext(name, NewClass); return NewClass; }
csn
Remove a channel from the call. @param channel
public void remove(Channel channel) { synchronized (this._associatedChannels) { int index = findChannel(channel); if (index != -1) { if (logger.isDebugEnabled()) logger.debug( "CallTracker removing ch...
csn
// NewTfaRemoveSecurityKeyType returns a new TfaRemoveSecurityKeyType instance
func NewTfaRemoveSecurityKeyType(Description string) *TfaRemoveSecurityKeyType { s := new(TfaRemoveSecurityKeyType) s.Description = Description return s }
csn
Unmarshall a DOMElement object corresponding to a QTI templateConstraint element. @param \DOMElement $element A DOMElement object. @return \qtism\data\QtiComponent A TemplateConstraint object. @throws \qtism\data\storage\xml\marshalling\UnmarshallingException
protected function unmarshall(DOMElement $element) { $expressionElt = self::getFirstChildElement($element); try { return new TemplateConstraint($this->getMarshallerFactory()->createMarshaller($expressionElt)->unmarshall($expressionElt)); } catch (InvalidArgumentException $e) { ...
csn
// NewFilter creates a new filter.
func NewFilter(includeRegex, excludeRegex string) (*Filter, error) { f := &Filter{} var err error if includeRegex != "" { f.inc, err = regexp.Compile(includeRegex) if err != nil { return nil, err } } if excludeRegex != "" { f.exc, err = regexp.Compile(excludeRegex) if err != nil { return nil, err ...
csn
Given a set of entity objects generate a networkx.Graph that represents their vertex nodes. Parameters -------------- entities : list Objects with 'closed' and 'nodes' attributes Returns ------------- graph : networkx.Graph Graph where node indexes represent vertices clo...
def vertex_graph(entities): """ Given a set of entity objects generate a networkx.Graph that represents their vertex nodes. Parameters -------------- entities : list Objects with 'closed' and 'nodes' attributes Returns ------------- graph : networkx.Graph Graph where...
csn
Get the message as text. If this is a binary message (that is, the message protocol does not define a charset), encodes it using Base64. @return The message as text.
public String messageAsText() { if (protocol.charset().isPresent()) { return message.decodeString(protocol.charset().get()); } else { return Base64.getEncoder().encodeToString(message.toArray()); } }
csn
Handle subscription of topics.
def _handle_subscription(self, topics): """Handle subscription of topics.""" if not isinstance(topics, list): topics = [topics] for topic in topics: topic_levels = topic.split('/') try: qos = int(topic_levels[-2]) except ValueError:...
csn
transfer a file from local to local
def put_file(self, in_path, out_path): ''' transfer a file from local to local ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shuti...
csn
// GetBlock retrieves a block from the database or ODR service by hash and number, // caching it if found.
func (lc *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) { // Short circuit if the block's already in the cache, retrieve otherwise if block, ok := lc.blockCache.Get(hash); ok { return block.(*types.Block), nil } block, err := GetBlock(ctx, lc.odr, hash, number) ...
csn
Add to all table a specifix prefix. @param db the db @param prefix the prefix
public static void renameTablesWithPrefix(SQLiteDatabase db, final String prefix) { Logger.info("MASSIVE TABLE RENAME OPERATION: ADD PREFIX " + prefix); query(db, null, QueryType.TABLE, new OnResultListener() { @Override public void onRow(SQLiteDatabase db, String name, String sql) { sql = String.format(...
csn
// CreateProposalResponse creates a proposal response.
func CreateProposalResponse(hdrbytes []byte, payl []byte, response *peer.Response, results []byte, events []byte, ccid *peer.ChaincodeID, visibility []byte, signingEndorser msp.SigningIdentity) (*peer.ProposalResponse, error) { hdr, err := GetHeader(hdrbytes) if err != nil { return nil, err } // obtain the propo...
csn
Sample-to-detector distance
def distance(self) -> ErrorValue: """Sample-to-detector distance""" if 'DistCalibrated' in self._data: dist = self._data['DistCalibrated'] else: dist = self._data["Dist"] if 'DistCalibratedError' in self._data: disterr = self._data['DistCalibratedError...
csn
Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier.
def capitalize_unicode_name(s): """ Turns a string such as 'capital delta' into the shortened, capitalized version, in this case simply 'Delta'. Used as a transform in sanitize_identifier. """ index = s.find('capital') if index == -1: return s tail = s[index:].replace('capital', '').stri...
csn
Deserialize the data into it's original python object. :param bytes data: The serialized object to load. :return: The original python object.
def loads(self, data): """ Deserialize the data into it's original python object. :param bytes data: The serialized object to load. :return: The original python object. """ if not isinstance(data, bytes): raise TypeError("loads() argument 1 must be bytes, not {0}".format(type(data).__name__)) if self....
csn
Find all plans that have trial. @author Vova Feldman (@svovaf) @since 1.0.9 @param FS_Plugin_Plan[] $plans @return FS_Plugin_Plan[]
function get_trial_plans( $plans ) { $trial_plans = array(); if ( is_array( $plans ) && 0 < count( $plans ) ) { /** * @var FS_Plugin_Plan[] $plans */ for ( $i = 0, $len = count( $plans ); $i < $len; $i ++ ) { if ( $plans[ $i ]->has_trial() ) { $trial_plans[] = $plans[ $i ]; } ...
csn
Command handler - treats each word in the message that triggered the command as an argument to the command, and does some validation to ensure that the number of arguments match.
def handle_command_event(self, event, command, args): """ Command handler - treats each word in the message that triggered the command as an argument to the command, and does some validation to ensure that the number of arguments match. """ argspec = getargspec(co...
csn
// create new keyfile given filepath
func NewKeyfile(f string) *Keyfile { if strings.ToUpper(f) == "TRANSIENT" { f = "" } return &Keyfile{ fname: f, } }
csn
// SetOpenShiftClient sets the passed OpenShift client in the application configuration
func (c *AppConfig) SetOpenShiftClient(imageClient imagev1typedclient.ImageV1Interface, templateClient templatev1typedclient.TemplateV1Interface, routeClient routev1typedclient.RouteV1Interface, OriginNamespace string, dockerclient *docker.Client) { c.OriginNamespace = OriginNamespace namespaces := []string{OriginNam...
csn
Loads data set from file.
protected function load() { if (!file_exists($this->getFileName())) { return; } $this->dataSet = json_decode(file_get_contents($this->getFileName())); if (!$this->dataSet) { throw new ContentNotFound("Loaded snapshot is empty"); } }
csn
// SetJobBookmarksEncryptionMode sets the JobBookmarksEncryptionMode field's value.
func (s *JobBookmarksEncryption) SetJobBookmarksEncryptionMode(v string) *JobBookmarksEncryption { s.JobBookmarksEncryptionMode = &v return s }
csn
Setup repistory form. @param moodleform $mform Moodle form (passed by reference) @param string $classname repository class name
public static function type_config_form($mform, $classname = 'repository') { global $OUTPUT; $a = new stdClass; $a->callbackurl = microsoft_skydrive::callback_url()->out(false); $mform->addElement('static', null, '', get_string('oauthinfo', 'repository_skydrive', $a)); $mform->...
csn
Add a list of devices in the group or add a list of patterns @param attributes The attribute list @throws DevFailed
private synchronized void add(final String... attributes) throws DevFailed { userAttributesNames = new String[attributes.length]; devices = new DeviceProxy[attributes.length]; int i = 0; for (final String attributeName : attributes) { final String deviceName = TangoUtil.getfu...
csn
Scores the similarity between two strings by returning the length of the longest common subsequence. Intended for comparing strings of different lengths; eg. when matching a typeahead search input with a school name. Meant for use in an instant search box where results are being fetched as a user is typing. @param a...
function typeaheadSimilarity(a, b) { var aLength = a.length; var bLength = b.length; var table = []; if (!aLength || !bLength) { return 0; } // Ensure `a` isn't shorter than `b`. if (aLength < bLength) { var _ref2 = [b, a]; a = _ref2[0]; b = _ref2[1]; } ...
csn
Set a sub-attribute. @param attrName @param value @return
public BaseJsonBo setSubAttr(String attrName, String dPath, Object value) { if (value == null) { return removeSubAttr(attrName, dPath); } Lock lock = lockForWrite(); try { JsonNode attr = cacheJsonObjs.get(attrName); if (attr == null) { ...
csn
// DeallocateService de-allocates all the network resources such as // virtual IP and ports associated with the service.
func (na *cnmNetworkAllocator) DeallocateService(s *api.Service) error { if s.Endpoint == nil { return nil } for _, vip := range s.Endpoint.VirtualIPs { if err := na.deallocateVIP(vip); err != nil { // don't bail here, deallocate as many as possible. log.L.WithError(err). WithField("vip.network", vip....
csn
Not a DSL method, but initialized from Deck.new
def enable_groups_from_env! return if ENV['SQUIB_BUILD'].nil? ENV['SQUIB_BUILD'].split(',').each do |grp| enable_build grp.strip.to_sym end end
csn
// Next use uses recordSet's executor to get next available chunk for later usage. // If chunk does not contain any rows, then we update last query found rows in session variable as current found rows. // The reason we need update is that chunk with 0 rows indicating we already finished current query, we need prepare f...
func (a *recordSet) Next(ctx context.Context, req *chunk.RecordBatch) error { if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil { span1 := span.Tracer().StartSpan("recordSet.Next", opentracing.ChildOf(span.Context())) defer span1.Finish() } err := a.executor.Next(ctx, req) if err...
csn
Converts text line breaks into HTML paragraphs and HTML line breaks. @param string $string String to transform @return string
public function nlToPbr($string) { $string = trim($string); $string = Modifiers::linebreaks($string); $string = str_replace("\n", '<br />', $string); $string = str_replace('<br /><br />', "</p>\n<p>", $string); $string = str_replace('<p></p>', '', $string); return '<p>' . $string . '</p>' . PHP_EOL; }
csn
Composer\Package\PackageInterface but the use causes some issue
private function buildOperation($type, $package) { $vendorDir = $this->kernel->getRootDir().'/../vendor'; $targetDir = $package->getTargetDir() ?: ''; $packageDir = empty($targetDir) ? $package->getPrettyName() : "{$package->getName()}/{$targetDir}"; $fqcn = $...
csn
Merge a given list of typingNames to the inferredTypings map
function mergeTypings(typingNames) { if (!typingNames) { return; } for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { var typing = typingNames_1[_i]; if (!(typing in inferredTypings)...
csn
Dumps views. @since 2.5.0
protected function dumpViews() { $this->tables->execute(); foreach ($this->tables->fetchAll(\PDO::FETCH_ASSOC) as $a) { $view = current($a); if (!isset($a['Table_type']) || $a['Table_type'] !== 'VIEW') { continue; } if (in_array($vie...
csn
Remove all the datastores and the database of the current user
def reset(yes): """ Remove all the datastores and the database of the current user """ ok = yes or confirm('Do you really want to destroy all your data? (y/n) ') if not ok: return dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file)) # user must be able to access and ...
csn
Validate that an attribute is a valid date. @param string $attribute @param mixed $value @return bool
protected function validateDate($attribute, $value) { if ($value instanceof DateTime) { return true; } if (strtotime($value) === false) { return false; } $date = date_parse($value); return checkdate($date['month'], $date['day'], $date['year'...
csn
From three tagNames, if one is under sectorTag and one under rowTag, returns the remaining one, which is supposedly the a box label. Otherwise, returns null.
private static TechReportPlacement processPlaceLabels(GraphContext graphContext, Set<String> tagNames) { TagGraphService tagService = new TagGraphService(graphContext); if (tagNames.size() < 3) throw new WindupException("There should always be exactly 3 placement labels - row, sector, c...
csn
Link AssetDeliveryPolicy to Asset. @param ContentKey|string $contentKey Asset to link a AssetDeliveryPolicy or Asset id @param AssetDeliveryPolicy|string $contentKeyDeliveryType DeliveryPolicy to link or DeliveryPolicy id @return string
public function getKeyDeliveryUrl($contentKey, $contentKeyDeliveryType) { $contentKeyId = Utilities::getEntityId( $contentKey, 'WindowsAzure\MediaServices\Models\ContentKey' ); $contentKeyId = urlencode($contentKeyId); $body = json_encode(['keyDeliveryType' =...
csn
// Set the PGP storage notification dismiss flag in the local DB.
func (h *PGPHandler) PGPStorageDismiss(ctx context.Context, sessionID int) error { username := h.G().Env.GetUsername() if username.IsNil() { return libkb.NewNoUsernameError() } key := libkb.DbKeyNotificationDismiss(libkb.NotificationDismissPGPPrefix, username) return h.G().LocalDb.PutRaw(key, []byte(libkb.Notif...
csn
Checks whether the token has expired or is still valid. If the token has no expiration date, assumes the token doesn't expire. @param \DateTime $date (optional) The date to compare with the epiration date of the token. If not provided, the current time is used. @return bool
public function expired(\DateTime $date = null) { // Check if the token has an expiration date. if (!$this->expire) { return false; } $date = $date ?: new \DateTime('now', new \DateTimezone('UTC')); return ($date > $this->expire); }
csn
Creates a directory structure in the provided destination directory. @param $destination
public function emitStructure($destination) { $this->treeGenerator->addPaths($this->getPaths()); return $this->treeGenerator->generate($destination); }
csn
// resolveInternetAddr resolves addr that is either a literal IP // address or a DNS name and returns an internet protocol family // address. It returns a list that contains a pair of different // address family addresses when addr is a DNS name and the name has // multiple address family records. The result contains a...
func ResolveInternetAddr(netw, addr string) (net.Addr, error) { var ( err error host, port, zone string portnum int ) switch netw { case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6": if addr != "" { if host, port, err = net.SplitHostPort(addr); err != nil { return nil, err } ...
csn
Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. The replacement should always be a string that may include references to the matched data from the rule. @param string $rule @param string $replacement @return void @author Koen Punt
public function plural($rule, $replacement){ if(is_string($rule)){ Utils::array_delete($this->uncountables, $rule); } Utils::array_delete($this->uncountables, $replacement); array_unshift($this->plurals, array($rule, $replacement)); }
csn
Returns the address of the host minimizing DNS lookups. @param addr @return
private static String getHostAddress(InetSocketAddress addr) { String hostToAppend = ""; if (addr.isUnresolved()) { hostToAppend = addr.getHostName(); } else { hostToAppend = addr.getAddress().getHostAddress(); } return hostToAppend; }
csn
gets Lowe's power spectrum from gauss coefficients Parameters _________ data : nested list of [[l,m,g,h],...] as from pmag.unpack() Returns _______ Ls : list of degrees (l) Rs : power at degree l
def lowes(data): """ gets Lowe's power spectrum from gauss coefficients Parameters _________ data : nested list of [[l,m,g,h],...] as from pmag.unpack() Returns _______ Ls : list of degrees (l) Rs : power at degree l """ lmax = data[-1][0] Ls = list(range(1, lmax+1))...
csn
Sets default actions, if configured to and none are defined. @return $this
protected function setDefaultRowActions() { $actions = $this->info->list->default_action ?: []; if (count($actions)) { return $this; } $addEditAction = config('cms-models.defaults.default-listing-action-edit', false); $addShowAction = config('cms-models.defaults...
csn
see if specific identity exists
async def exist(self, key, param=None): """see if specific identity exists""" identity = self._gen_identity(key, param) return await self.client.exists(identity)
csn
Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field
def audio_visual_key(name=None): """ Creates the grammar for an Audio Visual Key code. This is a variation on the ISAN (International Standard Audiovisual Number) :param name: name for the field :return: grammar for an ISRC field """ if name is None: name = 'AVI Field' societ...
csn
// newFreelist returns an empty, initialized freelist.
func newFreelist() *freelist { return &freelist{ pending: make(map[txid][]pgid), cache: make(map[pgid]bool), } }
csn
Internal use. @return The {@link Component} object for the specified class, null if the Entity does not have any components for that class.
@SuppressWarnings("unchecked") <T extends Component> T getComponent (ComponentType componentType) { int componentTypeIndex = componentType.getIndex(); if (componentTypeIndex < components.getCapacity()) { return (T)components.get(componentType.getIndex()); } else { return null; } }
csn
Bind to the application. Generate URL, name if it's not provided.
def bind(cls, app, *paths, methods=None, name=None, **kwargs): """Bind to the application. Generate URL, name if it's not provided. """ paths = paths or ['/%s(/{%s})?/?' % (cls.name, cls.name)] name = name or "api.%s" % cls.name return super(RESTHandler, cls).bind(app, *...
csn
// createMux initializes the main router the server uses.
func (s *Server) createMux() *mux.Router { m := mux.NewRouter() logrus.Debug("Registering routers") for _, apiRouter := range s.routers { for _, r := range apiRouter.Routes() { f := s.makeHTTPHandler(r.Handler()) logrus.Debugf("Registering %s, %s", r.Method(), r.Path()) m.Path(versionMatcher + r.Path())...
csn
Confirm that a send has completed. Does not actually check confirmations, but instead assumes that if this is called, the transaction has been completed. This is because we assume our own sends are safe. :param session: :param str ref_id: The updated ref_id for the transaction in question :param st...
def confirm_send(address, amount, ref_id=None, session=ses): """ Confirm that a send has completed. Does not actually check confirmations, but instead assumes that if this is called, the transaction has been completed. This is because we assume our own sends are safe. :param session: :param str...
csn
// CanMatch returns if this state can ever transition to a matching state // in this Automaton
func (f *FST) CanMatch(addr int) bool { if addr == noneAddr { return false } return true }
csn
Persist this x509 object to disk
def save(self, x509): """Persist this x509 object to disk""" self.x509 = x509 with open_tls_file(self.file_path, 'w', private=self.is_private()) as fh: fh.write(str(self))
csn
A generic identifier quoting function used for various parts of the query @param array $part the part of the query to quote @return array
protected function _basicQuoter($part) { $result = []; foreach ((array)$part as $alias => $value) { $value = !is_string($value) ? $value : $this->_driver->quoteIdentifier($value); $alias = is_numeric($alias) ? $alias : $this->_driver->quoteIdentifier($alias); $res...
csn
Return a list of blastn command-lines for ANIm - filenames - a list of paths to fragmented input FASTA files - outdir - path to output directory - blastn_exe - path to BLASTN executable Assumes that the fragment sequence input filenames have the form ACCESSION-fragments.ext, where the correspondin...
def generate_blastn_commands(filenames, outdir, blast_exe=None, mode="ANIb"): """Return a list of blastn command-lines for ANIm - filenames - a list of paths to fragmented input FASTA files - outdir - path to output directory - blastn_exe - path to BLASTN executable Assumes that the fragment seque...
csn
Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function sh...
def get_body_encoding(self): """Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object...
csn
Get the alias the shortcut points to. @param string $name Twig function name. @return string Either the alias or the name passed in if not found.
public function getShortcut($name) { $key = strtolower($name); return (array_key_exists($key, $this->shortcuts)) ? $this->shortcuts[$key] : $name; }
csn
Prepares the proxy servers to try.
private void resetNextProxy(HttpUrl url, Proxy proxy) { if (proxy != null) { // If the user specifies a proxy, try that and only that. proxies = Collections.singletonList(proxy); } else { // Try each of the ProxySelector choices until one connection succeeds. List<Proxy> proxiesOrNull = ...
csn
// Put writes data associated with a key to the database.
func (db *DB) Put(opts *WriteOptions, key, value []byte) error { var ( cErr *C.char cKey = byteToChar(key) cValue = byteToChar(value) ) C.rocksdb_put(db.c, opts.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)), &cErr) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return errors.New(C.GoS...
csn
Create random connections for all agents in the environment. :param int n: the number of connections for each agent Existing agent connections that would be created by chance are not doubled in the agent's :attr:`connections`, but count towards connections created.
def create_random_connections(self, n=5): '''Create random connections for all agents in the environment. :param int n: the number of connections for each agent Existing agent connections that would be created by chance are not doubled in the agent's :attr:`connections`, but count towa...
csn
Read strategy method. Validates the HMAC signature of the stored data. If the signatures match, then the data is safe and will be passed through as-is. If the stored data being read does not contain a `__signature` field, a `MissingSignatureException` is thrown. When catching this exception, you may choose to handle ...
public function read($data, array $options = []) { if ($data === null) { return $data; } $class = $options['class']; $currentData = $class::read(null, ['strategies' => false]); if (!isset($currentData['__signature'])) { throw new MissingSignatureException('HMAC signature not found.'); } if (Hash::...
csn
Delete change from a list. @param string $field @param string $condition @return Changes
public function deleteElementFromList( string $field, string $condition ): self { $this->changes[] = [ 'field' => $field, 'type' => self::TYPE_ARRAY_ELEMENT_DELETE, 'condition' => $condition, ]; return $this; }
csn
Update the IFrame with our new state. @method _updateIFrame @private @return {boolean} true if successful. false otherwise.
function _updateIFrame (fqstate) { var html, doc; html = '<html><body><div id="state">' + fqstate.replace(/&/g,'&amp;'). replace(/</g,'&lt;'). replace(/>/g,'&gt;'). replace(/"/g,'&quot;') + ...
csn
// LPersist removes the TTL of list.
func (db *DB) LPersist(key []byte) (int64, error) { if err := checkKeySize(key); err != nil { return 0, err } t := db.listBatch t.Lock() defer t.Unlock() n, err := db.rmExpire(t, ListType, key) if err != nil { return 0, err } err = t.Commit() return n, err }
csn
Create Marshaller from the JAXB context. @return Marshaller
public static Marshaller createMarshaller() throws JAXBException { Marshaller marshaller = MessageUtilsHelper.getContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); return marshaller; }
csn
Generate the temporal noise Generate the time course of the average brain voxel. To change the relative mixing of the noise components, change the sigma's specified below. Parameters ---------- stimfunction_tr : 1 Dimensional array This is the timecourse of the stimuli in this experime...
def _generate_noise_temporal(stimfunction_tr, tr_duration, dimensions, template, mask, noise_dict ): """Generate the temporal noise Genera...
csn
A convenience method to clone the QueryAtom instance while inserting a new binding. @param binding @return
public QueryAtom bind(QueryBinding binding) { List<QueryArgument> args = new ArrayList<QueryArgument>(); for(QueryArgument arg : this.args) { if(binding.isBound(arg)) { args.add(binding.get(arg)); } else { args.add(arg); } } return new QueryAtom(type, args); }
csn
will take care to save the long pressed index or to select all items in the range between the current long pressed item and the last long pressed item @param index the index of the long pressed item @param selectItem true, if the item at the index should be selected, false if this was already done outside of this help...
public boolean onLongClick(int index, boolean selectItem) { if (mLastLongPressIndex == null) { // we only consider long presses on not selected items if (mFastAdapter.getAdapterItem(index).isSelectable()) { mLastLongPressIndex = index; // we select this it...
csn
unlink user from authentication provider @param string $provider Facebook, Twiter, etc @param integer $userid optional @return void
public function socialUnlink($provider, $userid = null) { $this->debug->groupCollapsed(__METHOD__); if ($userid === null) { $userid = $this->userid; } $where = array( 'userid' => $userid, 'provider' => strtolower($provider), ); $this->db->rowMan('user_social', null, $where); $this->log('sociaUnl...
csn
A wrapper for inline validators from behaviors extending FormModelBehavior. Set the behavior name in 'behavior' param and validator name in 'validator' param. @todo port @param $attribute string @param $params array
public function behaviorValidator($attribute, $params) { $behavior = $params['behavior']; $validator = $params['validator']; unset($params['behavior']); unset($params['validator']); if (($behavior = $this->getBehavior($behavior)) !== null) { return $behavior->{$va...
csn
Scans the given directory for new, changed and deleted nodes. Sets the necessary localActions in the database. @param {string} dirPath - root directory to get delta for @param {Function} callback - callback function @returns {void} - no return value
function(dirPath, callback) { logger.info('getDelta start', {category: 'sync-local-delta'}); async.series([ (cb) => { logger.debug('findDeletedNodes start', {category: 'sync-local-delta'}); this.findDeletedNodes(cb) }, (cb) => { logger.debug('findChanges start', {cate...
csn
Add a foreign key column to the table. @param string $columnName A String with the column name. @param string $phpName A string representing the PHP name. @param string $type A string specifying the Propel type. @param string ...
public function addForeignKey($columnName, $phpName, $type, $fkTable, $fkColumn, $isNotNull = false, $size = 0, $defaultValue = null) { return $this->addColumn($columnName, $phpName, $type, $isNotNull, $size, $defaultValue, false, $fkTable, $fkColumn); }
csn
// connectDisksWithQuorum is same as connectDisks but waits // for quorum number of formatted disks to be online in // any given sets.
func (s *xlSets) connectDisksWithQuorum() { var onlineDisks int for onlineDisks < len(s.endpoints)/2 { for _, endpoint := range s.endpoints { if s.isConnected(endpoint) { continue } disk, format, err := connectEndpoint(endpoint) if err != nil { printEndpointError(endpoint, err) continue }...
csn
Directory that holds this file
def directory(self): """Directory that holds this file""" if self._directory is None: self._directory = self.api._load_directory(self.cid) return self._directory
csn
Retrieves Soap Actions from cache @param string $service @return array|null Soap Action array of strings, or NULL if action not cached
private function getCachedSoapActions( $service ) { $cache = $this->client->cache; $soapActions = $cache->get( $service . '_soap_actions' ); return $soapActions; }
csn
// XML is building xml.
func (su *sitemapURL) XML() []byte { doc := etree.NewDocument() url := doc.CreateElement("url") SetBuilderElementValue(url, su.data.URLJoinBy("loc", "host", "loc"), "loc") if _, ok := SetBuilderElementValue(url, su.data, "lastmod"); !ok { lastmod := url.CreateElement("lastmod") lastmod.SetText(time.Now().Forma...
csn
Check if entity is in a valid state for operations. @param object $entity @return bool
protected function isValidEntityState($entity) { $entityState = $this->uow->getEntityState($entity, UnitOfWork::STATE_NEW); if ($entityState === UnitOfWork::STATE_NEW) { return false; } // If Entity is scheduled for inclusion, it is not in this collection. // We...
csn
execute SCCI command This function calls SCCI server modules :param host: hostname or IP of iRMC :param userid: userid for iRMC with administrator privileges :param password: password for userid :param cmd: SCCI command :param port: port number of iRMC :param auth_method: irmc_username ...
def scci_cmd(host, userid, password, cmd, port=443, auth_method='basic', client_timeout=60, do_async=True, **kwargs): """execute SCCI command This function calls SCCI server modules :param host: hostname or IP of iRMC :param userid: userid for iRMC with administrator privileges :param ...
csn
Stores fixture HTML for resetting later
function storeFixture() { // Avoid overwriting user-defined values if (hasOwn.call(config, "fixture")) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { config.fixture = fixture.innerHTML; } }
csn
Dumps the given resource and all resources linked to it into a set of representation files in the given directory.
def to_files(self, resource, directory): """ Dumps the given resource and all resources linked to it into a set of representation files in the given directory. """ collections = self.__collect(resource) for (mb_cls, coll) in iteritems_(collections): fn = get_w...
csn
// processFeeUpdate processes a log update that updates the current commitment // fee.
func processFeeUpdate(feeUpdate *PaymentDescriptor, nextHeight uint64, remoteChain bool, mutateState bool, view *htlcView) { // Fee updates are applied for all commitments after they are // sent/received, so we consider them being added and removed at the // same height. var addHeight *uint64 var removeHeight *u...
csn
Calculates new TOI stats and emits them via statsd.
def emit_toi_stats(toi_set, peripherals): """ Calculates new TOI stats and emits them via statsd. """ count_by_zoom = defaultdict(int) total = 0 for coord_int in toi_set: coord = coord_unmarshall_int(coord_int) count_by_zoom[coord.zoom] += 1 total += 1 peripherals.s...
csn
Get the selector for type selection. @api private @example Get a type selection hash. criteria.type_selection @return [ Hash ] The type selection. @since 3.0.3
def type_selection klasses = klass._types if klasses.size > 1 { _type: { "$in" => klass._types }} else { _type: klass._types[0] } end end
csn
Compares two tracks based on their topology This method compares the given track against this instance. It only verifies if given track is close to this one, not the other way arround Args: track (:obj:`Track`) Returns: Two-tuple with global similarity b...
def similarity(self, track): """ Compares two tracks based on their topology This method compares the given track against this instance. It only verifies if given track is close to this one, not the other way arround Args: track (:obj:`Track`) Returns: ...
csn
Get the root path of the surf deployment declarations This defaults to ./.surf if a NULL path is given. @param string $path An absolute path (optional) @return string The configuration root path without a trailing slash. @throws \RuntimeException @throws InvalidConfigurationException
public function getDeploymentsBasePath($path = null) { $localDeploymentDescription = @realpath('./.surf'); if (! $path && is_dir($localDeploymentDescription)) { $path = $localDeploymentDescription; } $path = $path ?: Files::concatenatePaths([$this->getHomeDir(), 'deployme...
csn
Sets the S3 ACL grants for all objects in the Distribution to the appropriate value based on the type of Distribution. :type replace: bool :param replace: If False, the Origin Access Identity will be appended to the existing ACL for the object. If...
def set_permissions_all(self, replace=False): """ Sets the S3 ACL grants for all objects in the Distribution to the appropriate value based on the type of Distribution. :type replace: bool :param replace: If False, the Origin Access Identity will be appen...
csn
Read a notebook from a file
def read(file_or_stream, fmt, as_version=4, **kwargs): """Read a notebook from a file""" fmt = long_form_one_format(fmt) if fmt['extension'] == '.ipynb': notebook = nbformat.read(file_or_stream, as_version, **kwargs) rearrange_jupytext_metadata(notebook.metadata) return notebook ...
csn
Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict
def states(self, states): """ Overwrite the setter of the container state base class as special handling for the decider state is needed. :param states: the dictionary of new states :raises exceptions.TypeError: if the states parameter is not of type dict """ # First safely remo...
csn
Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty.
def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't empty. """ # Don't poll shards when there are pending records. if self.buffer: return # 0) Collect ...
csn
Get the package's name or the filename if nothing is found @param {*} file
function getPresetName(file) { const packageJson = findUp.sync("package.json", { cwd: path.dirname(file) }); if (packageJson) { return require(packageJson).name || file; } return file; }
csn
Get the values defined on this line. :param context_type: "ENV" or "LABEL" :return: values of given type defined on this line
def get_line_value(self, context_type): """ Get the values defined on this line. :param context_type: "ENV" or "LABEL" :return: values of given type defined on this line """ if context_type.upper() == "ENV": return self.line_envs elif context_type.upp...
csn
Converts GRAY color to RGBA.
function GRAY_TO_RGBA() { var s = this.s(); var a = this.a(); return kolor.rgba(s, s, s, a); }
csn
Get the highest nesting level nested inside this message
private function getTopNestingLevel() { $highestLevel = $this->getNestingLevel(); foreach ($this->getChildren() as $child) { $childLevel = $child->getNestingLevel(); if ($highestLevel < $childLevel) { $highestLevel = $childLevel; } } ...
csn
Setup before the Heat stack create or update has been done.
def _pre_heat_deploy(self): """Setup before the Heat stack create or update has been done.""" clients = self.app.client_manager compute_client = clients.compute self.log.debug("Checking hypervisor stats") if utils.check_hypervisor_stats(compute_client) is None: raise...
csn
Set current blend mode & opacity for filled objects. Valid blend modes are: Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDogde, ColorBurn, HardLight, SoftLight, Difference, Exclusion @param string $mode the blend mode to use @param float $opacity 0.0 fully transparent, 1.0 fully opaque
function setFillTransparency($mode, $opacity) { static $blend_modes = array("Normal", "Multiply", "Screen", "Overlay", "Darken", "Lighten", "ColorDogde", "ColorBurn", "HardLight", "SoftLight", "Difference", "Exclusion");...
csn