query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
private boolean maybeFinish() { // Check for cancellations Throwable localError = this.cancellation.get(); if (localError != null) { finished = true; outerResponseObserver.onError(localError); return true; } // Check for upstream termination and exhaustion of local buffers if (done && !reframer.hasFullFrame() && !awaitingInner) { finished = true; if (error != null) {
outerResponseObserver.onError(error); } else if (reframer.hasPartialFrame()) { outerResponseObserver.onError(new IncompleteStreamException()); } else { outerResponseObserver.onComplete(); } return true; } // No termination conditions found, go back to business as usual return false; }
csn_ccr
// SetCertificateOverride sets the CertificateOverride field's value.
func (s *StartBuildInput) SetCertificateOverride(v string) *StartBuildInput { s.CertificateOverride = &v return s }
csn
// Convert_core_NodeCondition_To_v1_NodeCondition is an autogenerated conversion function.
func Convert_core_NodeCondition_To_v1_NodeCondition(in *core.NodeCondition, out *v1.NodeCondition, s conversion.Scope) error { return autoConvert_core_NodeCondition_To_v1_NodeCondition(in, out, s) }
csn
Retrieve the relation between this node and a child PID.
def _get_child_relation(self, child_pid): """Retrieve the relation between this node and a child PID.""" return PIDRelation.query.filter_by( parent=self._resolved_pid, child=child_pid, relation_type=self.relation_type.id).one()
csn
python placeholder symble for boolean
def less_strict_bool(x): """Idempotent and None-safe version of strict_bool.""" if x is None: return False elif x is True or x is False: return x else: return strict_bool(x)
cosqa
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`, from multiple countries.
def make_simple_multi_country_equity_info(countries_to_sids, countries_to_exchanges, start_date, end_date): """Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`, from multiple countries. """ sids = [] symbols = [] exchanges = [] for country, country_sids in countries_to_sids.items(): exchange = countries_to_exchanges[country] for i, sid in enumerate(country_sids): sids.append(sid) symbols.append('-'.join([country, str(i)])) exchanges.append(exchange) return pd.DataFrame( { 'symbol': symbols, 'start_date': start_date, 'end_date': end_date, 'asset_name': symbols, 'exchange': exchanges, }, index=sids, columns=( 'start_date', 'end_date', 'symbol', 'exchange', 'asset_name', ), )
csn
Update nodes data size.
protected void accumulatePersistedNodesChanges(Map<String, Long> calculatedChangedNodesSize) throws QuotaManagerException { for (Entry<String, Long> entry : calculatedChangedNodesSize.entrySet()) { String nodePath = entry.getKey(); long delta = entry.getValue(); try { long dataSize = delta + quotaPersister.getNodeDataSize(rName, wsName, nodePath); quotaPersister.setNodeDataSizeIfQuotaExists(rName, wsName, nodePath, dataSize); } catch (UnknownDataSizeException e) { calculateNodeDataSizeTool.getAndSetNodeDataSize(nodePath); } } }
csn
def login login_hash = { 'sync-id' => 0, 'password' => @password, 'user-id' => @username, 'token' => @token } login_hash['silo-id'] = @silo_id if @silo_id r = execute(make_xml('LoginRequest', login_hash))
if r.success @session_id = r.sid true end rescue APIError raise AuthenticationFailed.new(r) end
csn_ccr
Returns an Uuid identifier. @param string|null $namespace @param string|null $name @return string
public static function create($namespace = null, $name = null) { if (null === $namespace) { return self::createNamespacelessUuid(); } return self::createNamespacedUuid($namespace, $name); }
csn
func (t *ToTransformation) UpdateWatermark(id execute.DatasetID, pt execute.Time)
error { return t.d.UpdateWatermark(pt) }
csn_ccr
Runs the application. This is the main entrance of an application. @return int the exit status (0 means normal, non-zero values mean abnormal)
public function run() { if (YII_ENABLE_ERROR_HANDLER) { $this->get('errorHandler')->register(); } try { $this->state = self::STATE_BEFORE_REQUEST; $this->trigger(RequestEvent::BEFORE); $this->state = self::STATE_HANDLING_REQUEST; $this->response = $this->handleRequest($this->getRequest()); $this->state = self::STATE_AFTER_REQUEST; $this->trigger(RequestEvent::AFTER); $this->state = self::STATE_SENDING_RESPONSE; $this->response->send(); $this->state = self::STATE_END; return $this->response->exitStatus; } catch (ExitException $e) { $this->end($e->statusCode, $this->response ?? null); return $e->statusCode; } }
csn
Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer.   Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6   Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5
class Solution: def findSpecialInteger(self, arr: List[int]) -> int: count = 0 num = arr[0] for x in arr: if x == num: count = count+ 1 elif x != num and ((count / len(arr))>0.25): return num else: num = x count = 1 return arr[len(arr)-1]
apps
def search(self): """Applies the filter to the stored dataframe. A safe environment dictionary will be created, which stores all allowed functions and attributes, which may be used for the filter. If any object in the given `filterString` could not be found in the dictionary, the filter does not apply and returns `False`. Returns: tuple: A (indexes, success)-tuple, which indicates identified objects by applying the filter and if the operation was successful in general. """ # there should be a grammar defined and some lexer/parser. # instead of this quick-and-dirty implementation. safeEnvDict = { 'freeSearch': self.freeSearch, 'extentSearch': self.extentSearch, 'indexSearch': self.indexSearch } for col in self._dataFrame.columns: safeEnvDict[col] = self._dataFrame[col] try: searchIndex = eval(self._filterString, {
'__builtins__': None}, safeEnvDict) except NameError: return [], False except SyntaxError: return [], False except ValueError: # the use of 'and'/'or' is not valid, need to use binary operators. return [], False except TypeError: # argument must be string or compiled pattern return [], False return searchIndex, True
csn_ccr
Revert the effect of indentation. Examples -------- Remove a simple one-level indentation: >>> text = '''<->This is line 1. ... <->Next line. ... <->And another one.''' >>> print(text) <->This is line 1. <->Next line. <->And another one. >>> print(dedent(text, '<->')) This is line 1. Next line. And another one. Multiple levels of indentation: >>> text = '''<->Level 1. ... <-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <->Level 1. <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 1. <->Level 2. <-><->Level 3. >>> text = '''<-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 2. <->Level 3. >>> print(dedent(text, '<->', max_levels=1)) <->Level 2. <-><->Level 3.
def dedent(string, indent_str=' ', max_levels=None): """Revert the effect of indentation. Examples -------- Remove a simple one-level indentation: >>> text = '''<->This is line 1. ... <->Next line. ... <->And another one.''' >>> print(text) <->This is line 1. <->Next line. <->And another one. >>> print(dedent(text, '<->')) This is line 1. Next line. And another one. Multiple levels of indentation: >>> text = '''<->Level 1. ... <-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <->Level 1. <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 1. <->Level 2. <-><->Level 3. >>> text = '''<-><->Level 2. ... <-><-><->Level 3.''' >>> print(text) <-><->Level 2. <-><-><->Level 3. >>> print(dedent(text, '<->')) Level 2. <->Level 3. >>> print(dedent(text, '<->', max_levels=1)) <->Level 2. <-><->Level 3. """ if len(indent_str) == 0: return string lines = string.splitlines() # Determine common (minumum) number of indentation levels, capped at # `max_levels` if given def num_indents(line): max_num = int(np.ceil(len(line) / len(indent_str))) for i in range(max_num): if line.startswith(indent_str): line = line[len(indent_str):] else: break return i num_levels = num_indents(min(lines, key=num_indents)) if max_levels is not None: num_levels = min(num_levels, max_levels) # Dedent dedent_len = num_levels * len(indent_str) return '\n'.join(line[dedent_len:] for line in lines)
csn
protected function initLayout() { if ($this->layout === null) { $this->layout = 'Generic'; } if (is_string($this->layout) || is_array($this->layout)) { $this->layout = $this->factory($this->layout, ['form'=>$this], 'FormLayout'); $this->layout = $this->add($this->layout); } elseif (is_object($this->layout)) { $this->layout->form = $this; $this->add($this->layout); } else { throw new Exception(['Unsupported specification of form layout. Can be array, string or object', 'layout' => $this->layout]); } // Add save button in layout
if ($this->buttonSave) { $this->buttonSave = $this->layout->addButton($this->buttonSave); $this->buttonSave->setAttr('tabindex', 0); $this->buttonSave->on('click', $this->js()->form('submit')); $this->buttonSave->on('keypress', new jsExpression('if (event.keyCode === 13){$([name]).form("submit");}', ['name' => '#'.$this->name])); } }
csn_ccr
Use this API to fetch all the dnstxtrec resources that are configured on netscaler.
public static dnstxtrec[] get(nitro_service service) throws Exception{ dnstxtrec obj = new dnstxtrec(); dnstxtrec[] response = (dnstxtrec[])obj.get_resources(service); return response; }
csn
Get the user's configuration @return {*} A configuration object
function getOverrides() { const configPath = path.join(process.cwd(), "crafty.config.js"); if (fs.existsSync(configPath)) { return require(configPath); } console.log(`No crafty.config.js found in '${process.cwd()}', proceeding...`); return {}; }
csn
// Convert_config_VolumeConfiguration_To_v1alpha1_VolumeConfiguration is an autogenerated conversion function.
func Convert_config_VolumeConfiguration_To_v1alpha1_VolumeConfiguration(in *config.VolumeConfiguration, out *v1alpha1.VolumeConfiguration, s conversion.Scope) error { return autoConvert_config_VolumeConfiguration_To_v1alpha1_VolumeConfiguration(in, out, s) }
csn
private CreateSubnetResponseType createSubnet(final String vpcId, final String cidrBlock) { CreateSubnetResponseType ret = new CreateSubnetResponseType(); ret.setRequestId(UUID.randomUUID().toString());
MockSubnet mockSubnet = mockSubnetController.createSubnet(cidrBlock, vpcId); SubnetType subnetType = new SubnetType(); subnetType.setVpcId(mockSubnet.getVpcId()); subnetType.setSubnetId(mockSubnet.getSubnetId()); ret.setSubnet(subnetType); return ret; }
csn_ccr
Delete rows from the table. @param KDatabaseQueryDelete $query The query object. @return integer Number of rows affected, or -1 if an error occurred.
public function delete(KDatabaseQueryDelete $query) { $context = $this->getContext(); $context->query = $query; //Execute the delete operation if ($this->invokeCommand('before.delete', $context) !== false) { //Execute the query $context->result = $this->execute($context->query); $context->affected = $this->_affected_rows; $this->invokeCommand('after.delete', $context); } return $context->affected; }
csn
Convert file data to a string for display. This function takes the file data produced by gather_file_data().
def file_data_to_str(data): """ Convert file data to a string for display. This function takes the file data produced by gather_file_data(). """ if not data: return _('<i>File name not recorded</i>') res = data['name'] try: mtime_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['mtime'])) res += '<br><i>{}</i>: {}'.format(_('Last modified'), mtime_as_str) res += '<br><i>{}</i>: {} {}'.format( _('Size'), data['size'], _('bytes')) except KeyError: res += '<br>' + _('<i>File no longer exists</i>') return res
csn
Returns the directory path and creates it if not exists. @return string
private function getDirectoryPath() { $path = $this->config['directory']; // Create directory if not exists if (!is_dir($path)) { mkdir($path, 0755, true); } return $path . DIRECTORY_SEPARATOR; }
csn
func (d *ResourceDiff) diffChange(key string) (interface{}, interface{}, bool, bool, bool) { old, new, customized := d.getChange(key) if !old.Exists { old.Value = nil } if !new.Exists || d.removed(key) {
new.Value = nil } return old.Value, new.Value, !reflect.DeepEqual(old.Value, new.Value), new.Computed, customized }
csn_ccr
func Login(ctx context.Context, authConfig *types.AuthConfig) (HubUser, error) { lclient, err := getClient() if err != nil { return HubUser{}, err } // For licensing we know they must have a valid login session if authConfig.Username == "" { return HubUser{}, fmt.Errorf("you must be logged in to access licenses. Please
use 'docker login' then try again") } token, err := lclient.LoginViaAuth(ctx, authConfig.Username, authConfig.Password) if err != nil { return HubUser{}, err } user, err := lclient.GetHubUserByName(ctx, authConfig.Username) if err != nil { return HubUser{}, err } orgs, err := lclient.GetHubUserOrgs(ctx, token) if err != nil { return HubUser{}, err } return HubUser{ Client: lclient, token: token, User: *user, Orgs: orgs, }, nil }
csn_ccr
Sets the value of this tag. The list tag's type will be set to that of the first tag being added, or null if the given list is empty. @param value New value of this tag. @throws IllegalArgumentException If all tags in the list are not of the same type.
public void setValue(List<Tag> value) throws IllegalArgumentException { this.type = null; this.value.clear(); for(Tag tag : value) { this.add(tag); } }
csn
Converts the value of a given CSS property of a given HTML element from any CSS units into pixels @param {String} valueWithUnit valid CSS value with unit e.g. "12pt", "1em", "10px" @param {HTMLElement} elem Needed if <code>valueWithUnit</code> is in "em" or "%", can be null otherwise. @param {String} property camelCased CSS property name @return {Number} value in pixels
function (valueWithUnit, elem, property) { var unit = this.getUnit(valueWithUnit, property); var value = parseFloat(valueWithUnit, 10); return this.__convertToPixels[unit].call(this, value, elem, property); }
csn
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. @param [*Promise] Promises a number of promises that will be combined into a single promise @return [Promise] Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the `promises` array. If any of the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.
def all(*promises) deferred = Q.defer counter = promises.length results = [] if counter > 0 promises.each_index do |index| ref(promises[index]).then(proc {|result| if results[index].nil? results[index] = result counter -= 1 deferred.resolve(results) if counter <= 0 end result }, proc {|reason| if results[index].nil? deferred.reject(reason) end reason }) end else deferred.resolve(results) end return deferred.promise end
csn
func (z *zone) ResourceRecordSets() (dnsprovider.ResourceRecordSets, bool) { return
&resourceRecordSets{ zone: z, }, true }
csn_ccr
Gets the redirection validator that ensures the followed redirections are in scan's scope. @return the redirection validator, never {@code null}. @since TODO add version @see #getRedirectRequestConfig()
HttpRedirectionValidator getRedirectionValidator() { if (redirectionValidator == null) { redirectionValidator = redirection -> { if (!nodeInScope(redirection.getEscapedURI())) { if (log.isDebugEnabled()) { log.debug("Skipping redirection out of scan's scope: " + redirection); } return false; } return true; }; } return redirectionValidator; }
csn
public static double getDouble(INDArray arr, int[] indices) { long offset = getOffset(arr.shapeInfo(),
ArrayUtil.toLongArray(indices)); return arr.data().getDouble(offset); }
csn_ccr
Computes a hash code for the given dictionary that is safe for persistence round trips
def compute_hash(attributes, ignored_attributes=None): """ Computes a hash code for the given dictionary that is safe for persistence round trips """ ignored_attributes = list(ignored_attributes) if ignored_attributes else [] tuple_attributes = _convert(attributes.copy(), ignored_attributes) hasher = hashlib.sha256(str(tuple_attributes).encode('utf-8', errors='ignore')) return hasher.hexdigest()
csn
private function setupDaemon(DaemonOptionsInterface $daemonOptions): void { $this->requestCount = 0; $this->requestLimit = (int) $daemonOptions->getOption(DaemonOptions::REQUEST_LIMIT); $this->memoryLimit = (int) $daemonOptions->getOption(DaemonOptions::MEMORY_LIMIT); $this->autoShutdown = (bool) $daemonOptions->getOption(DaemonOptions::AUTO_SHUTDOWN);
$timeLimit = (int) $daemonOptions->getOption(DaemonOptions::TIME_LIMIT); if (DaemonOptions::NO_LIMIT !== $timeLimit) { pcntl_alarm($timeLimit); } $this->installSignalHandlers(); }
csn_ccr
Turn a decimal into a hexadecimal. @param {Number} dec The decimal. @return {String} The hexadecimal.
function(dec) { var hex; hex = dec.toString(16); if (hex.length < 2) { hex = "0" + hex; } return hex; }
csn
Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser to.
def register_intent_parser(self, intent_parser, domain=0): """ Register a intent parser with a domain. Args: intent_parser(intent): The intent parser you wish to register. domain(str): a string representing the domain you wish register the intent parser to. """ if domain not in self.domains: self.register_domain(domain=domain) self.domains[domain].register_intent_parser( intent_parser=intent_parser)
csn
Checks the event and system validity then returns the page target, FALSE otherwise. @param \BackBee\Event\Event $event @param bool $check_status @return bool
private function checkCachePageEvent($check_status = true) { return null !== $this->cache_page && true === $this->validator->isValid('page', $this->application->getRequest()->getUri()) && ( true === $check_status ? $this->validator->isValid('cache_status', $this->object) : true ) ; }
csn
// getAttachedInterfacesByID returns the node interfaces of the specified instance.
func getAttachedInterfacesByID(client *gophercloud.ServiceClient, serviceID string) ([]attachinterfaces.Interface, error) { var interfaces []attachinterfaces.Interface pager := attachinterfaces.List(client, serviceID) err := pager.EachPage(func(page pagination.Page) (bool, error) { s, err := attachinterfaces.ExtractInterfaces(page) if err != nil { return false, err } interfaces = append(interfaces, s...) return true, nil }) if err != nil { return interfaces, err } return interfaces, nil }
csn
// SetResourceCount sets the ResourceCount field's value.
func (s *GroupedResourceCount) SetResourceCount(v int64) *GroupedResourceCount { s.ResourceCount = &v return s }
csn
// NewProperty creates a new Property
func NewProperty(parent *Properties) *Property { property := &Property{parent: parent, Group: &Group{}, Contract: &Contract{}} property.Init() return property }
csn
Return a list of all of the agents from a list of statements. Only agents that are not None and have a TEXT entry are returned. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` Returns ------- agents : list of :py:class:`indra.statements.Agent` List of agents that appear in the input list of indra statements.
def all_agents(stmts): """Return a list of all of the agents from a list of statements. Only agents that are not None and have a TEXT entry are returned. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` Returns ------- agents : list of :py:class:`indra.statements.Agent` List of agents that appear in the input list of indra statements. """ agents = [] for stmt in stmts: for agent in stmt.agent_list(): # Agents don't always have a TEXT db_refs entry (for instance # in the case of Statements from databases) so we check for this. if agent is not None and agent.db_refs.get('TEXT') is not None: agents.append(agent) return agents
csn
public static Format getFormatter(@Nonnull final Locale locale, @Nonnull final String format, @Nullable final Class<?>... type) { Format formatter = null; Pattern TEXT_FORMAT_STRING = Pattern.compile("^\\{([^}]+)}(.+)$"); Matcher matcher = TEXT_FORMAT_STRING.matcher(format); if (matcher.matches()) { switch (matcher.group(1)) { case "Message": formatter = new MessageFormat(matcher.group(2), locale); break; case "Date": formatter = new SimpleDateFormat(matcher.group(2), locale); break; case "String": formatter = new FormatterFormat(matcher.group(2), locale); break; default:
case "Log": formatter = new LoggerFormat(matcher.group(2)); break; } } else { if (type != null && type.length == 1 && type[0] != null && (Calendar.class.isAssignableFrom(type[0]) || Date.class.isAssignableFrom(type[0]))) { formatter = new SimpleDateFormat(format, locale); } else { formatter = new LoggerFormat(format); } } return formatter; }
csn_ccr
Description: #Task: Write a function that returns true if the number is a "Very Even" number. If a number is a single digit, then it is simply "Very Even" if it itself is even. If it has 2 or more digits, it is "Very Even" if the sum of it's digits is "Very Even". #Examples: ``` input(88) => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd input(222) => returns true input(5) => returns false input(841) => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even ``` Note: The numbers will always be 0 or positive integers!
def is_very_even_number(n): while len(str(n)) > 1: n = sum(int(x) for x in str(n)) return True if n % 2 == 0 else False
apps
Write the list of entries to a file. :param filename: :param encoding: :return:
def write(self, filename, encoding='utf-8'): """Write the list of entries to a file. :param filename: :param encoding: :return: """ with io.open(str(filename), 'w', encoding=encoding) as fp: for entry in self: fp.write(entry.__unicode__()) fp.write('\n\n')
csn
protected function before() { if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) { $this->connection->executeUpdate('EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"');
} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) { $this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=0'); } else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) { $this->connection->executeUpdate('PRAGMA foreign_keys = OFF'); } }
csn_ccr
private String readFile( Reader reader ) throws IOException { lineLengths = new ArrayList<Integer>(); lineLengths.add( null ); LineNumberReader lnr = new LineNumberReader( reader ); StringBuilder sb = new StringBuilder(); int nlCount = 0; boolean inEntry = false; String line; while( (line = lnr.readLine()) != null ){ lineLengths.add( line.length() ); Matcher commentMat = commentPat.matcher( line ); if( commentMat.matches() ){ if( inEntry ){ nlCount++; } else { sb.append( '\n' ); } if( "#/".equals( commentMat.group( 2 ) ) ){ String[] options = commentMat.group( 1 ).substring( 2 ).trim().split( "\\s+" ); for( String option: options ){ optionSet.add( option ); }
} continue; } if( entryPat.matcher( line ).matches() ){ if( inEntry ){ for( int i = 0; i < nlCount; i++ ) sb.append( '\n' ); } sb.append( line ); nlCount = 1; inEntry = true; continue; } sb.append( ' ').append( line ); nlCount++; } if( inEntry ) sb.append( '\n' ); lnr.close(); // logger.info( "====== DSL definition:" ); // logger.info( sb.toString() ); return sb.toString(); }
csn_ccr
Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
def deserialize(self, value, **kwargs): """Deserialization of value. :return: Deserialized value. :raises: :class:`halogen.exception.ValidationError` exception if value is not valid. """ for validator in self.validators: validator.validate(value, **kwargs) return value
csn
func NewTLV(tag Tag, value []byte) Body { return
&Field{ Tag: tag, Data: value } }
csn_ccr
' Called by a proxy to lookup a map of object references. The proxy knows the schema name so the hold does not need to bother storing it.
public Map<String, Object> getObjectReferenceMap(String field, String schemaName) { List<String> instanceIds = references.get(field); if(instanceIds == null || instanceIds.size() == 0) { return null; } Map<String, Object> objects = new HashMap<>(); for (String instanceId : instanceIds) { BeanId id = BeanId.create(instanceId, schemaName); Object instance = instances.get(id); if(instance != null) { objects.put(instanceId, instance); } else { instance = cache.get(id); instances.put(id, instance); objects.put(instanceId, instance); } } return objects; }
csn
Try to convert upper unicode characters to plain ascii, the returned string may contain unconverted unicode characters. @param string $text input string @param string $charset encoding of the text @return string converted ascii string
public static function specialtoascii($text, $charset='utf-8') { $charset = self::parse_charset($charset); $oldlevel = error_reporting(E_PARSE); $result = self::typo3()->specCharsToASCII($charset, (string)$text); error_reporting($oldlevel); return $result; }
csn
// FindStringSubmatchMap behaves the same as FindStringSubmatch except instead // of a list of matches with the names separate, it returns the full match and a // map of named submatches
func (r *ExtRegexp) FindStringSubmatchMap(s string) (string, map[string]string) { match := r.FindStringSubmatch(s) if match == nil { return "", nil } captures := make(map[string]string) for i, name := range r.SubexpNames() { if i == 0 { continue } if name != "" { // ignore unnamed matches captures[name] = match[i] } } return match[0], captures }
csn
def _get_generic_schema(self): """ Returns whoosh's generic schema of the dataset. """ schema = Schema( vid=ID(stored=True, unique=True), # Object id title=NGRAMWORDS(), keywords=KEYWORD, # Lists of coverage identifiers, ISO time values
and GVIDs, source names, source abbrev doc=TEXT) # Generated document for the core of the topic search return schema
csn_ccr
Reverses an fst @param infst the fst to reverse @return the reversed fst
public static MutableFst reverse(Fst infst) { infst.throwIfInvalid(); MutableFst fst = ExtendFinal.apply(infst); Semiring semiring = fst.getSemiring(); MutableFst result = new MutableFst(fst.getStateCount(), semiring); result.setInputSymbolsAsCopy(fst.getInputSymbols()); result.setOutputSymbolsAsCopy(fst.getOutputSymbols()); MutableState[] stateMap = initStateMap(fst, semiring, result); for (int i = 0; i < fst.getStateCount(); i++) { State oldState = fst.getState(i); MutableState newState = stateMap[oldState.getId()]; for (int j = 0; j < oldState.getArcCount(); j++) { Arc oldArc = oldState.getArc(j); MutableState newNextState = stateMap[oldArc.getNextState().getId()]; double newWeight = semiring.reverse(oldArc.getWeight()); result.addArc(newNextState, oldArc.getIlabel(), oldArc.getOlabel(), newState, newWeight); } } return result; }
csn
Add a Comparator to the end of the chain using the given sortFields order @param comparator Comparator to add to the end of the chain @param reverse false = forward sortFields order; true = reverse sortFields order
public void addComparator(Comparator<T> comparator, boolean reverse) { checkLocked(); comparatorChain.add(comparator); if (reverse == true) { orderingBits.set(comparatorChain.size() - 1); } }
csn
def make_slice_key(cls, start_string, size_string): """ Converts the given start and size query parts to a slice key. :return: slice key :rtype: slice """ try: start = int(start_string) except ValueError: raise ValueError('Query parameter "start" must be a number.') if start < 0: raise ValueError('Query parameter "start" must be zero or ' 'a positive number.')
try: size = int(size_string) except ValueError: raise ValueError('Query parameter "size" must be a number.') if size < 1: raise ValueError('Query parameter "size" must be a positive ' 'number.') return slice(start, start + size)
csn_ccr
Enriched features. {threshdoc}
def enriched(self, thresh=0.05, idx=True): """ Enriched features. {threshdoc} """ return self.upregulated(thresh=thresh, idx=idx)
csn
Zonal Computing Olympiad 2014, 30 Nov 2013 In IPL 2025, the amount that each player is paid varies from match to match. The match fee depends on the quality of opposition, the venue etc. The match fees for each match in the new season have been announced in advance. Each team has to enforce a mandatory rotation policy so that no player ever plays three matches in a row during the season. Nikhil is the captain and chooses the team for each match. He wants to allocate a playing schedule for himself to maximize his earnings through match fees during the season. -----Input format----- Line 1: A single integer N, the number of games in the IPL season. Line 2: N non-negative integers, where the integer in position i represents the fee for match i. -----Output format----- The output consists of a single non-negative integer, the maximum amount of money that Nikhil can earn during this IPL season. -----Sample Input 1----- 5 10 3 5 7 3 -----Sample Output 1----- 23 (Explanation: 10+3+7+3) -----Sample Input 2----- 8 3 2 3 2 3 5 1 3 -----Sample Output 2----- 17 (Explanation: 3+3+3+5+3) -----Test data----- There is only one subtask worth 100 marks. In all inputs: • 1 ≤ N ≤ 2×105 • The fee for each match is between 0 and 104, inclusive. -----Live evaluation data----- There are 12 test inputs on the server during the exam.
# cook your dish here n=int(input()) l=list(map(int,input().split())) temp=[] for item in l: temp.append(item) if(n<=3): print(sum(temp)) else: for i in range(3,n): temp[i]=l[i]+min(temp[i-1],temp[i-2],temp[i-3]) res=sum(l)-min(temp[n-1],temp[n-2],temp[n-3]) print(res)
apps
public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "entry"); try { // if there are no filters, just invoke the requested servlet if (!_filtersDefined) { invokeTarget(request, response); } else { // increment the filter index _currentFilterIndex++; if (_currentFilterIndex < _numberOfFilters) { // more filters to go...invoke the next one FilterInstanceWrapper wrapper = ((FilterInstanceWrapper) _filters.get(_currentFilterIndex)); if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){ //306998.15 logger.logp(Level.FINE, CLASS_NAME,"doFilter", "executing filter -->" + wrapper.getFilterName()); } wrapper.doFilter(request, response, this); } else { invokeTarget(request, response); } } } catch (UnavailableException e) { throw e; } catch (IOException ioe) { throw ioe; } catch (ServletException e) { Throwable t = e.getCause(); if (t!=null && t instanceof FileNotFoundException) { //don't log a FFDC logger.logp(Level.FINE, CLASS_NAME, "doFilter", "FileNotFound"); } else{ //start 140014 if(webapp.getDestroyed() != true) com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter", "82", this);
else if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "Can not invoke filter because application is destroyed", e); //end 140014 } if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "exit"); throw e; } catch (RuntimeException re) { throw re; } catch (Throwable th) { com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(th, "com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter", "89", this); if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "exit"); throw new ServletErrorReport(th); } if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "exit"); }
csn_ccr
def extend(self, assembly): """Extends the `Assembly` with the contents of another `Assembly`. Raises ------ TypeError Raised if other is any type other than `Assembly`. """ if isinstance(assembly, Assembly):
self._molecules.extend(assembly) else: raise TypeError( 'Only Assembly objects may be merged with an Assembly.') return
csn_ccr
Marshall a Shuffling object into a DOMElement object. @param \qtism\data\QtiComponent $component A Shuffling object. @return \DOMElement The according DOMElement object.
protected function marshall(QtiComponent $component) { $element = static::getDOMCradle()->createElement($component->getQtiClassName()); $this->setDOMElementAttribute($element, 'responseIdentifier', $component->getResponseIdentifier()); foreach ($component->getShufflingGroups() as $shufflingGroup) { $marshaller = $this->getMarshallerFactory()->createMarshaller($shufflingGroup); $element->appendChild($marshaller->marshall($shufflingGroup)); } return $element; }
csn
func (h *Client) InstallRelease(chstr, ns string, opts ...InstallOption) (*rls.InstallReleaseResponse, error) {
// load the chart to install chart, err := chartutil.Load(chstr) if err != nil { return nil, err } return h.InstallReleaseFromChart(chart, ns, opts...) }
csn_ccr
Check the request for a cache-related response @param request the request @param modified the modified time @param etag the etag @throws WebApplicationException either a 412 Precondition Failed or a 304 Not Modified, depending on the context.
protected static void checkCache(final Request request, final Instant modified, final EntityTag etag) { final ResponseBuilder builder = request.evaluatePreconditions(from(modified), etag); if (nonNull(builder)) { throw new WebApplicationException(builder.build()); } }
csn
public function bindParameters(ContainerBuilder $container, $name, $config) { if (is_array($config) && empty($config[0])) { foreach ($config as $key => $value) {
$this->bindParameters($container, $name . '.' . $key, $value); } } else { $container->setParameter($name, $config); } }
csn_ccr
Update channel. @param string $channel Channel name @param array $options Channel options @param string $token Twitch token @return JSON Request result
public function putChannel($channel, $rawOptions, $token = null) { $options = []; foreach ($rawOptions as $key => $value) { $options['channel['.$key.']'] = $value; } return $this->sendRequest('PUT', 'channels/'.$channel, $this->getToken($token), $options); }
csn
private static function parseQuery() : array { /* * Parse the query string. We need to do this ourself, so that we get access * to the raw (urlencoded) values. This is required because different software * can urlencode to different values. */ $data = []; $relayState = ''; $sigAlg = ''; $sigQuery = ''; foreach (explode('&', $_SERVER['QUERY_STRING']) as $e) { $tmp = explode('=', $e, 2); $name = $tmp[0]; if (count($tmp) === 2) { $value = $tmp[1]; } else { /* No value for this parameter. */ $value = ''; } $name = urldecode($name); $data[$name] = urldecode($value); switch ($name) {
case 'SAMLRequest': case 'SAMLResponse': $sigQuery = $name.'='.$value; break; case 'RelayState': $relayState = '&RelayState='.$value; break; case 'SigAlg': $sigAlg = '&SigAlg='.$value; break; } } $data['SignedQuery'] = $sigQuery.$relayState.$sigAlg; return $data; }
csn_ccr
Set the log filename. @see NCSARequestLog#setRetainDays(int) @param filename The filename to use. If the filename contains the string "yyyy_mm_dd", then a RolloverFileOutputStream is used and the log is rolled over nightly and aged according setRetainDays. If no filename is set or a null filename passed, then requests are logged to System.err.
public void setFilename(String filename) { if (filename!=null) { filename=filename.trim(); if (filename.length()==0) filename=null; } _filename=filename; }
csn
func (db *DynamoDB) Seed(overwrite bool, jwtPass string) error { cred, err := db.DB.Config.Credentials.Get() if err != nil { return fmt.Errorf("dynamodb: failed to initialize: %v", err) } log.Printf("dynamodb: initialized with region: %v, access key ID: %v, endpoint: %v", *(db.DB.Config.Region), cred.AccessKeyID, db.DB.Config.Endpoint) if !overwrite { if tbls, err := db.listTables(); err != nil { return err } else if len(tbls) != 0 { return nil } } if err := db.deleteTables(); err != nil { return err } // create the tables for _, tbl := range db.Tables { tableParams := &dynamodb.CreateTableInput{ TableName: aws.String(tbl), ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(1), WriteCapacityUnits: aws.Int64(1), }, AttributeDefinitions: []*dynamodb.AttributeDefinition{ { AttributeName: aws.String("ID"), AttributeType: aws.String("S"), }, { AttributeName: aws.String("Email"), AttributeType: aws.String("S"), }, }, KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("ID"), KeyType: aws.String("HASH"), }, }, GlobalSecondaryIndexes: []*dynamodb.GlobalSecondaryIndex{ { IndexName: aws.String("Email"), KeySchema: []*dynamodb.KeySchemaElement{ { AttributeName: aws.String("Email"), KeyType: aws.String("HASH"), }, }, Projection: &dynamodb.Projection{ NonKeyAttributes: []*string{ aws.String("Email"), }, ProjectionType: aws.String("INCLUDE"), }, ProvisionedThroughput: &dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(1), WriteCapacityUnits: aws.Int64(1), }, },
}, // LocalSecondaryIndexes: []*dynamodb.LocalSecondaryIndex{ // { // IndexName: aws.String("IndexName"), // KeySchema: []*dynamodb.KeySchemaElement{ // { // AttributeName: aws.String("KeySchemaAttributeName"), // KeyType: aws.String("KeyType"), // }, // // }, // Projection: &dynamodb.Projection{ // NonKeyAttributes: []*string{ // aws.String("NonKeyAttributeName"), // // }, // ProjectionType: aws.String("ProjectionType"), // }, // }, // }, // StreamSpecification: &dynamodb.StreamSpecification{ // StreamEnabled: aws.Bool(true), // StreamViewType: aws.String("StreamViewType"), // }, } if _, err := db.DB.CreateTable(tableParams); err != nil { return err } // tables with secondary indexes need to be created sequentially so wait till table is ready if err := db.DB.WaitUntilTableExists(&dynamodb.DescribeTableInput{TableName: aws.String(tbl)}); err != nil { return err } } // insert the seed data if err := data.SeedInit(jwtPass); err != nil { return err } for _, u := range data.SeedUsers { if err := db.SaveUser(&u); err != nil { return err } } return nil }
csn_ccr
protected function getDirectoryPrettyName() { $pathName = $this->normalizePath($this->file->getPathname()); // If the post is inside a child directory of the _blog directory then // we deal with it like regular site files and generate a nested // directories based post path with exact file name. if ($this->isInsideBlogDirectory($pathName)) {
return str_replace('/_blog/', '/', parent::getDirectoryPrettyName()); } $fileBaseName = $this->getFileName(); $fileRelativePath = $this->getBlogPostSlug($fileBaseName); return KATANA_PUBLIC_DIR."/$fileRelativePath"; }
csn_ccr
def state_counts(self, variable, **kwargs): """ Return counts how often each state of 'variable' occured in the data. If the variable has parents, counting is done conditionally for each state configuration of the parents. Parameters ---------- variable: string Name of the variable for which the state count is to be done. complete_samples_only: bool Specifies how to deal with missing data, if present. If set to `True` all rows that contain `np.NaN` somewhere are ignored. If `False` then every row where neither the variable nor its parents are `np.NaN` is used. Desired default behavior can be passed to the class constructor. Returns ------- state_counts: pandas.DataFrame Table with state counts for 'variable' Examples -------- >>> import pandas as pd >>> from pgmpy.models import BayesianModel >>> from pgmpy.estimators import ParameterEstimator >>> model = BayesianModel([('A', 'C'), ('B', 'C')]) >>> data = pd.DataFrame(data={'A': ['a1', 'a1', 'a2'],
'B': ['b1', 'b2', 'b1'], 'C': ['c1', 'c1', 'c2']}) >>> estimator = ParameterEstimator(model, data) >>> estimator.state_counts('A') A a1 2 a2 1 >>> estimator.state_counts('C') A a1 a2 B b1 b2 b1 b2 C c1 1 1 0 0 c2 0 0 1 0 """ parents = sorted(self.model.get_parents(variable)) return super(ParameterEstimator, self).state_counts(variable, parents=parents, **kwargs)
csn_ccr
To Integer Convert value to integer. @param val the value to convert to integer. @param def optional default value on null or error.
function toInteger(val, def) { if (!is_1.isValue(val)) return toDefault(null, def); var parsed = function_1.tryWrap(parseInt, val)(def); if (is_1.isInteger(parsed)) return parsed; if (toBoolean(val)) return 1; return 0; }
csn
Appends a Middleware to the route which is to be executed before the route runs
def middleware(self, args): """ Appends a Middleware to the route which is to be executed before the route runs """ if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)): self.url.pop() self.url.append((self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=args))) return self
csn
def connect(self): """Connect to MQTT server and wait for server to acknowledge""" if not self.connect_attempted: self.connect_attempted = True self.client.connect(self.host, port=self.port) self.client.loop_start()
while not self.connected: log.info('waiting for MQTT connection...') time.sleep(1)
csn_ccr
func (r *ProviderConfigRef) Addr() addrs.ProviderConfig { return addrs.ProviderConfig{
Type: r.Name, Alias: r.Alias, } }
csn_ccr
protected static function cache_add(context $context) { if (isset(self::$cache_contextsbyid[$context->id])) { // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow return; } if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) { $i = 0; foreach(self::$cache_contextsbyid as $ctx) { $i++; if ($i <= 100) { // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later continue; } if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) { // we remove oldest third of the contexts to make room for more contexts break;
} unset(self::$cache_contextsbyid[$ctx->id]); unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]); self::$cache_count--; } } self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context; self::$cache_contextsbyid[$context->id] = $context; self::$cache_count++; }
csn_ccr
def mean(self, start=None, end=None, mask=None): """This calculated the average value of the time series over the given time range from `start` to `end`, when
`mask` is truthy. """ return self.distribution(start=start, end=end, mask=mask).mean()
csn_ccr
def extra_metadata(self): """Get extra metadata for file in repository.""" return get_extra_metadata( self.gh.api,
self.repository['owner']['login'], self.repository['name'], self.release['tag_name'], )
csn_ccr
private function getObjectStateIds(array $stateIdentifiers): array { $idList = []; foreach ($stateIdentifiers as $identifier) { $identifier = explode('|', $identifier); if (count($identifier) !== 2) { continue; } try {
$stateGroup = $this->objectStateHandler->loadGroupByIdentifier($identifier[0]); $objectState = $this->objectStateHandler->loadByIdentifier($identifier[1], $stateGroup->id); $idList[$stateGroup->id][] = $objectState->id; } catch (NotFoundException $e) { continue; } } return $idList; }
csn_ccr
public static IntDoubleVector estimateGradientFd(Function fn, IntDoubleVector x, double epsilon) { int numParams = fn.getNumDimensions(); IntDoubleVector gradFd = new IntDoubleDenseVector(numParams); for (int j=0; j<numParams; j++) {
// Test the deriviative d/dx_j(f_i(\vec{x})) IntDoubleVector d = new IntDoubleDenseVector(numParams); d.set(j, 1); double dotFd = getGradDotDirApprox(fn, x, d, epsilon); if (Double.isNaN(dotFd)) { log.warn("Hit NaN"); } gradFd.set(j, dotFd); } return gradFd; }
csn_ccr
def get_meta_graph_copy(self, tags=None): """Returns a copy of a MetaGraph with the identical set of tags.""" meta_graph =
self.get_meta_graph(tags) copy = tf_v1.MetaGraphDef() copy.CopyFrom(meta_graph) return copy
csn_ccr
Updates criterias progress by given type & checks referred achievements for completeness state. Returns number of updated criterias. @param mixed $owner @param string $type @param mixed $data = null @return int
public function updateAchievementCriterias($owner, string $type, $data = null): int { $criterias = $this->storage->getOwnerCriteriasByType($owner, $type, $data); if (!count($criterias)) { return 0; } $this->achievementsToCheck = []; $achievements = $this->storage->getAchievementsByCriterias($criterias); $updatedCriteriasCount = 0; foreach ($criterias as $criteria) { /** @var AchievementCriteria $criteria*/ if ($criteria->completed()) { continue; } $achievement = $this->storage->getAchievementForCriteria($criteria, $achievements); if (is_null($achievement)) { continue; } $change = $this->getCriteriaChange($owner, $criteria, $achievement, $data); if (is_null($change)) { continue; } $this->setCriteriaProgress($owner, $criteria, $achievement, $change); $updatedCriteriasCount++; } if (count($this->achievementsToCheck) > 0) { $this->checkCompletedAchievements($owner); } return $updatedCriteriasCount; }
csn
function removeChild(parent, child, currentView) { if (child !== null && canInsertNativeNode(parent, currentView)) { // We only remove the element if not in View or not projected. var renderer = currentView[RENDERER];
isProceduralRenderer(renderer) ? renderer.removeChild(parent.native, child) : parent.native.removeChild(child); return true; } return false; }
csn_ccr
function(handle) { if (isValidID(handle)) { var deferred = $q.defer(); var instance = self.get(handle); if (instance) { deferred.resolve(instance);
} else { if (pendings[handle] === undefined) { pendings[handle] = []; } pendings[handle].push(deferred); } return deferred.promise; } return $q.reject("Invalid `md-component-id` value."); }
csn_ccr
def set_logger(self, logger_name, level, handler=None): """ Sets the level of a logger """ if 'loggers' not in self.config: self.config['loggers'] = {}
real_level = self.real_level(level) self.config['loggers'][logger_name] = {'level': real_level} if handler: self.config['loggers'][logger_name]['handlers'] = [handler]
csn_ccr
def fetch_userid(self, side): """Return the userid for the specified bed side.""" for user in self.users:
obj = self.users[user] if obj.side == side: return user
csn_ccr
// If returns Cond via condition
func If(condition bool, condTrue Cond, condFalse ...Cond) Cond { var c = condIf{ condition: condition, condTrue: condTrue, } if len(condFalse) > 0 { c.condFalse = condFalse[0] } return c }
csn
Clear outdated and invalid pages from sitemap table
public static function expire() { // ##################### // Delete expired entries // ##################### $query = 'DELETE FROM tx_metaseo_sitemap WHERE is_blacklisted = 0 AND expire <= ' . (int)time(); DatabaseUtility::exec($query); // ##################### // Deleted or // excluded pages // ##################### $query = 'SELECT ts.uid FROM tx_metaseo_sitemap ts LEFT JOIN pages p ON p.uid = ts.page_uid AND p.deleted = 0 AND p.hidden = 0 AND p.tx_metaseo_is_exclude = 0 AND ' . DatabaseUtility::conditionNotIn('p.doktype', self::getDoktypeBlacklist()) . ' WHERE p.uid IS NULL'; $deletedSitemapPages = DatabaseUtility::getColWithIndex($query); // delete pages if (!empty($deletedSitemapPages)) { $query = 'DELETE FROM tx_metaseo_sitemap WHERE uid IN (' . implode(',', $deletedSitemapPages) . ') AND is_blacklisted = 0'; DatabaseUtility::exec($query); } }
csn
# Task You're given a substring s of some cyclic string. What's the length of the smallest possible string that can be concatenated to itself many times to obtain this cyclic string? # Example For` s = "cabca"`, the output should be `3` `"cabca"` is a substring of a cycle string "abcabcabcabc..." that can be obtained by concatenating `"abc"` to itself. Thus, the answer is 3. # Input/Output - `[input]` string `s` Constraints: `3 ≤ s.length ≤ 15.` - `[output]` an integer
def cyclic_string(s): return next((i for i, _ in enumerate(s[1:], 1) if s.startswith(s[i:])), len(s))
apps
Load a valid list of users for this gradebook as the screen "items". @return array $users A list of enroled users.
protected function load_users() { global $CFG; // Create a graded_users_iterator because it will properly check the groups etc. $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol); $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol); $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $this->context); require_once($CFG->dirroot.'/grade/lib.php'); $gui = new \graded_users_iterator($this->course, null, $this->groupid); $gui->require_active_enrolment($showonlyactiveenrol); $gui->init(); // Flatten the users. $users = array(); while ($user = $gui->next_user()) { $users[$user->user->id] = $user->user; } $gui->close(); return $users; }
csn
Gets the body from the request. @param Request $request @return array
private function getParsedBody(Request $request): array { $contentType = \explode(';', (string) $request->headers->get('content-type'), 2)[0]; // JSON object switch ($contentType) { case static::CONTENT_TYPE_JSON: $parsedBody = \json_decode($request->getContent(), true); if (\JSON_ERROR_NONE !== \json_last_error()) { throw new BadRequestHttpException('POST body sent invalid JSON'); } break; case static::CONTENT_TYPE_FORM_DATA: $parsedBody = $this->handleUploadedFiles($request->request->all(), $request->files->all()); break; default: throw new BadRequestHttpException(\sprintf( 'Batching parser only accepts "%s" or "%s" content-type but got %s.', static::CONTENT_TYPE_JSON, static::CONTENT_TYPE_FORM_DATA, \json_encode($contentType) )); } return $parsedBody; }
csn
Retrieves one row by primary key value provided @param mixed $id The primary key field value to use to retrieve one row @return \Hubzero\Database\Relational|static @since 2.0.0
public static function one($id) { $instance = self::blank(); return $instance->whereEquals($instance->getPrimaryKey(), $id)->rows()->seek($id); }
csn
Removes a value from the cache by its key. @param correlationId (optional) transaction id to trace execution through call chain. @param key a unique value key.
public void remove(String correlationId, String key) { synchronized (_lock) { // Get the entry CacheEntry entry = _cache.get(key); // Remove entry from the cache if (entry != null) { _cache.remove(key); _count--; } } }
csn
Method to handle all incoming DMF amqp messages. @param message incoming message @param type the message type @param tenant the contentType of the message @return a message if <null> no message is send back to sender
@RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue:dmf_receiver}", containerFactory = "listenerContainerFactory") public Message onMessage(final Message message, @Header(name = MessageHeaderKey.TYPE, required = false) final String type, @Header(name = MessageHeaderKey.TENANT, required = false) final String tenant) { return onMessage(message, type, tenant, getRabbitTemplate().getConnectionFactory().getVirtualHost()); }
csn
Check that an application file is ignored in .gitignore. @param string $filename @param string $suggestion
protected function checkIgnored($filename, $suggestion = null) { if (!file_exists($filename)) { return; } if (!$repositoryDir = $this->gitHelper->getRoot($this->appRoot)) { return; } $relative = $this->fsHelper->makePathRelative($filename, $repositoryDir); if (!$this->gitHelper->checkIgnore($relative, $repositoryDir)) { $suggestion = $suggestion ?: $relative; $this->stdErr->writeln("<comment>You should exclude this file using .gitignore:</comment> $suggestion"); } }
csn
def connect_output(self, node): """Connect another node to our output. This downstream node will automatically be triggered when we update our output. Args: node (SGNode): The node that should receive our output """ if len(self.outputs) == self.max_outputs:
raise TooManyOutputsError("Attempted to connect too many nodes to the output of a node", max_outputs=self.max_outputs, stream=self.stream) self.outputs.append(node)
csn_ccr
Encapsulates a string represented as markdown and plain text.
function Description(def) { if(typeof def === 'string') { this.parse(def); }else if(def && typeof def === 'object' && typeof def.txt === 'string' && typeof def.md === 'string') { this.md = def.md; this.txt = def.txt; }else{ throw new Error('invalid value for description'); } }
csn
Compute lagged correlation coefficient for two time series.
def corr_coeff(x1, x2, t, tau1, tau2): """Compute lagged correlation coefficient for two time series.""" dt = t[1] - t[0] tau = np.arange(tau1, tau2+dt, dt) rho = np.zeros(len(tau)) for n in range(len(tau)): i = np.abs(int(tau[n]/dt)) if tau[n] >= 0: # Positive lag, push x2 forward in time seg2 = x2[0:-1-i] seg1 = x1[i:-1] elif tau[n] < 0: # Negative lag, push x2 back in time seg1 = x1[0:-i-1] seg2 = x2[i:-1] seg1 = seg1 - seg1.mean() seg2 = seg2 - seg2.mean() rho[n] = np.mean(seg1*seg2)/seg1.std()/seg2.std() return tau, rho
csn
def get_validator_format(L): """ Format the LIPD data in the layout that the Lipd.net validator accepts. '_format' example: [ {"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...}, {"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...}, ... ] :param dict L: Metadata :return list _api_data: Data formatted for validator API """ _api_data = [] _j, _csvs = get_csv_from_metadata(L["dataSetName"], L) _j = rm_values_fields(copy.deepcopy(L)) _j = idx_name_to_num(_j) # All the filenames being processed _filenames = ["metadata.jsonld", "bagit.txt", "bag-info.txt", "manifest-md5.txt", "tagmanifest-md5.txt"]\ + [k for k,v in _csvs.items()] # Loop for each filename for filename in _filenames: # Create a blank template _file = {"type": "", "filenameFull": "", "filenameShort": "", "data": "", "pretty": ""} # filename, no path prefix # _short = os.path.basename(filename) _short = filename # Bagit files if filename.endswith(".txt"): _file = {"type": "bagit", "filenameFull": filename, "filenameShort": _short} # JSONLD files elif filename.endswith(".jsonld"): _file = {"type": "json", "filenameFull": filename, "filenameShort": _short, "data": _j} # CSV files
elif filename.endswith(".csv"): _cols_rows = {"cols": 0, "rows": 0} ensemble = is_ensemble(_csvs[_short]) # special case for calculating ensemble rows and columns if ensemble: _cols_rows = get_ensemble_counts(_csvs[_short]) # all other non-ensemble csv files. else: _cols_rows["cols"] = len(_csvs[_short]) for k, v in _csvs[_short].items(): _cols_rows["rows"] = len(v["values"]) break # take what we've gathered for this file, and add it to the list. _file = {"type": "csv", "filenameFull": filename, "filenameShort": _short, "data": _cols_rows} _api_data.append(_file) return _api_data
csn_ccr
Get the geometries of a table intersecting a given geometry. @param tableName the table name. @param intersectionGeometry the geometry to check, assumed in the same srid of the table geometry. @param prePostWhere an optional set of 3 parameters. The parameters are: a prefix wrapper for geom, a postfix for the same and a where string to apply. They all need to be existing if the parameter is passed. @return The list of geometries intersecting the geometry. @throws Exception
public List<Geometry> getGeometriesIn( String tableName, Geometry intersectionGeometry, String... prePostWhere ) throws Exception { List<Geometry> geoms = new ArrayList<Geometry>(); List<String> wheres = new ArrayList<>(); String pre = ""; String post = ""; String where = ""; if (prePostWhere != null && prePostWhere.length == 3) { if (prePostWhere[0] != null) pre = prePostWhere[0]; if (prePostWhere[1] != null) post = prePostWhere[1]; if (prePostWhere[2] != null) { where = prePostWhere[2]; wheres.add(where); } } GeometryColumn gCol = getGeometryColumnsForTable(tableName); String sql = "SELECT " + pre + gCol.geometryColumnName + post + " FROM " + tableName; if (intersectionGeometry != null) { intersectionGeometry.setSRID(gCol.srid); wheres.add(getSpatialindexGeometryWherePiece(tableName, null, intersectionGeometry)); } if (wheres.size() > 0) { sql += " WHERE " + DbsUtilities.joinBySeparator(wheres, " AND "); } IGeometryParser geometryParser = getType().getGeometryParser(); String _sql = sql; return execOnConnection(connection -> { try (IHMStatement stmt = connection.createStatement(); IHMResultSet rs = stmt.executeQuery(_sql)) { while( rs.next() ) { Geometry geometry = geometryParser.fromResultSet(rs, 1); geoms.add(geometry); } return geoms; } }); }
csn
public static function getTree( Bookboon $bookboon, array $blacklistedCategoryIds = [], int $depth = 2 ) : BookboonResponse { $bResponse = $bookboon->rawRequest('/categories', ['depth' => $depth]); $categories = $bResponse->getReturnArray(); if (count($blacklistedCategoryIds) !== 0) {
self::recursiveBlacklist($categories, $blacklistedCategoryIds); } $bResponse->setEntityStore( new EntityStore(Category::getEntitiesFromArray($categories)) ); return $bResponse; }
csn_ccr
public function has($name) { $keys = explode('.', $name); $lastBranch = $this->loadConfig(); foreach ($keys as $keyName) { if (isset($lastBranch[$keyName]) && (is_array($lastBranch) || is_object($lastBranch))) { if (is_array($lastBranch)) { $lastBranch = $lastBranch[$keyName]; } else {
$lastBranch = $lastBranch->$keyName; } } else { return false; } } return true; }
csn_ccr
public function createToc($text, $start = 2, $stop = 4) { $level = "$start-$stop"; $pattern = "#<(h[$level])([^>]*)>(.*)</h[$level]>#"; preg_match_all($pattern, $text, $matches, PREG_SET_ORDER); $toc = []; foreach ($matches as $val) { preg_match("#id=['\"]([^>\"']+)#", $val[2], $id); $id = isset($id[1]) ? $id[1] : null; $toc[] = [ "level" => isset($val[1])
? $val[1] : null, "title" => isset($val[3]) ? ltrim(strip_tags($val[3]), "#") : null, "id" => $id, ]; } return $toc; }
csn_ccr
Get class name by repository url. @param mixed $repo
private function getClass($repo) { $class = S::create( str_replace(['.'], ['-'], basename($repo, '.git')) )->camelize(); return ucfirst(trim($class)); }
csn