query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
// Int64 returns the value associated with the key as a int64.
func (s *Session) Int64(key string) int64 { s.RLock() defer s.RUnlock() v, ok := s.data[key] if !ok { return 0 } value, ok := v.(int64) if !ok { return 0 } return value }
csn
Gets all tag instances of the Catalog. @param bool $force If true, then reloads the list from the storage. @return CNabuCatalogTagList Returns the list of tag instances.
public function getTags(bool $force = false) { if ($this->nb_catalog_tag_list->isEmpty() || $force) { $this->nb_catalog_tag_list->clear(); $this->nb_catalog_tag_list->merge( CNabuCatalogTag::getAllCatalogTags($this) ); } return $this->nb_c...
csn
Use this method to set the data for this blob
def set_data(self, data): "Use this method to set the data for this blob" if data is None: self.data_size = 0 self.data = None return self.data_size = len(data) # create a string buffer so that null bytes aren't interpreted # as the end of the string self.data = ctypes.cast(ctypes.create_string_bu...
csn
// ipcListen will create a Unix socket on the given endpoint.
func ipcListen(endpoint string) (net.Listener, error) { if len(endpoint) > int(C.max_socket_path_size()) { log.Warn(fmt.Sprintf("The ipc endpoint is longer than %d characters. ", C.max_socket_path_size()), "endpoint", endpoint) } // Ensure the IPC path exists and remove any previous leftover if err := os.Mkdi...
csn
Creates a time-based instance If node, clock sequence, or timestamp values are not passed in, they will be generated. Generating the node and clock sequence are not recommended for this UUID version. The current timestamp can be retrieved in the correct format from the `Uuid::timestamp()` static method. @link http:/...
public static function time(?string $node = null, ?int $clockSeq = null, ?string $timestamp = null): Uuid { return static::uuid1($node, $clockSeq, $timestamp); }
csn
Get metadata of device
def getMetadata(self, remote, address, key): """Get metadata of device""" if self._server is not None: # pylint: disable=E1121 return self._server.getAllMetadata(remote, address, key)
csn
Get the start and end IP addresses for an IP address range @param string $ipRange IP address range in presentation format @return array|false Array( low, high ) IP addresses in presentation format; or false if error
public function getIpsForRange($ipRange) { $range = IPUtils::getIPRangeBounds($ipRange); if ($range === null) { return false; } return array(IPUtils::binaryToStringIP($range[0]), IPUtils::binaryToStringIP($range[1])); }
csn
Deletes an integration account agreement. @param resource_group_name [String] The resource group name. @param integration_account_name [String] The integration account name. @param agreement_name [String] The integration account agreement name. @param custom_headers [Hash{String => String}] A hash of custom header...
def delete_with_http_info(resource_group_name, integration_account_name, agreement_name, custom_headers:nil) delete_async(resource_group_name, integration_account_name, agreement_name, custom_headers:custom_headers).value! end
csn
// Finalize writes sitemap and index files if it had some // specific condition in BuilderFile struct.
func (sm *Sitemap) Finalize() *Sitemap { sm.bldrs.Add(sm.bldr) sm.bldrs.Write() sm.bldr = nil return sm }
csn
Returns TRUE if an lifetime value for the passed key is available and the item has timed out. @param mixed $key The key of the item the lifetime check is requested @return boolean TRUE if the item has timed out, else FALSE
public function isTimedOut($key) { // if the item is available and has timed out, return TRUE if (array_key_exists($key, $this->lifetime) && $this->lifetime[$key] < time()) { return true; } // else return FALSE return false; }
csn
Return the length, starting position and value of consecutive identical values. Parameters ---------- arr : sequence Array of values to be parsed. Returns ------- (values, run lengths, start positions) values : np.array The values taken by arr over each run run lengths : np...
def rle_1d(arr): """Return the length, starting position and value of consecutive identical values. Parameters ---------- arr : sequence Array of values to be parsed. Returns ------- (values, run lengths, start positions) values : np.array The values taken by arr over each ...
csn
locate operation based on uri and httpMethod @param uri original uri of the request @param httpMethod http method of the request @return OpenApiOperation the wrapper of an api operation
private OpenApiOperation getOpenApiOperation(String uri, String httpMethod) throws URISyntaxException { String uriWithoutQuery = new URI(uri).getPath(); NormalisedPath requestPath = new ApiNormalisedPath(uriWithoutQuery); Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(...
csn
// Convert_core_LimitRange_To_v1_LimitRange is an autogenerated conversion function.
func Convert_core_LimitRange_To_v1_LimitRange(in *core.LimitRange, out *v1.LimitRange, s conversion.Scope) error { return autoConvert_core_LimitRange_To_v1_LimitRange(in, out, s) }
csn
Get expected part size for a particular part number.
def expected_part_size(self, part_number): """Get expected part size for a particular part number.""" last_part = self.multipart.last_part_number if part_number == last_part: return self.multipart.last_part_size elif part_number >= 0 and part_number < last_part: ...
csn
Strip quotes from a string
function stripQuotes (str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str }
csn
Get the current hierarchy level. @return the current hierarchy level @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. @see #decode
public String getCurrentHierPath() throws URIException { char[] path = getRawCurrentHierPath(); return (path == null) ? null : decode(path, getProtocolCharset()); }
csn
// SystemIdentityPath mocks base method
func (m *MockConfig) SystemIdentityPath() string { ret := m.ctrl.Call(m, "SystemIdentityPath") ret0, _ := ret[0].(string) return ret0 }
csn
Actually serialize and write the request.
def _write(self, request): """Actually serialize and write the request.""" with sw("serialize_request"): request_str = request.SerializeToString() with sw("write_request"): with catch_websocket_connection_errors(): self._sock.send(request_str)
csn
Gets the Section attribute of the IniFile object @param strSection section name to get @return The Section value @throws IOException
public Map getSection(String strSection) throws IOException { Object o = sections.get(strSection.toLowerCase()); if (o == null) throw new IOException("section with name " + strSection + " does not exist"); return (Map) o; }
csn
All attachments, as Attachment objects.
@InterfaceAudience.Public public List<Attachment> getAttachments() { Map<String, Object> attachmentMetadata = getAttachmentMetadata(); if (attachmentMetadata == null) { return new ArrayList<Attachment>(); } List<Attachment> result = new ArrayList<Attachment>(attachmentMet...
csn
Generate template file, same name. @param string $path @param array $arguments
public function templateFile($path, array $arguments = []) { $this->file($path)->template($this->makePath($path), $arguments); }
csn
Update farm attached to that vrack network id REST: POST /ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}/updateFarmId @param farmId [required] Farm Id you want to attach to that vrack network @param serviceName [required] The internal name of your IP load balancing @param vrackNetworkId [required] Intern...
public OvhVrackNetwork serviceName_vrack_network_vrackNetworkId_updateFarmId_POST(String serviceName, Long vrackNetworkId, Long[] farmId) throws IOException { String qPath = "/ipLoadbalancing/{serviceName}/vrack/network/{vrackNetworkId}/updateFarmId"; StringBuilder sb = path(qPath, serviceName, vrackNetworkId); H...
csn
Gets an array of RemoteHistoryContao objects which contain a foreign key that references this object. If the $criteria is not null, it is used to always fetch the results from the database. Otherwise the results are fetched from the database the first time, then cached. Next time the same method is called without $cri...
public function getRemoteHistoryContaos($criteria = null, PropelPDO $con = null) { $partial = $this->collRemoteHistoryContaosPartial && !$this->isNew(); if (null === $this->collRemoteHistoryContaos || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collRemoteHist...
csn
A tuple is abstracted as an ordered container of its values >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> module = ast.parse('def foo(a, b): return a, b') >>> result = pm.gather(Aliases, module) >>> Aliases.dump(result, filter=ast.Tuple) ...
def visit_Tuple(self, node): ''' A tuple is abstracted as an ordered container of its values >>> from pythran import passmanager >>> pm = passmanager.PassManager('demo') >>> module = ast.parse('def foo(a, b): return a, b') >>> result = pm.gather(Aliases, module) ...
csn
// SetCanonicalHostedZoneName sets the CanonicalHostedZoneName field's value.
func (s *LoadBalancerDescription) SetCanonicalHostedZoneName(v string) *LoadBalancerDescription { s.CanonicalHostedZoneName = &v return s }
csn
Construct a fully typed and quantified expression for representing a verification condition. Aside from flattening the various components, it must also determine appropriate variable types, including those for aliased variables. @param vc @param environment @return
public WyalFile.Stmt.Block buildVerificationCondition(WyilFile.Decl declaration, GlobalEnvironment environment, VerificationCondition vc) { WyalFile.Stmt antecedent = flatten(vc.antecedent); Expr consequent = vc.consequent; HashSet<WyalFile.VariableDeclaration> freeVariables = new HashSet<>(); freeVariables(...
csn
// String gets a zipfian random string from a set with the given cardinality.
func (g *Generator) String(length, cardinality int) string { if length > 32 { length = 32 } val := g.Uint64(cardinality) b := make([]byte, 8) binary.BigEndian.PutUint64(b, val) _, _ = g.hsh.Write(b) // no need to check err hashed := g.hsh.Sum(nil) g.hsh.Reset() return base32.StdEncoding.EncodeToString(hash...
csn
// SetLinuxParameters sets the LinuxParameters field's value.
func (s *ContainerDefinition) SetLinuxParameters(v *LinuxParameters) *ContainerDefinition { s.LinuxParameters = v return s }
csn
Create a new ThreatIntelSet. ThreatIntelSets consist of known malicious IP addresses. GuardDuty generates findings based on ThreatIntelSets. @param createThreatIntelSetRequest CreateThreatIntelSet request body. @return Result of the CreateThreatIntelSet operation returned by the service. @throws BadRequestException 40...
@Override public CreateThreatIntelSetResult createThreatIntelSet(CreateThreatIntelSetRequest request) { request = beforeClientExecution(request); return executeCreateThreatIntelSet(request); }
csn
Execute context. @param array ...$args @return mixed
final public function execute(...$args) { $className = get_class($this); if (!method_exists($this, 'process')) { throw new RuntimeException( sprintf( 'Context "%s" should have process method', $className ) ...
csn
Create a map of the empirical probability for each category. Args: col(pandas.DataFrame): Data to transform.
def _fit(self, col): """Create a map of the empirical probability for each category. Args: col(pandas.DataFrame): Data to transform. """ column = col[self.col_name].replace({np.nan: np.inf}) frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict...
csn
Build the INSERT ON DUPLICATE KEY sql statement. @param array $data @param array $updateColumns @return string
protected static function buildInsertOnDuplicateSql(array $data, array $updateColumns = null) { $first = static::getFirstRow($data); $sql = 'INSERT INTO `' . static::getTablePrefix() . static::getTableName() . '`(' . static::getColumnList($first) . ') VALUES' . PHP_EOL; $sql .= static::bu...
csn
Builds the cache directives from response headers. @param $response @return string[]
protected function buildCacheDirectives($response) { $cacheControlHeader = null; if ($response->hasHeader('cache-control')) { $cacheControlHeader = $this->parseHeader($response->getHeader('cache-control')); $cacheControlHeader = current($cacheControlHeader); $cach...
csn
Create credentials for an IBM Cloud Object Storage Account
def cli(env, identifier): """Create credentials for an IBM Cloud Object Storage Account""" mgr = SoftLayer.ObjectStorageManager(env.client) credential = mgr.create_credential(identifier) table = formatting.Table(['id', 'password', 'username', 'type_name']) table.sortby = 'id' table.add_row([ ...
csn
Entering broadcasting phase, leader broadcasts proposal to followers. @throws InterruptedException if it's interrupted. @throws TimeoutException in case of timeout. @throws IOException in case of IO failure. @throws ExecutionException in case of exception from executors.
void broadcasting() throws TimeoutException, InterruptedException, IOException, ExecutionException { // Initialization. broadcastingInit(); try { while (this.quorumMap.size() >= clusterConfig.getQuorumSize()) { MessageTuple tuple = filter.getMessage(config.getTimeoutMs()); ...
csn
// GenerateOutputImageLabels generate the labels based on the s2i Config // and source repository informations.
func GenerateOutputImageLabels(info *git.SourceInfo, config *api.Config) map[string]string { labels := map[string]string{} namespace := constants.DefaultNamespace if len(config.LabelNamespace) > 0 { namespace = config.LabelNamespace } labels = GenerateLabelsFromConfig(labels, config, namespace) labels = Genera...
csn
Get k-fold indices generator
def split_KFold_idx(train, cv_n_folds=5, stratified=False, random_state=None): """Get k-fold indices generator """ test_len(train) y = train[1] n_rows = y.shape[0] if stratified: if len(y.shape) > 1: if y.shape[1] > 1: raise ValueError("Can't use stratified K-...
csn
Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only)
def delete(self, directory_updated=False): # pylint: disable=W0212 """ Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only...
csn
Calculate the imei check byte.
def imeicsum(text): ''' Calculate the imei check byte. ''' digs = [] for i in range(14): v = int(text[i]) if i % 2: v *= 2 [digs.append(int(x)) for x in str(v)] chek = 0 valu = sum(digs) remd = valu % 10 if remd != 0: chek = 10 - remd ...
csn
Gets the instance of the element who owns the specified line and column.
def get_element(self, line, column): """Gets the instance of the element who owns the specified line and column.""" ichar = self.charindex(line, column) icontains = self.contains_index result = None if line < icontains: #We only need to search through the typ...
csn
set initial entries to field array @param array $fieldArray @param int $contentId @param bool $new
public function setFieldEntries(array &$fieldArray, $contentId = 0, $new = false) { $containerUpdateArray = []; if (isset($fieldArray['tx_gridelements_container'])) { if ((int)$fieldArray['tx_gridelements_container'] > 0 && $new) { $containerUpdateArray[(int)$fieldArray['...
csn
Validates the checksum of a file against a given checksum @param {object} params - json containing { filePath - path to the file, expectedChecksum - the checksum to validate against }
function validateChecksum(requester, params) { params = params || { filePath: installerPath, expectedChecksum: _updateParams.checksum }; var hash = crypto.createHash('sha256'), currentRequester = requester || ""; if (fs.existsSync(params.filePath)) {...
csn
Ensure that the in|exclude &quot;patterns&quot; have been properly divided up. @since Ant 1.6.3
private synchronized void ensureNonPatternSetsReady() { if (!areNonPatternSetsReady) { includePatterns = fillNonPatternSet(includeNonPatterns, includes); excludePatterns = fillNonPatternSet(excludeNonPatterns, excludes); areNonPatternSetsReady = true; } }
csn
Read and return a line of text. :rtype: str :return: the next line of text in the file, including the newline character
def readline(self): """ Read and return a line of text. :rtype: str :return: the next line of text in the file, including the newline character """ _complain_ifclosed(self.closed) line = self.f.readline() if self.__encoding: return l...
csn
// VolumeList returns a list of all volumes.
func (c *Client) VolumeList() ([]*ct.Volume, error) { var volumes []*ct.Volume return volumes, c.Get("/volumes", &volumes) }
csn
USB devices get the usb device information @return void
protected function _usb() { if (CommonFunctions::executeProgram('listusb', '', $bufr, PSI_DEBUG)) { $devices = preg_split("/\n/", $bufr); foreach ($devices as $device) { if (preg_match("/^\S+\s+\S+\s+\"(.*)\"\s+\"(.*)\"/", $device, $ar_buf)) { $dev...
csn
String representation of the Object's public URI A string representing the Object's public URI assuming that it's parent Container is CDN-enabled. Example: <code> # ... authentication/connection/container code excluded # ... see previous examples # Print out the Object's CDN URI (if it has one) in an HTML img-tag # ...
function public_uri() { if ($this->container->cdn_enabled) { return $this->container->cdn_uri . "/" . $this->name; } return NULL; }
csn
Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks.
def init_app(self, app): """ Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. """ # If no version path was provided in the init of the Dockerflow # class we'll use the parent direct...
csn
Sends a text message to all the registered bots. Used to simulate a user typing in chat with your bot. @param message the message to send.
public void sendTextMessage(String message) { MessageEnvelope envelope = new MessageEnvelope(); ReceivedMessage body = new ReceivedMessage(); body.setText(message); envelope.setMessage(body); envelope.setSender(new User(facebookMockId)); System.out.println("Sending message: [" + message + "] as user : [" ...
csn
Dismiss a notice. @since 160524 WP notices. @param string $key A key to dismiss.
public function dismiss(string $key) { $notices = $this->get(); if (!isset($notices[$key])) { return; // Nothing to do. } // No update necessary in this case. $notices[$key] = $this->normalize($notices[$key]); $notice = &$notices[$key]; // By reference. ...
csn
Parse XML to restore the 'AT' input. @param {!Element} xmlElement XML storage element. @this Blockly.Block
function(xmlElement) { // Note: Until January 2013 this block did not have mutations, // so 'statement' defaults to false and 'at' defaults to true. var isStatement = (xmlElement.getAttribute('statement') == 'true'); this.updateStatement_(isStatement); var isAt = (xmlElement.getAttribute('at') != 'f...
csn
Given a callable function, attempts to determine the reflection parameters. @param callable $callable @return \ReflectionParameter[]
private function getReflectionParameters(callable $callable) { $reflectionParams = []; if (is_array($callable)) { // Callable array $reflector = new \ReflectionMethod($callable[0], $callable[1]); $reflectionParams = $reflector->getParameters(); } else if ...
csn
Checks whether the current user is an admin of the given chat or not. @param $id_chat @return bool|null
public function is_admin($id_chat): ?bool { if ( $this->check() && ($chat = $this->info($id_chat)) && !$chat['blocked'] ){ return (bool)$this->db->count('bbn_chats_users', [ 'id_chat' => $id_chat, 'id_user' => $this->user->get_id(), 'admin' => 1 ]); } return null; }
csn
Create a new copy of version descriptor. @param version original version descriptor (optional). @return copied version descriptor (optional). @since v1.1.0
public static Version copy(Version version) { if (version == null) { return null; } Version result = new Version(); result.labels = new LinkedList<String>(version.labels); result.numbers = new LinkedList<Integer>(version.numbers); result.snapshot = version.sna...
csn
Sets the text value. @param entity the entity @param member the member @param retVal the ret val @return the object
private static Object setTextValue(Object entity, Field member, Object retVal) { if (member != null && member.getType().isEnum()) { EnumAccessor accessor = new EnumAccessor(); if (member != null) { retVal = accessor.fromString(member.getType(), (St...
csn
This text should appear on the screen @param text
@LogExecTime public void verifyTextPresent(String text, String msg) { jtCore.verifyTextPresent(text, msg); }
csn
Initialize steppy logger. This logger is used throughout the steppy library to report computation progress. Example: Simple use of steppy logger: .. code-block:: python initialize_logger() logger = get_logger() logger.info('My message inside p...
def initialize_logger(): """Initialize steppy logger. This logger is used throughout the steppy library to report computation progress. Example: Simple use of steppy logger: .. code-block:: python initialize_logger() logger = get_logger() ...
csn
// Open a new Redis connection
func (rc *RedisConnector) open(socketPath, host, password string, db int, cnf *config.RedisConfig, tlsConfig *tls.Config) (redis.Conn, error) { var opts = []redis.DialOption{ redis.DialDatabase(db), redis.DialReadTimeout(time.Duration(cnf.ReadTimeout) * time.Second), redis.DialWriteTimeout(time.Duration(cnf.Writ...
csn
Pretend django_cassandra_engine to be dummy database backend with no support for migrations.
def handle(self, *args, **options): """ Pretend django_cassandra_engine to be dummy database backend with no support for migrations. """ self._change_cassandra_engine_name('django.db.backends.dummy') try: super(Command, self).handle(*args, **options) f...
csn
Perform a bottom-up, non-recursive, in-place mergesort. Efficient for very-large objects, and written without recursion since PHP isn't well optimized for large recursion stacks. @param callable $cb The callback for comparison @return static
protected function mergeSort(callable $cb) { $count = count($this); $sfa = $this->sfa; $result = new SplFixedArray($count); for ($k = 1; $k < $count; $k = $k << 1) { for ($left = 0; ($left + $k) < $count; $left += $k << 1) { $right = $left + $k; ...
csn
Build the transfromation graph once.
def start_bundle(self, element=None): """Build the transfromation graph once.""" import tensorflow as tf from trainer import feature_transforms g = tf.Graph() session = tf.Session(graph=g) # Build the transformation graph with g.as_default(): transformed_features, _, placeholders = (...
csn
Apply the scope to a given ORM query builder. @param \Nova\Database\ORM\Builder $builder @return void
public function apply(Builder $builder) { $model = $builder->getModel(); $builder->whereNull($model->getQualifiedDeletedAtColumn()); $this->extend($builder); }
csn
Get the absolute image source of the image, if not available the method returns false. @return string|boolean Returns the path to the file, otherwise false. @see \luya\admin\base\Property::getValue()
public function getValue() { $value = parent::getValue(); if ($value) { $image = Yii::$app->storage->getImage($value); /* @var $image \luya\admin\image\Item */ if ($image) { if ($this->filterName()) { return $image->app...
csn
Given the type of the targeting partition parameter and an object, coerce the object to the correct type and hash it. NOTE NOTE NOTE NOTE! THIS SHOULD BE THE ONLY WAY THAT YOU FIGURE OUT THE PARTITIONING FOR A PARAMETER! ON SERVER @return The partition best set up to execute the procedure. @throws VoltTypeException
public static int getPartitionForParameter(VoltType partitionType, Object invocationParameter) { return instance.get().getSecond().getHashedPartitionForParameter(partitionType, invocationParameter); }
csn
Returns the number of isotopes defined by this class. @return The size value
public int getSize() { int count = 0; for (List<IIsotope> isotope : isotopes) if (isotope != null) count += isotope.size(); return count; }
csn
// AttachDisk mocks base method
func (m *MockCloud) AttachDisk(arg0, arg1 string) (interface{}, error) { ret := m.ctrl.Call(m, "AttachDisk", arg0, arg1) ret0, _ := ret[0].(interface{}) ret1, _ := ret[1].(error) return ret0, ret1 }
csn
Determines what the focal point of the downloaded image should be. Returns: focal_point: (x, y) The location of the source in the middle observation, in the coordinate system of the current source reading.
def calculate_focus(self, reading): """ Determines what the focal point of the downloaded image should be. Returns: focal_point: (x, y) The location of the source in the middle observation, in the coordinate system of the current source reading. """ ...
csn
Parse a Flask response into a body, a status code, and headers The returned value from a Flask view could be: * a tuple of (response, status) or (response, status, headers) * a Response object * a string
def parse_response(response): """ Parse a Flask response into a body, a status code, and headers The returned value from a Flask view could be: * a tuple of (response, status) or (response, status, headers) * a Response object * a string """ if isinstance(response, tuple): ...
csn
Returns the requested SAML attribute indexed by FriendlyName @param string $friendlyName The requested attribute of the user. @return array|null Requested SAML attribute ($friendlyName).
public function getAttributeWithFriendlyName($friendlyName) { assert('is_string($friendlyName)'); $value = null; if (isset($this->_attributesWithFriendlyName[$friendlyName])) { return $this->_attributesWithFriendlyName[$friendlyName]; } return $value; }
csn
Sanitize url dict as used in django-bootstrap3 settings.
def url_to_attrs_dict(url, url_attr): """ Sanitize url dict as used in django-bootstrap3 settings. """ result = dict() # If url is not a string, it should be a dict if isinstance(url, six.string_types): url_value = url else: try: url_value = url["url"] exc...
csn
Public API get, this will call the get function on the loaded endpoint, optionally add another id if specified @param id: id to load
public function get($id=NULL) { if (!$id) { if (!isset($this->id)) { $url = URIResource::Make($this->path); } else { $url = URIResource::Make($this->path, array($this->id)); } $data = new DataPacket($this->client->get($url)); } else { $url =...
csn
Applies action to all RouterStubs that are connected @param action
public void forEach(Consumer<RouterStub> action) { stubs.stream().filter(RouterStub::isConnected).forEach(action::accept); }
csn
Returns a compact representation of all of the subtasks of a task. @param task The task to get the subtasks of. @return Request object
public CollectionRequest<Task> subtasks(String task) { String path = String.format("/tasks/%s/subtasks", task); return new CollectionRequest<Task>(this, Task.class, path, "GET"); }
csn
Remove the specified handler. @param \core\message\inbound\handler $handler The handler to remove
public static function remove_messageinbound_handler($handler) { global $DB; // Delete Inbound Message datakeys. $DB->delete_records('messageinbound_datakeys', array('handler' => $handler->id)); // Delete Inbound Message handlers. $DB->delete_records('messageinbound_handlers', ...
csn
// Init initializes PhysicalTableReader.
func (p PhysicalTableReader) Init(ctx sessionctx.Context) *PhysicalTableReader { p.basePhysicalPlan = newBasePhysicalPlan(ctx, TypeTableReader, &p) p.TablePlans = flattenPushDownPlan(p.tablePlan) p.schema = p.tablePlan.Schema() return &p }
csn
// ClearDataForOriginWithParams - Clears storage for origin.
func (c *Storage) ClearDataForOriginWithParams(v *StorageClearDataForOriginParams) (*gcdmessage.ChromeResponse, error) { return gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Storage.clearDataForOrigin", Params: v}) }
csn
// Timeout is used to set timeout for connections.
func (gr *GoReq) Timeout(timeout time.Duration) *GoReq { gr.Transport.Dial = func(network, addr string) (net.Conn, error) { conn, err := net.DialTimeout(network, addr, timeout) if err != nil { gr.Errors = append(gr.Errors, err) return nil, err } conn.SetDeadline(time.Now().Add(timeout)) return conn, ni...
csn
Function for printing the menu Keyword arguments: place -- name of the cafeteria / mensa static -- set true if a static menu exists (default: False)
def print_menu(place, static=False): """Function for printing the menu Keyword arguments: place -- name of the cafeteria / mensa static -- set true if a static menu exists (default: False) """ day = get_day() if static: plan = get(FILES[1]) for meal in plan["weeks"][0]["days...
csn
One step of execution.
def execute_once(self): """One step of execution.""" symbol = self.tape.get(self.head, self.EMPTY_SYMBOL) index = self.alphabet.index(symbol) rule = self.states[self.state][index] if rule is None: raise RuntimeError('Unexpected symbol: ' + symbol) self.tape...
csn
// Convert_v1_PolicyRule_To_audit_PolicyRule is an autogenerated conversion function.
func Convert_v1_PolicyRule_To_audit_PolicyRule(in *PolicyRule, out *audit.PolicyRule, s conversion.Scope) error { return autoConvert_v1_PolicyRule_To_audit_PolicyRule(in, out, s) }
csn
Check if the request is made form an allowed IP
def process_request(self, request): """ Check if the request is made form an allowed IP """ # Section adjusted to restrict login to ?edit # (sing cms-toolbar-login)into DjangoCMS login. restricted_request_uri = request.path.startswith( reverse('admin:index') o...
csn
If +value+ is an instance of class +klass+, return it, else create a new instance of +klass+ with value +value+.
def new_with_value_if_need(klass, value) if value.is_a?(klass) value else klass.new(value) end end
csn
Transform the bounding box in the feature projection to WGS84 @param boundingBox bounding box in feature projection @return bounding box in WGS84
public BoundingBox boundingBoxToWgs84(BoundingBox boundingBox) { if (projection == null) { throw new GeoPackageException("Shape Converter projection is null"); } return boundingBox.transform(toWgs84); }
csn
Get the ETag associated with a file. @param so StoredObject to get resourceLength, lastModified and a hashCode of StoredObject @return the ETag
protected String getETag( final StoredObject so ) { String resourceLength = ""; String lastModified = ""; if ( so != null && so.isResource() ) { resourceLength = new Long( so.getResourceLength() ).toString(); lastModified = new Long( so.getLastModified() ...
csn
delegate function that will call the good callback for the good event
function (event) { var eventWrapper = new ariaTemplatesDomEventWrapper(event), result = true; var targetCallback = delegateMap[event.type]; if (targetCallback) { if (event.type == "safetap...
csn
Converts a given cookie into a HTTP conform cookie String @param cookie the cookie to convert @return The cookie string representation of the given cookie
String getCookieString(Cookie cookie) { StringBuilder builder = new StringBuilder(); builder.append(cookie.getName()); builder.append("="); builder.append(cookie.getValue()); if (cookie.getVersion() > 0) { builder.append(";" + VERSION + "=").append(cookie.getVersion...
csn
Before saving the model, strip dynamic attributes applied from config. @return void
public function beforeSave() { /* * Dynamic attributes are stored in the jsonable attribute 'data'. */ $staticAttributes = ['id', 'theme', 'data', 'created_at', 'updated_at']; $dynamicAttributes = array_except($this->getAttributes(), $staticAttributes); $this->data...
csn
Processes semantic config and translates it to container parameters. @param \Symfony\Component\DependencyInjection\ContainerBuilder $container @param $config
protected function processSemanticConfig(ContainerBuilder $container, $config) { $processor = new ConfigurationProcessor($container, 'eztags'); $processor->mapConfig( $config, static function ($config, $scope, ContextualizerInterface $c) { $c->setContextualPar...
csn
Lists all Currency models. @return mixed @throws Exception
public function actionIndex() { $rates = Currency::find()->orderBy('id DESC')->all(); $model = new Currency(); if (Yii::$app->request->isPost) { if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $model->save(); ...
csn
Outputs an encoded string representation of the mail message including all headers, attachments, etc. This is an encoded email in US-ASCII, so it is able to be directly sent to an email server.
def encoded ready_to_send! buffer = header.encoded buffer << "\r\n" buffer << body.encoded(content_transfer_encoding) buffer end
csn
Open the current session @return self
public function open() { if (version_compare(PHP_VERSION, '5.4', '>')) { if (session_status() == PHP_SESSION_NONE) { session_start(); } } else { @session_start(); } $this->is_opened = true; return $this; }
csn
inserts a record with a time to live. If the record exists, and exception will be thrown. @param namespace Namespace to store the record @param set Set to store the record @param key Key of the record @param bins A list of Bins to insert @param ttl The record time to live in seconds
public void insert(String namespace, String set, Key key, List<Bin> bins, int ttl) { this.client.put(this.insertPolicy, key, bins.toArray(new Bin[0])); }
csn
Create a vod media via local file. @param $fileName string, path of local file @param $title string, the title of the media @param $description string, the description of the media, optional @param array $options Supported options: { config: the optional bce configuration, which will overwrite the default vod client c...
public function createMediaFromFile($fileName, $title, $description = '', $options = array()) { if (empty($fileName)) { throw new BceClientException("The parameter fileName should NOT be null or empty string"); } if (empty($title)) { throw new BceClientException("The...
csn
gets information about solr @return array|Schema\Solr
public function getSolrFields() { $solr = $this->def->getSolr(); if (!$solr instanceof Solr) { return []; } $fields = []; foreach ($solr->getFields() as $field) { $fields[] = [ 'name' => $field->getName(), 'type' => $fi...
csn
Interact with the HelperRegistry to load all the helpers. @return $this
public function loadHelpers() { $registry = $this->helpers(); $helpers = $registry->normalizeArray($this->helpers); foreach ($helpers as $properties) { $this->loadHelper($properties['class'], $properties['config']); } return $this; }
csn
Determine whether or not the provided address is private.
private boolean isPrivateIp(String address) { InetAddress ip; try { ip = InetAddress.getByName(address); } catch (UnknownHostException e) { return false; } return ip.isLoopbackAddress() || ip.isLinkLocalAddress() || ip.isSiteLocalAddress(); }
csn
Get the timestamp based on input date, no matter input is timestamp or string date. @param string|int|\DateTime|null $date The input date/timestamp/insertTag @param bool $replaceInsertTags Disable/enable {{date::}} insertTag support @param string|null $timezone ...
public function getTimeStamp($date = null, $replaceInsertTags = true, $timezone = null) { if (null === $date) { return 0; } if ($date instanceof \DateTime) { $timezone ? $date->setTimezone(new \DateTimeZone($timezone)) : null; return $date->getTimestamp(...
csn
Save current experimental data to a file
public void save(String file) throws IOException,FileNotFoundException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(blockerNames); oos.writeObject(datasetNames); oos.writeObject(learnerNames); oos.writeObject(expt); oos.close(); }
csn
Encrypt the data and write into the session @param string $id @param string $data
public function write($id, $data) { return parent::write($id, $this->encrypt($data, $this->key)); }
csn
Search for delta files and return a dict of Delta objects, keyed by directory names.
def __get_delta_files(self): """Search for delta files and return a dict of Delta objects, keyed by directory names.""" files = [(d, f) for d in self.dirs for f in listdir(d) if isfile(join(d, f))] deltas = OrderedDict() for d, f in files: file_ = join(d, f) if ...
csn