query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Layout fixes on startup.
function () { this._super.onenter (); this.element.action = "javascript:void(0)"; this._scrollbar ( gui.Client.scrollBarSize ); this._flexboxerize ( this.dom.q ( "label" ), this.dom.q ( "input" ) ); }
csn
Get a list of path transformers for a given address. @param address the path address @param placeholderResolver a placeholder resolver used to resolve children of a placeholder registration @return a list of path transformations
public List<PathAddressTransformer> getPathTransformations(final PathAddress address, PlaceholderResolver placeholderResolver) { final List<PathAddressTransformer> list = new ArrayList<PathAddressTransformer>(); final Iterator<PathElement> iterator = address.iterator(); resolvePathTransformers(i...
csn
gets the parity blocks corresponding to file returns the parity blocks in case of DFS and the part blocks containing parity blocks in case of HAR FS
private static BlockLocation[] getParityBlocks(final Path filePath, final long blockSize, final long numStripes, final RaidInfo raidInfo) throws IOException { FileSystem parityFS = raid...
csn
Removes duplicates and sources that already match an existing wild card. e.g. *.github.com asdf.github.com becomes *.github.com
def dedup_source_list(sources) sources = sources.uniq wild_sources = sources.select { |source| source =~ STAR_REGEXP } if wild_sources.any? sources.reject do |source| !wild_sources.include?(source) && wild_sources.any? { |pattern| File.fnmatch(pattern, source) } ...
csn
Creates an immutable copy of the specified set. @param set the set to copy from @return an immutable set copy
public static <T> Set<T> immutableSetCopy(Set<T> set) { if (set == null) return null; if (set.isEmpty()) return Collections.emptySet(); if (set.size() == 1) return Collections.singleton(set.iterator().next()); Set<? extends T> copy = ObjectDuplicator.duplicateSet(set); if (copy == null) ...
csn
Allows for deletion of non-empty directories - takes care of recursion appropriately. @param string $strPath Full path to the folder to be deleted @return int number of deleted files
public static function deleteFolder($strPath) { if (!is_dir($strPath)) { unlink($strPath); return 1; } $d = dir($strPath); $count = 0; while ($entry = $d->read()) { if ($entry != "." && $entry != "..") { if (is_dir($strPa...
csn
Get a bucket's location @param string $bucket Bucket name @return string | false
public static function getBucketLocation($bucket) { $rest = new S3Request('GET', $bucket, '', self::$endpoint); $rest->setParameter('location', null); $rest = $rest->getResponse(); if ($rest->error === false && $rest->code !== 200) $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP st...
csn
Returns a NodeList with attributes for the element. @method getAttribs @param {HTMLElement/string} elm Element node or string id to get attributes from. @return {NodeList} NodeList with attributes.
function (elm) { var attrs; elm = this.get(elm); if (!elm) { return []; } if (isIE) { attrs = []; // Object will throw exception in IE if (elm.nodeName == 'OBJECT') { return elm.attributes; } // IE doesn...
csn
Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fractions between 0 and 1. The weighted load represents a weighted average of processor and memory loads using the parameters `wproc` and `wmem` respectively.
def gpu_load(wproc=0.5, wmem=0.5): """Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fractions between 0 and 1. The weighted load represents a weighted average of processor and memory loads using the parameters `wproc` and `wmem` re...
csn
Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value.
def position(self): """ Returns the current position of the motor in pulses of the rotary encoder. When the motor rotates clockwise, the position will increase. Likewise, rotating counter-clockwise causes the position to decrease. Writing will set the position to that value. ...
csn
Helper method for determining how many single index entries there are in a particular multi-index
def _get_single_depth(self, multi_index): ''' Helper method for determining how many single index entries there are in a particular multi-index ''' single_depth = 0 for subind in multi_index: if is_slice_or_dim_range(subind): break ...
csn
Given the current state of a Loader instance, perform a batch load from its current queue.
def dispatch_queue(loader): # type: (DataLoader) -> None """ Given the current state of a Loader instance, perform a batch load from its current queue. """ # Take the current loader queue, replacing it with an empty queue. queue = loader._queue loader._queue = [] # If a maxBatchSize...
csn
initialize the ARC4 encryption @param string $key
function ARC4_init($key = '') { $this->arc4 = ''; // setup the control array if (mb_strlen($key, '8bit') == 0) { return; } $k = ''; while (mb_strlen($k, '8bit') < 256) { $k .= $key; } $k = substr($k, 0, 256); for ($i ...
csn
Performs teardown tasks
final protected function doCommandImportTearDown() { $this->writeln('Executing <info>teardown</info> tasks', false, true); $this->indent(); $this->subscriberPass(); $this->outdent(); $this->writeln('Teardown tasks complete.', false, true); }
csn
Similar to the case-when in SQL. Refer to the example below :param expr: :param args: :param kw: :return: sequence or scalar :Example: >>> # if df.id == 3 then df.name >>> # elif df.id == df.fid.abs() then df.name + 'test' >>> # default: 'test' >>> df.id.switch(3, df.name, df.fid....
def _switch(expr, *args, **kw): """ Similar to the case-when in SQL. Refer to the example below :param expr: :param args: :param kw: :return: sequence or scalar :Example: >>> # if df.id == 3 then df.name >>> # elif df.id == df.fid.abs() then df.name + 'test' >>> # default: 'te...
csn
Transforms an URI into "a canonical form" used in the triplestore to denote triples subject. @param string $uri URI to transform @return string
public function standardizeUri(string $uri): string { if ($uri == '') { throw new BadMethodCallException('URI is empty'); } if (substr($uri, 0, 1) === '/') { $uri = substr($uri, 1); } $uri = preg_replace('|^https?://[^/]+/rest/(tx:[-0-9a-zA-Z]+/)?|', '', $...
csn
Works out how the ContextMenu shall be placed Sets the placement property of the popover Places a "fakeDiv" in the DOM which the popover can be opened by @param {sap.m.Control} oSource the overlay @param {boolean} bContextMenu whether the ContextMenu should be opened as a context menu @return {div} the "fakeDiv" @priva...
function (oSource, bContextMenu) { this.getPopover().setShowArrow(true); var sOverlayId = (oSource.getId && oSource.getId()) || oSource.getAttribute("overlay"); var sFakeDivId = "contextMenuFakeDiv"; // get Dimensions of Overlay and Viewport var oOverlayDimensions = this._getOverlayDimensions(sOverlayId...
csn
Return Day of Month in the 1 to 30 range @param bool $asInt @return int|float
public function getDate($asInt = true) { $result = fmod($this->getRyzomDay(), self::RYZOM_MONTH_IN_DAY) + 1; return $asInt ? (int) $result : $result; }
csn
Skip edit log operations up to a given transaction ID, or until the end of the edit log is reached. After this function returns, the next call to readOp will return either end-of-file (null) or a transaction with a txid equal to or higher than the one we asked for. @param txid The transaction ID to read up until. ...
public boolean skipUntil(long txid) throws IOException { while (true) { FSEditLogOp op = readOp(); if (op == null) { return false; } if (op.getTransactionId() >= txid) { cachedOp = op; return true; } } }
csn
Requests the waveform preview for a specific track ID, given a connection to a player that has already been set up. @param rekordboxId the track whose waveform preview is desired @param slot identifies the media slot we are querying @param client the dbserver client that is communicating with the appropriate player @...
WaveformPreview getWaveformPreview(int rekordboxId, SlotReference slot, Client client) throws IOException { final NumberField idField = new NumberField(rekordboxId); // First try to get the NXS2-style color waveform if we are supposed to. if (preferColor.get()) { try { ...
csn
Set the object Assets Loader instance and dispatch required template envionement @param \Assets\Loader $loader @return self
public function guessFromAssetsLoader(AssetsLoader $loader) { $this->setAssetsLoader($loader); $this ->setLayoutsDir($this->assets_loader->getAssetsRealPath()) ->setToTemplate('setWebRootPath', $this->assets_loader->getAssetsWebPath()) ->setToView('addDefaultViewP...
csn
Returns the location type from a location URI.
public static LocationType getLocationType(URI location) { String scheme = location.getScheme(); if (EMODB_SCHEME.equals(scheme)) { // If the host matches the locator pattern then assume host discovery, otherwise it's a // direct URL to an EmoDB server if (LOCATOR_PAT...
csn
This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example, "pretty=true&size=10"
def db(self, entity, query_filters="size=10"): """ This function allows an entity to access the historic data. Args: entity (string): Name of the device to listen to query_filters (string): Elastic search response format string example,...
csn
Check if the path matches at least one of the provided patterns.
def check_path_matches_patterns(path, patterns): ''' Check if the path matches at least one of the provided patterns. ''' path = os.path.abspath(path) for patt in patterns: if isinstance(patt, six.string_types): if path == patt: return True elif patt.search(path):...
csn
Convert a standard element to one of our bespoke elements. @param mixed $element The element to convert @param RemoteWebDriver $driver The driver that contains this element @return mixed
public static function convertElement($element, RemoteWebDriver $driver) { if ($element instanceof RemoteWebElement) { return new self($element, $driver); } return $element; }
csn
Return an axes dictionary for the passed axes.
def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes.""" d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)} d.update(kwargs) return d
csn
This must throw a PhassetsInternalException if the current configuration doesn't allow this deployer to deploy processed assets. @throws PhassetsInternalException If at this time Phassets can't use this deployer to deploy and serve deployed assets
public function isSupported() { $this->destinationPath = $this->configurator->getConfig('filesystem_deployer', 'destination_path'); $this->baseUrl = $this->configurator->getConfig('filesystem_deployer', 'base_url'); $this->trigger = $this->configurator->getConfig('filesystem_deployer', 'chan...
csn
Clean extra code @param DOMDocument $doc @param $container @return string
private static function getCleanedHTML(DOMDocument $doc, $container) { while ($doc->firstChild) { $doc->removeChild($doc->firstChild); } while ($container->firstChild ) { $doc->appendChild($container->firstChild); } $html = trim($doc->saveHTML()); ...
csn
Returns a promise that resolves when the page is ready @param funcToExecute - The function to execute when the page is loaded
function whenReady(funcToExecute) { if (isReady()) { logger.info('Page is already loaded, instantly executing!'); funcToExecute(); return; } logger.info('Waiting for page to be ready'); callbacksOnReady.push(funcToExecute); }
csn
osk string changed
function(packet) { packet._index = 8; packet.preEditIndex = packet.readInt(); packet.preEditLength = packet.readInt(); // TODO: see above about how how we're skipping // 16 bytes here for some reason and how hacky // this is if (packet.buf.length > 36) { ...
csn
Add a configuration object. :param name: Name for later retrieval :param cfg: Configuration object :param expand: Flag for adding sub-configs for each sub-collection. See discussion in method doc. :return: self, for chaining :raises: CreateQueryEngineError...
def add(self, name, cfg, expand=False): """Add a configuration object. :param name: Name for later retrieval :param cfg: Configuration object :param expand: Flag for adding sub-configs for each sub-collection. See discussion in method doc. :return: self, f...
csn
Updates the commerce tax fixed rate address rel in the database or adds it if it does not yet exist. Also notifies the appropriate model listeners. @param commerceTaxFixedRateAddressRel the commerce tax fixed rate address rel @return the commerce tax fixed rate address rel that was updated
@Indexable(type = IndexableType.REINDEX) @Override public CommerceTaxFixedRateAddressRel updateCommerceTaxFixedRateAddressRel( CommerceTaxFixedRateAddressRel commerceTaxFixedRateAddressRel) { return commerceTaxFixedRateAddressRelPersistence.update(commerceTaxFixedRateAddressRel); }
csn
Runs given spider inside the twisted reactdor. Parameters ---------- spider_cls : scrapy.Spider Spider to run. capture_items : bool (default: True) If enabled, the scraped items are captured and returned. return_crawler : bool (default: False) If enabled, the crawler instanc...
def _run_spider_in_reactor(spider_cls, capture_items=True, return_crawler=False, settings=None, **kwargs): """Runs given spider inside the twisted reactdor. Parameters ---------- spider_cls : scrapy.Spider Spider to run. capture_items : bool (default: True) ...
csn
Utility function to add dictionary items to a log message.
def add_items_to_message(msg, log_dict): """Utility function to add dictionary items to a log message.""" out = msg for key, value in log_dict.items(): out += " {}={}".format(key, value) return out
csn
Returns all tags and their values the specified class is tagged with @param string $className Name of the class @return array An array of tags and their values or an empty array if no tags were found
public function getClassTagsValues($className) { if (!isset($this->reflectedClassNames[$className])) { $this->reflectClass($className); } if (!isset($this->classTagsValues[$className])) { return []; } return isset($this->classTagsValues[$className]) ? ...
csn
// setOpts validates the specified options against the selected backend and // then modifies the configuration
func setOpts(opts map[string]string, supportedOpts backendOptions) error { errors := 0 for key, val := range opts { opt, ok := supportedOpts[key] if !ok { errors++ log.WithField(logfields.Key, key).Error("unknown kvstore configuration key") continue } if opt.validate != nil { if err := opt.valid...
csn
Parse valid marker segment, segment description is unknown. Parameters ---------- fptr : file object The file to parse. Returns ------- Segment The current segment.
def _parse_reserved_segment(self, fptr): """Parse valid marker segment, segment description is unknown. Parameters ---------- fptr : file object The file to parse. Returns ------- Segment The current segment. """ offset = ...
csn
// ExecuteFetchAsApp will execute the given query.
func (agent *ActionAgent) ExecuteFetchAsApp(ctx context.Context, query []byte, maxrows int) (*querypb.QueryResult, error) { // get a connection conn, err := agent.MysqlDaemon.GetAppConnection(ctx) if err != nil { return nil, err } defer conn.Recycle() result, err := conn.ExecuteFetch(string(query), maxrows, tru...
csn
Gets event by its index as String @param index index @return TimelineEvent found event or null
public TimelineEvent getEvent(String index) { return getEvent(index != null ? Integer.valueOf(index) : -1); }
csn
Retrieve session ticket via client id. @param webContext the web context @param clientId the client id @return the transient session ticket
protected TransientSessionTicket retrieveSessionTicketViaClientId(final WebContext webContext, final String clientId) { val ticket = this.ticketRegistry.getTicket(clientId, TransientSessionTicket.class); if (ticket == null) { LOGGER.error("Delegated client identifier cannot be located in the...
csn
Add a row to the data set. @param columnValues Column values forming a row. @return The data set instance (for chained calls). @throws InvalidOperationException if this data set is read-only. @see #rows(Object[][]) @see #add(DataSet) @see #isReadOnly()
@SafeVarargs public final DataSet row(Object... columnValues) { checkIfNotReadOnly(); if (columnValues.length != source.getColumnCount()) { throw new InvalidOperationException(source.getColumnCount() + " columns expected, not " + columnValues.length + "."); } addRow(new Row(columnValue...
csn
Creates the my.cnf file for @param array $db_info @param unknown $path @return string
private function createMyCnf(array $db_info, $path) { $this->db_info = $db_info; $data = array( 'head' => '[client]', 'user' => 'user = ' . $this->db_info['user'], 'password' => 'password = ' . $this->db_info['password'], 'host' => 'host = ' . $this->d...
csn
Execute mysql query @param {object} connectionInfo Object containing information about the connection @param {string} query The query to execute @param {Array} params Params to use in the query @returns {mixed} Void
function (connectionInfo, query, params) { var connection; // Connection validation if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) { return respond({ success: false, data: { err: 'Bad hostname provided.', quer...
csn
Sets the maximum allowed number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle. @param maximumPoolSize the new maximum @throws IllegalArgumentException if the new maximum is less than...
public void setMaximumPoolSize(int maximumPoolSize) { if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize) throw new IllegalArgumentException(); this.maximumPoolSize = maximumPoolSize; if (workerCountOf(ctl.get()) > maximumPoolSize) interruptIdleWorkers(); }
csn
Validates a plugin. @param PluginBundleInterface $plugin @return ValidationError[]
public function validate(PluginBundleInterface $plugin) { $validationErrors = []; foreach ($this->checkers as $checker) { if (null !== $errors = $checker->check($plugin, $this->isInUpdateMode())) { $validationErrors = array_merge($validationErrors, $errors); ...
csn
Toggle a class on or off. @param {Float} progress: Current progress data of the scene, between 0 and 1. @this {Object} @return {void}
function toggle(progress) { var opts = this.options; var element = this.element; var times = Object.keys(opts); times.forEach(function(time) { var css = opts[time]; if (progress > time) { element.classList.add(css); } else { element.classList.remove(css); } }); }
csn
Convert log-power-spectrum to MFCC using the orthogonal DCT-II
def dct(input, K=13): """Convert log-power-spectrum to MFCC using the orthogonal DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep) return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N)
csn
// SetHandshakeData sets the handshake data received by the client.
func (s *Session) SetHandshakeData(data *HandshakeData) { s.Lock() defer s.Unlock() s.handshakeData = data }
csn
Writes the package parts to a zip archive. @param [Zip::OutputStream] zip @return [Zip::OutputStream]
def write_parts(zip) p = parts p.each do |part| unless part[:doc].nil? zip.put_next_entry(zip_entry_for_part(part)) part[:doc].to_xml_string(zip) end unless part[:path].nil? zip.put_next_entry(zip_entry_for_part(part)) zip.write IO.read(part[:p...
csn
Rotate the log file and make sure the configured number of files is kept. @return void
protected function rotateLogFile() { if (file_exists($this->logFileUrl . '.lock')) { return; } else { touch($this->logFileUrl . '.lock'); } if ($this->logFilesToKeep === 0) { unlink($this->logFileUrl); } else { for ($logFileCou...
csn
Ensure that we're going to compute at least N extra rows of `term`.
def _ensure_extra_rows(self, term, N): """ Ensure that we're going to compute at least N extra rows of `term`. """ attrs = self.graph.node[term] attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
csn
Create dictionary from list with key in lower case and value with default
def case_sensitive(self, lst): """Create dictionary from list with key in lower case and value with default """ dictionary = {} for pkg in lst: dictionary[pkg.lower()] = pkg return dictionary
csn
Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table.
def build_attr_string(attrs, supported=True): '''Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table. ''' if not supported: return '' if type(attrs) == str: attrs = [attrs] result =...
csn
Append new row to table widget. :param table: The table that shall have the row added to it. :type table: QTableWidget :param label: Label for the row. :type label: str :param data: custom data associated with label value. :type data: str
def append_row(table, label, data): """Append new row to table widget. :param table: The table that shall have the row added to it. :type table: QTableWidget :param label: Label for the row. :type label: str :param data: custom data associated with label value. :type data: str """ ...
csn
// StopDeliverForChannel stops blocks delivery for channel by stopping channel block provider
func (d *deliverServiceImpl) StopDeliverForChannel(chainID string) error { d.lock.Lock() defer d.lock.Unlock() if d.stopping { errMsg := fmt.Sprintf("Delivery service is stopping, cannot stop delivery for channel %s", chainID) logger.Errorf(errMsg) return errors.New(errMsg) } if client, exist := d.blockProvi...
csn
Return the start of a message boundary. @param string $boundary @param string $charSet @param string $contentType @param string $encoding @return string
protected function getBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if ('' == $charSet) { $charSet = $this->CharSet; } if ('' == $contentType) { $contentType = $this->ContentType; } if ('' == $encoding) { $e...
csn
Convert the passed source value to the destination class using the best match type converter provider, if a conversion is necessary. @param <DSTTYPE> The destination type. @param aSrcValue The source value. May be <code>null</code>. @param aDstClass The destination class to use. @return <code>null</code> if the source...
@Nullable public static <DSTTYPE> DSTTYPE convert (@Nullable final Object aSrcValue, @Nonnull final Class <DSTTYPE> aDstClass) { return convert (TypeConverterProviderBestMatch.getInstance (), aSrcValue, aDstClass); }
csn
Pass through to provider CommentBookSession.use_comparative_book_view
def use_comparative_book_view(self): """Pass through to provider CommentBookSession.use_comparative_book_view""" self._book_view = COMPARATIVE # self._get_provider_session('comment_book_session') # To make sure the session is tracked for session in self._get_provider_sessions(): ...
csn
renders the template html for the modal. @return bool|string|Response @throws \Sonata\AdminBundle\Exception\NoValueException
public function placementAction() { /** @var \Networking\InitCmsBundle\Entity\MenuItem $rootNode */ $rootNode = $this->admin->getObject($this->get('session')->get('root_menu_id')); if (!$rootNode) { throw new NotFoundHttpException(); } if ($rootNode->getChildren...
csn
Handle PUT requests @param EventInterface $event The current event
public function put(EventInterface $event) { $request = $event->getRequest(); $metadata = json_decode($request->getContent(), true); $event->getManager() ->trigger('db.metadata.delete') ->trigger('db.metadata.update', [ 'metadata' => $metadata, ...
csn
Pass through to provider LogLookupSession.get_logs
def get_logs(self): """Pass through to provider LogLookupSession.get_logs""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('log_lookup_session').get_logs() cat_list = [] for cat in catalo...
csn
Generates a v alid JID based on the room name. :param append_date: appends the given date to the JID
def generate_jid(name, append_date=None): """Generates a v alid JID based on the room name. :param append_date: appends the given date to the JID """ if not append_date: return sanitize_jid(name) return '{}-{}'.format(sanitize_jid(name), append_date.strftime('%Y-%m-%d'))
csn
Adds certificates to an existing keystore or creates a new one if necesssary. :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param certificate: The PEM public certificate to add to keystore....
def add(name, keystore, passphrase, certificate, private_key=None): ''' Adds certificates to an existing keystore or creates a new one if necesssary. :param name: alias for the certificate :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the...
csn
Returns an array of orders for the user @return array
protected function getListOrderAccount() { $conditions = $this->query_filter; $conditions['order'] = 'desc'; $conditions['sort'] = 'created'; $conditions['limit'] = $this->data_limit; $conditions['user_id'] = $this->data_user['user_id']; $list = (array) $this->order-...
csn
// emit the metrics
func (pipeline *Pipeline) emitMetrics() { pipeline.apply(func(node *Node) { pipeline.source.pipe.Event <- events.NewMetricsEvent(time.Now().UnixNano(), node.path, node.pipe.MessageCount) }) }
csn
Configure whether rollover is enabled for streaming or storage streams. Normally a SensorLog is used in ring-buffer mode which means that old readings are automatically overwritten as needed when new data is saved. However, you can configure it into fill-stop mode by using: set_rollove...
def set_rollover(self, area, enabled): """Configure whether rollover is enabled for streaming or storage streams. Normally a SensorLog is used in ring-buffer mode which means that old readings are automatically overwritten as needed when new data is saved. However, you can configure it...
csn
// GetRepositoryMetadata returns the metadata for all the images in the // named image repository.
func (r ImageRepos) GetRepositoryMetadata(repo image.Name) image.RepositoryMetadata { if metadata, ok := r.imageRepos[repo.CanonicalName()]; ok { // copy tags tagsCopy := make([]string, len(metadata.Tags)) copy(tagsCopy, metadata.Tags) // copy images imagesCopy := make(map[string]image.Info, len(metadata.Ima...
csn
// getDefaultIngressRules will create the default ingressRules given an api port
func (f Firewall) getDefaultIngressRules(apiPort int) []network.IngressRule { return []network.IngressRule{ { PortRange: corenetwork.PortRange{ FromPort: 22, ToPort: 22, Protocol: "tcp", }, SourceCIDRs: []string{ "0.0.0.0/0", }, }, { PortRange: corenetwork.PortRange{ FromPort...
csn
Try to fix invalid email addresses
public static function fix_email($email) { $parts = rcube_utils::explode_quoted_string('@', $email); foreach ($parts as $idx => $part) { // remove redundant quoting (#1490040) if ($part[0] == '"' && preg_match('/^"([a-zA-Z0-9._+=-]+)"$/', $part, $m)) { $parts[...
csn
Consumes a list of rules and returns them. 5.4.1. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-rules
def consume_rules(flags = {}) rules = [] while token = @tokens.consume case token[:node] # Non-standard. Spec says to discard comments and whitespace, but we # keep them so we can serialize faithfully. when :comment, :whitespace rules << token when :cd...
csn
Triggers a network request to reload the bucket's details. Example: ``` $bucket->reload(); $info = $bucket->info(); echo $info['location']; ``` @see https://cloud.google.com/storage/docs/json_api/v1/buckets/get Buckets get API documentation. @param array $options [optional] { Configuration options. @type string $if...
public function reload(array $options = []) { return $this->info = $this->connection->getBucket($options + $this->identity); }
csn
Get the socket @return resource @throws \Exception
protected function _getSocket() { if (is_resource($this->_socket)) { if (feof($this->_socket)) { // Supervisor sometimes seems to close the socket after a request is completed, which // causes the following request made by SupervisorClient to fail mysteriously wit...
csn
// Offset works exactly like Query.Offset. See the documentation for // Query.Offset for more information.
func (q *TransactionQuery) Offset(amount uint) *TransactionQuery { q.query.Offset(amount) return q }
csn
Get arg or args @param null $pos @return array
public function getArg($pos = null) { if ($pos === null) { return $this->args; } return isset($this->args[$pos]) ? $this->args[$pos] : $this->args; }
csn
Initialize new connection from the socket. @param buf the initial buffer @param offset the initial buffer offset @param length the initial buffer length @return int as if by read
@Override public int acceptInitialRead(byte []buffer, int offset, int length) { synchronized (_readLock) { // initialize fields from the _fd int result = nativeAcceptInit(_socketFd, _localAddrBuffer, _remoteAddrBuffer, buffer, offset, length); return result...
csn
// AddHook adds a hook to the standard logger hooks.
func (logger *Logger) AddHook(hook lg.Hook) { mux := &sync.Mutex{} unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd)) old := logger.std mux.Lock() stdVal.Hooks.Add(hook) mux.Unlock() atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsa...
csn
General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml
def _make_attr_element_from_typeattr(parent, type_attr_i): """ General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml """ attr = _make_attr_element(parent, type_attr_i.attr) if type_attr_i.unit...
csn
Convert a string to utf-8. @param string $content The content to convert @param string $charset The original charset @return string
public static function toUtf8($content, $charset) { $charset = strtoupper($charset); if (empty($charset) || $charset === 'UTF-8') { return $content; } $encodings = array_map('strtoupper', mb_list_encodings()); if (in_array($charset, $encodings, true)) { ...
csn
setter for token - sets @generated @param v value to set into the feature
public void setToken(Token v) { if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_token == null) jcasType.jcas.throwFeatMissing("token", "de.unihd.dbs.uima.types.heideltime.Event"); jcasType.ll_cas.ll_setRefValue(addr, ((Event_Type)jcasType).casFeatCode_token, jcasType.ll_cas.ll_getFSRef(v));}
csn
Defer a frequent call to the microtask queue.
function debounce (fn) { let calling = null let latestArgs = null return (...args) => { latestArgs = args if (!calling) { calling = Promise.resolve().then(() => { calling = null // At this point `args` may be different from the most // recent state, if multiple calls happened...
csn
fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called.
def fetch(*args, **kwargs): """fetch an URL. :func:`~urlfetch.fetch` is a wrapper of :func:`~urlfetch.request`. It calls :func:`~urlfetch.get` by default. If one of parameter ``data`` or parameter ``files`` is supplied, :func:`~urlfetch.post` is called. """ data = kwargs.get('data', None) f...
csn
// SetDiskStatus sets the DiskStatus field's value.
func (s *Disk) SetDiskStatus(v string) *Disk { s.DiskStatus = &v return s }
csn
Read a resource set. https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set :param str token: client access token :param str id: Identifier of the resource set :rtype: dict
def resource_set_read(self, token, id): """ Read a resource set. https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set :param str token: client access token :param str id: Identifier of the resource set :rtype: dict """ ...
csn
// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. // It returns the raw data contained in an Excel XLSX file as three // dimensional slice. Merged cells will be unmerged. Covered cells become the // values of theirs origins.
func FileToSliceUnmerged(path string) ([][][]string, error) { f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
csn
Gets the value of the genericApplicationPropertyOfRoad property. <p> This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the genericApplicationP...
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfRoad() { if (_GenericApplicationPropertyOfRoad == null) { _GenericApplicationPropertyOfRoad = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationPropertyOfRoad; }
csn
Get the file path for a specific loaded resource. @param {String} name The resource name. @type String @example alert( <b>CKEDITOR.plugins.getFilePath( 'sample' )</b> ); // "&lt;editor path&gt;/plugins/sample/plugin.js"
function( name ) { var external = this.externals[ name ]; return CKEDITOR.getUrl( this.getPath( name ) + ( ( external && ( typeof external.file == 'string' ) ) ? external.file : this.fileName + '.js' ) ); }
csn
Helper method. Generic login with username and password.
def login_generic(request, username, password): """Helper method. Generic login with username and password.""" user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return True return False
csn
r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is... ========\\\\' >>> bar('...MacGyver', p...
def bar(msg='', width=40, position=None): r""" Returns a string with text centered in a bar caption. Examples: >>> bar('test', width=10) '== test ==' >>> bar(width=10) '==========' >>> bar('Richard Dean Anderson is...', position='top', width=50) '//========= Richard Dean Anderson is...
csn
Data universe available at the current time. Universe contains the data passed in when creating a Backtest. Use this data to determine strategy logic.
def universe(self): """ Data universe available at the current time. Universe contains the data passed in when creating a Backtest. Use this data to determine strategy logic. """ # avoid windowing every time # if calling and on same date return # cached va...
csn
If two records or record IDs have the same rank, sort them by ID. This prevents a different order being returned by different Rubies.
def sort(ranked_records) ranked_records.sort { |a, b| a_score = a.last a_id = a.first.is_a?(Fixnum) ? a.first : a.first.id b_score = b.last b_id = b.first.is_a?(Fixnum) ? b.first : b.first.id if a_score == b_score a_id <=> b_id else b_score <=>...
csn
Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the pixels color value...
def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]: """Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, in...
csn
// DeleteHost handles a request to delete an existing host.
func (*Service) DeleteHost(c context.Context, req *crimson.DeleteHostRequest) (*empty.Empty, error) { if err := deleteHost(c, req.Name); err != nil { return nil, err } return &empty.Empty{}, nil }
csn
Register the assets before we eventually enqueue them
public function registerAssets() { $data = $this->getData(); // Read the assets manifest file if it exists $manifest = $this->loadManifest(); if (isset($data['styles'])) { foreach ($data['styles'] as $handle => $props) { $this->handle...
csn
Add artifact with given framing to the environment. :param object artifact: Artifact to be added.
def add_artifact(self, artifact): '''Add artifact with given framing to the environment. :param object artifact: Artifact to be added. ''' artifact.env_time = self.age self.artifacts.append(artifact) self._log(logging.DEBUG, "ARTIFACTS appended: '{}', length={}" ...
csn
// DualStack selects the first IPv4 address // and IPv6 address in ips.
func DualStack(ips []net.IP) []net.IP { if len(ips) <= 1 { return ips } var ( ipv4, ipv6 bool a []net.IP ) for _, ip := range ips { if ipLen := len(ip); !ipv4 && ipLen == net.IPv4len { a = append(a, ip) ipv4 = true } else if !ipv6 && ipLen == net.IPv6len { a = append(a, ip) ipv6 = tr...
csn
Factory for Amount models with MICRO amounts and provided `divisibility`. @param integer $amount @param integer $divisibility @return \NEM\Models\Amount
static public function fromMicro($amount, $divisibility = 6) { $amt = new Amount(["amount" => $amount]); $amt->setDivisibility($divisibility); return $amt; }
csn
Creates a default SConstruct file
def create_sconstruct(self, project_dir='', sayyes=False): """Creates a default SConstruct file""" project_dir = util.check_dir(project_dir) sconstruct_name = 'SConstruct' sconstruct_path = util.safe_join(project_dir, sconstruct_name) local_sconstruct_path = util.safe_join( ...
csn
Returns the executor in use by this query.
protected QueryExecutor<S> executor() throws RepositoryException { QueryExecutor<S> executor = mExecutor; if (executor == null) { mExecutor = executor = executorFactory().executor(mFilter, mOrdering, null); } return executor; }
csn
submit to members
@Override public <T> Future<T> submitToMember(Callable<T> task, Member member) { final Address memberAddress = getMemberAddress(member); return submitToTargetInternal(task, memberAddress, null, false); }
csn
Send Velocity in the world frame of reference setpoint. vx, vy, vz are in m/s yawrate is in degrees/s
def send_velocity_world_setpoint(self, vx, vy, vz, yawrate): """ Send Velocity in the world frame of reference setpoint. vx, vy, vz are in m/s yawrate is in degrees/s """ pk = CRTPPacket() pk.port = CRTPPort.COMMANDER_GENERIC pk.data = struct.pack('<Bffff...
csn