query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Unassign layout from display group. @param array|int $layoutId The Layout ID to unassign @return XiboDisplayGroup
public function unassignLayout($layoutId) { $this->getLogger()->info('Unassigning Layout ID ' . json_encode($layoutId) . ' From display Group ID ' . $this->displayGroupId); $this->doPost('/displaygroup/' . $this->displayGroupId . '/layout/unassign', [ 'layoutId' => $layoutId ...
csn
Renders the dashboard when the server is initially run. Usage description: The rendered HTML allows the user to select a project and the desired run. :return: Template to render, Object that is taken care by flask.
def index(): """ Renders the dashboard when the server is initially run. Usage description: The rendered HTML allows the user to select a project and the desired run. :return: Template to render, Object that is taken care by flask. """ # Reset current index values when the page is refreshe...
csn
func (i *Iterator) Close() error {
i.r.SetChunk(nil) return i.Error() }
csn_ccr
public function entryDataCleanup($entry_id, $data = null) { $where = is_array($entry_id) ? " `entry_id` IN (" .
implode(',', $entry_id) . ") " : " `entry_id` = '$entry_id' "; Symphony::Database()->delete('tbl_entries_data_' . $this->get('id'), $where); return true; }
csn_ccr
select 50 items randomnly from list python
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
cosqa
protected function fire($action, $params) { if(!isset($this->events[$action])){ throw new HandlerException('Action handler not exists', HandlerException::ACTION_HANDLER_NOT_EXISTS); } // prepare params array for handler // we provide a client library as a param for furth...
$callbackParams = new \ArrayObject($callbackParams, \ArrayObject::STD_PROP_LIST); // fire handlers for every event foreach($this->events[$action] as $e){ $result = call_user_func($e, $callbackParams); if(!$result){ break; } } }
csn_ccr
Requires that the file referred to by `backup_file` exists in the file system before running the decorated function.
def require_backup_exists(func): """ Requires that the file referred to by `backup_file` exists in the file system before running the decorated function. """ def new_func(*args, **kwargs): backup_file = kwargs['backup_file'] if not os.path.exists(backup_file): raise Resto...
csn
Create new attribute or get name of current attribute @param null|string $attribute @return EntityAttributeContainer|string
public function attr($attribute = null) { if ($this->isNull($attribute)) { return $this->attribute; } return $this->parent->attr($attribute); }
csn
Given a dotted Python path & an attribute name, imports the module & returns the attribute. If not found, raises ``UnknownCallableError``. Ex:: choice = import_attr('random', 'choice') :param module_name: The dotted Python path :type module_name: string :param attr_name: The attribu...
def import_attr(module_name, attr_name): """ Given a dotted Python path & an attribute name, imports the module & returns the attribute. If not found, raises ``UnknownCallableError``. Ex:: choice = import_attr('random', 'choice') :param module_name: The dotted Python path :type m...
csn
func NewPaperDocCreateArgs(ImportFormat *ImportFormat) *PaperDocCreateArgs { s :=
new(PaperDocCreateArgs) s.ImportFormat = ImportFormat return s }
csn_ccr
Tracks an event and associated properties through the Sift Science API. See https://siftscience.com/resources/references/events_api.html for valid $event values and $properties fields. @param string $event The type of the event to send. This can be either a reserved event name, like $transaction or $label or a custo...
public function track($event, $properties, $opts = array()) { $this->mergeArguments($opts, array( 'return_score' => false, 'return_action' => false, 'return_workflow_status' => false, 'force_workflow_run' => false, 'abuse_types' => array(), ...
csn
You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N. You can perform Q kinds of operations. The i-th operation is as follows: - Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1. Minimize the hamming distance between...
import sys input=sys.stdin.readline n=int(input()) b=list(map(int,input().split())) ope=[[] for i in range(n)] Q=int(input()) for i in range(Q): l,r=list(map(int,input().split())) ope[r-1].append(l-1) res=b.count(0) Data=[(-1)**((b[i]==1)+1) for i in range(n)] for i in range(1,n): Data[i]+=Data[i-1] Dat...
apps
public function setMeta(int $offset, int $fileSize, string $filePath, string $location = null) : self { $this->offset = $offset; $this->fileSize =
$fileSize; $this->filePath = $filePath; $this->location = $location; return $this; }
csn_ccr
func (k *kubernetesClient) DeleteOperator(appName string) (err error) { logger.Debugf("deleting %s operator", appName) operatorName := k.operatorName(appName) legacy := isLegacyName(operatorName) // First delete the config map(s). configMaps := k.client().CoreV1().ConfigMaps(k.namespace) configMapName := operat...
for _, c := range p.Spec.Containers { secretName := appSecretName(deploymentName, c.Name) if err := k.deleteSecret(secretName); err != nil { return errors.Annotatef(err, "deleting %s secret for container %s", appName, c.Name) } } // Delete operator storage volumes. volumeNames, err := k.deleteVolum...
csn_ccr
Unregister handler. @return boolean true if handler was unregistered (i.e. not already unregistered).
public function unRegister() { if (isset(static::$handlers[$this->handlerId])) { if (!is_null($this->getKey())) { static::$keys[$this->getKey()]--; } unset(static::$handlers[$this->handlerId]); return true; } return false; }
csn
// LogURI provides the raw logging URI
func LogURI(uri *url.URL) Creator { return func(_ string) (IO, error) { return &logURI{ config: Config{ Stdout: uri.String(), Stderr: uri.String(), }, }, nil } }
csn
public function createAtkVue($id, $component, $data = []) {
return $this->service->createAtkVue($id, $component, $data); }
csn_ccr
Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap
def unwrap_obj(obj): """ Gets the actual object from a decorated or wrapped function @obj: (#object) the object to unwrap """ try: obj = obj.fget except (AttributeError, TypeError): pass try: # Cached properties if obj.func.__doc__ == obj.__doc__: ...
csn
def get_all_user_policies(self, user_name, marker=None, max_items=None): """ List the names of the policies associated with the specified user. :type user_name: string :param user_name: The name of the user the policy is associated with. :type marker: string :param mark...
where the results are truncated. Set this to the value of the Marker element in the response you just received. :type max_items: int :param max_items: Use this only when paginating results to indicate the maximum number of...
csn_ccr
First APP1 marker in image markers.
def app1(self): """ First APP1 marker in image markers. """ for m in self._markers: if m.marker_code == JPEG_MARKER_CODE.APP1: return m raise KeyError('no APP1 marker in image')
csn
def fbank(wav_path, flat=True): """ Currently grabs log Mel filterbank, deltas and double deltas.""" (rate, sig) = wav.read(wav_path) if len(sig) == 0: logger.warning("Empty wav: {}".format(wav_path)) fbank_feat = python_speech_features.logfbank(sig, rate, nfilt=40) energy = extract_energy(...
delta_delta_feat = python_speech_features.delta(delta_feat, 2) all_feats = [feat, delta_feat, delta_delta_feat] if not flat: all_feats = np.array(all_feats) # Make time the first dimension for easy length normalization padding # later. all_feats = np.swapaxes(all_feats, 0, 1) ...
csn_ccr
public List<ICalendar> all() throws IOException { StreamReader reader = constructReader(); if (index != null) { reader.setScribeIndex(index); } try { List<ICalendar> icals = new ArrayList<ICalendar>(); ICalendar ical; while ((ical = reader.readNext()) != null) {
if (warnings != null) { warnings.add(reader.getWarnings()); } icals.add(ical); } return icals; } finally { if (closeWhenDone()) { reader.close(); } } }
csn_ccr
Constructs a Reflect base class. @exports ProtoBuf.Reflect.T @constructor @abstract @param {!ProtoBuf.Builder} builder Builder reference @param {?ProtoBuf.Reflect.T} parent Parent object @param {string} name Object name
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @e...
csn
Main update method called by the extension manager. @return string Messages
public function main() { ob_start(); $exectimeStart = microtime( true ); if( ( $result = $this->checkEnvironment() ) !== null ) { return $result; } try { \Aimeos\Aimeos\Setup::execute(); $output = ob_get_contents(); } catch( Exception $e ) { $output = ob_get_contents(); $output .= PH...
csn
func (b *Buffer) Bytes() []byte { switch { case b.written >= b.size && b.writeCursor == 0: return b.data case b.written > b.size: out := make([]byte, b.size) copy(out,
b.data[b.writeCursor:]) copy(out[b.size-b.writeCursor:], b.data[:b.writeCursor]) return out default: return b.data[:b.writeCursor] } }
csn_ccr
public Note add(String photoId, Note note) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_ADD); parameters.put("photo_id", photoId); Rectangle bounds = note.getBounds(); if (bounds != null) { ...
parameters.put("note_text", text); } Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } Element noteEl...
csn_ccr
def dashboard_import(self, name, fileobj): """dashboard_import Dashboard_Name, filename Uploads a dashboard template to the current user's dashboard tabs. UN-DOCUMENTED CALL: This function is not considered stable. """ data = self._upload(fileobj)
return self.raw_query('dashboard', 'importTab', data={ 'filename': data['filename'], 'name': name, })
csn_ccr
Returns a duplicates of an array.
public static Object duplicateArray(Object source) { int size = Array.getLength(source); Object newarray = Array.newInstance(source.getClass().getComponentType(), size); System.arraycopy(source, 0, newarray, 0, size); return newarray; }
csn
// NewChainDBRPC contains ChainDB and RPC client parameters. By default, // duplicate row checks on insertion are enabled. also enables rpc client
func NewChainDBRPC(chaindb *ChainDB, cl *rpcclient.Client) (*ChainDBRPC, error) { return &ChainDBRPC{chaindb, cl}, nil }
csn
func (m addrMap) Ranges(b32 string) (nets addrList) { ranges, ok := m[b32] if ok { for _, r := range ranges {
_, cidr, err := net.ParseCIDR(r) if err == nil { nets = append(nets, cidr) } } } else { nets = nil } return }
csn_ccr
public static String toCNF(INode in, String formula) throws ContextClassifierException { PEParser parser = new PEParser(); CNFTransformer transformer = new CNFTransformer(); String result = formula; if ((formula.contains("&") && formula.contains("|")) || formula.contains("~")) { ...
tmpFormula = tmpFormula.replace("~", "NOT"); tmpFormula = "(" + tmpFormula + ")"; if (!tmpFormula.isEmpty()) { tmpFormula = tmpFormula.replace('.', 'P'); Sentence f = (Sentence) parser.parse(tmpFormula); Sentence cnf = transformer.tran...
csn_ccr
func (r *Redshift) GetTableFromConf(f s3filepath.S3File) (*Table, error) { var tempSchema map[string]Table log.Printf("Parsing file: %s", f.ConfFile) reader, err := pathio.Reader(f.ConfFile) if err != nil { return nil, fmt.Errorf("error opening conf file: %s", err) } data, err := ioutil.ReadAll(reader) if err...
multiple tables in a conf file t, ok := tempSchema[f.Table] if !ok { return nil, fmt.Errorf("can't find table in conf") } if t.Meta.Schema != f.Schema { return nil, fmt.Errorf("mismatched schema, conf: %s, file: %s", t.Meta.Schema, f.Schema) } if t.Meta.DataDateColumn == "" { return nil, fmt.Errorf("data d...
csn_ccr
public function parseOnTableColumns($item, array &$outputRow) { if (method_exists($item, 'presenter')) { $item = $item->presenter(); } $columns = $this->columnFactory->getColumns(); $includedColumns = $this->columnFactory->getIncludedColumns($this->fieldFactory->...
'rendered' => $columns[$field]->renderOutput($attributeValue, $item), ); } //otherwise it's likely the primary key column which wasn't included (though it's needed for identification purposes) else { $outputRow[$field] = array( ...
csn_ccr
Start the tracker thread.
public void start(final boolean startPeerCleaningThread) throws IOException { logger.info("Starting BitTorrent tracker on {}...", getAnnounceUrl()); connection = new SocketConnection(new ContainerServer(myTrackerServiceContainer)); List<SocketAddress> tries = new ArrayList<SocketAddress>() {{ ...
csn
Make sure the space is properly set between long command options and short command options @param {Integer} the longest length of the command's options @param {Integer} the character length of the given option
public static function getSpacer($lengthLong,$itemLongLength) { $i = 0; $spacer = " "; $spacerLength = $lengthLong - $itemLongLength; while ($i < $spacerLength) { $spacer .= " "; $i++; } return $spacer; }
csn
func (d *Duration) Set(s string) error { if v, err := strconv.ParseInt(s, 10, 64); err == nil { *d = Duration(time.Duration(v) * time.Second)
return nil } v, err := time.ParseDuration(s) *d = Duration(v) return err }
csn_ccr
attempt to retrieve message from queue head
public Object tryGet() { Object o = null; if (head != null) { o = head.getContents(); head = head.getNext(); count--; if (head == null) { tail = null; count = 0; } } return o; }
csn
// FindStr in a error.
func FindStr(ie interface{}, sub string) int { if ie == nil || sub == "" { return -1 } switch val := ie.(type) { case *Error: if val == nil { return -1 } return val.FindStr(sub) default: panic("invalid type") } }
csn
public SpoutDeclarer setSpout(String id, IControlSpout spout) {
return setSpout(id, spout, null); }
csn_ccr
def convertwaiveredfits(waiveredObject, outputFileName=None, forceFileOutput=False, convertTo='multiExtension', verbose=False): """ Convert the input waivered FITS object to various formats. The default ...
name replaced with the character `h` in multi-extension FITS format. Default: False convertTo target conversion type Default: 'multiExtension' verbose provide verbose output ...
csn_ccr
def namespace(self, **context): """ Returns the namespace that should be used for this schema, when specified. :return: <str> """ context = orb.Context(**context) if context.forceNamespace:
return context.namespace or self.__namespace else: return self.__namespace or context.namespace
csn_ccr
function parseRemoteApplications(response) { let entities = {}; Object.keys(response).forEach(key
=> { entities[key] = parseRemoteApplication(response[key]); }); return entities; }
csn_ccr
// evalAnchor evaluates a date expression relative to an anchor time.
func EvalAnchor(anchor time.Time, expression string) (time.Time, error) { if len(expression) < 3 { return zero, fmt.Errorf("Expression too short: %s", expression) } if strings.HasPrefix(expression, "now") { expression = expression[3:] } if expression == "" { return time.Now(), nil } numStr, unit := expr...
csn
function(sbm) { return _.sum(_.map(sbm.data, function (ar)
{ return ar.length })) }
csn_ccr
def add_url_parameters(url, parameters): """ Add url parameters to URL. """ scheme, netloc, path, query_string, fragment = urlsplit(url) query = parse_qs(query_string)
query.update(parameters) return urlunsplit((scheme, netloc, path, urlencode(query), fragment))
csn_ccr
def strip_bewit(url): """ Strips the bewit parameter out of a url. Returns (encoded_bewit, stripped_url) Raises InvalidBewit if no bewit found. :param url: The url containing a bewit parameter :type url: str """ m = re.search('[?&]bewit=([^&]+)', url) if not m:
raise InvalidBewit('no bewit data found') bewit = m.group(1) stripped_url = url[:m.start()] + url[m.end():] return bewit, stripped_url
csn_ccr
Add entity to the batch deletion @param EntityInterface $entity @throws \Aws\DynamoDb\Exception\DynamoDBException
public function deleteBatch(EntityInterface $entity) { if (is_null($this->deleteBatch)) { $this->deleteBatch = WriteRequestBatch::factory($this->dynamoDb); } $this->deleteBatch->add(new DeleteRequest($this->formatKeyCondition($entity), $this->getEntityTable($entity))); }
csn
Sort the items. @param {Array} items @returns {Array}
function(items) { return items.sort(function(a, b) { return a.title.localeCompare(b.title); }); }
csn
Set the parameters. @param config Parameterization
public void setParameters(Parameterization config) { // Clear errors after each step, so they don't consider themselves failed // because of earlier errors. logTab.setParameters(config); // config.clearErrors(); inputTab.setParameters(config); // config.clearErrors(); algTab.setParameters(co...
csn
def copy_function(func, name=None): """Copy a function object with different name. Args: func (function): Function to be copied. name (string, optional): Name of the new function. If not spacified, the same name of `func` will be used. Returns: newfunc (function): New f...
code.co_names, code.co_varnames, code.co_filename, newname, code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars, ) newfunc = FunctionType( newcode, func.__globals__, newname, func.__defaults__, ...
csn_ccr
Fires on receipt of payment received window message
def payment_sent order_number = session[:order_number] session[:order_number] = nil order = Spree::Order.find_by_number(order_number) || raise(ActiveRecord::RecordNotFound) redirect_to spree.order_path(order), :notice => Spree.t(:order_processed_successfully) end
csn
@Override protected void onThresholdReached () throws IOException { FileOutputStream aFOS = null; try { aFOS = new FileOutputStream (m_aOutputFile); m_aMemoryOS.writeTo (aFOS);
m_aCurrentOS = aFOS; // Explicitly close the stream (even though this is a no-op) StreamHelper.close (m_aMemoryOS); m_aMemoryOS = null; } catch (final IOException ex) { StreamHelper.close (aFOS); throw ex; } }
csn_ccr
func (we *WorkflowExecutor) monitorAnnotations(ctx context.Context) <-chan struct{} { log.Infof("Starting annotations monitor") // Create a channel to listen for a SIGUSR2. Upon receiving of the signal, we force reload our annotations // directly from kubernetes API. The controller uses this to fast-track notificat...
annotationUpdateCh <- struct{}{} we.setExecutionControl() case <-annotationChanges: log.Infof("%s updated", we.PodAnnotationsPath) err := we.LoadExecutionControl() if err != nil { log.Warnf("Failed to reload execution control from annotations: %v", err) continue } if we.Executi...
csn_ccr
Update the given picker to the helper if it's different from the current one.
private void maybeUpdatePicker(ConnectivityState state, RoundRobinPicker picker) { // Discard the new picker if we are sure it won't make any difference, in order to save // re-processing pending streams, and avoid unnecessary resetting of the pointer in // RoundRobinPicker. if (picker.dropList.equals(c...
csn
Create a ValidationToken from an HTTP Request. @param accountSid Twilio Account SID @param credentialSid Twilio Credential SID @param signingKeySid Twilio Signing Key SID @param privateKey Private Key @param request HTTP Request @param signedHeaders Headers to sign @throws IOException when unable to generate @r...
public static ValidationToken fromHttpRequest( String accountSid, String credentialSid, String signingKeySid, PrivateKey privateKey, HttpRequest request, List<String> signedHeaders ) throws IOException { Builder builder = new Builder(accountSid, credentialSid,...
csn
func (p *Pool) pingAndPurgeIfNeeded(other *Pool) error { ping := redisPool.Get() pong := redis.PubSubConn{redisPool.Get()} // Listen for pongs by subscribing to the other pool's pong key pong.Subscribe(other.pongKey()) // Ping the other pool by publishing to its ping key ping.Do("PUBLISH", other.pingKey(), 1) //...
err := reply.(error) errChan <- err return } } }() timeout := time.After(p.config.StaleTimeout) select { case <-pongChan: // The other pool responded with a pong return nil case err := <-errChan: // Received an error from the pubsub conn return err case <-timeout: // The pool is conside...
csn_ccr
// FlagStr returns the currently set flag header
func (m *HeaderCtxFlag) FlagStr() string { m.mu.RLock() ret := m.expectedVal m.mu.RUnlock() return ret }
csn
def group_files_by_size(fileslist, multi): # pragma: no cover ''' Cluster files into the specified number of groups, where each groups total size is as close as possible to each other. Pseudo-code (O(n^g) time complexity): Input: number of groups G per cluster, list of files F with respective sizes - ...
fgrouped[i] = [] big_key, big_value = flord.popitem(0) fgrouped[i].append([big_key]) for j in xrange(multi-1): cluster = [] if not flord: break child_key, child_value = flord.popitem(0) cluster.append(child_key) if child_value == big...
csn_ccr
public function isValid($value) { if (! is_array($value) || !isset($value['mode'])
|| (!isset($value['content']) && !isset($value['attributes'])) ){ return false; } return true; }
csn_ccr
u"""Executes XPath query on the ``lxml`` object and returns a correct object. :param str path: XPath string e.g., 'cars'/'car' :param str/dict namespaces: e.g., 'exslt', 're' or ``{'re': "http://exslt.org/regular-expressions"}`` :param bool regexp: if ``True`` and no namespaces is ...
def xpath( self, path, namespaces=None, regexp=False, smart_strings=True, single_use=False, ): u"""Executes XPath query on the ``lxml`` object and returns a correct object. :param str path: XPath string e.g., 'cars'/'car' ...
csn
// Create a new domain.
func (s *Service) DomainCreate(ctx context.Context, appIdentity string, o DomainCreateOpts) (*Domain, error) { var domain Domain return &domain, s.Post(ctx, &domain, fmt.Sprintf("/apps/%v/domains", appIdentity), o) }
csn
Handler for showing keyboard or mouse page with day and total links.
def inputindex(input): """Handler for showing keyboard or mouse page with day and total links.""" stats = {} countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last" tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos") for table in tables: ...
csn
DELETE DIRECTORIES IN CHILDREN @param string $arg @return bool
public function deleteDirectory($arg) { foreach (func_get_args() as $name) { (new static($this->fullName.'/'.$name))->delete(); } return true; }
csn
def artifacts(self): """ Property for accessing artifact manager of the current job. :return: instance of :class:`yagocd.resources.artifact.ArtifactManager` :rtype: yagocd.resources.artifact.ArtifactManager """ return ArtifactManager( session=self._session, ...
pipeline_name=self.pipeline_name, pipeline_counter=self.pipeline_counter, stage_name=self.stage_name, stage_counter=self.stage_counter, job_name=self.data.name )
csn_ccr
def flat_data(self): """ Function to pass our modified values to the original ones """ def flat_field(value): """ Flat item """ try: value.flat_data()
return value except AttributeError: return value modified_data = self.__modified_data__ if self.__modified_data__ is not None else self.__original_data__ if modified_data is not None: self.__original_data__ = [flat_field(value) for value in modified_...
csn_ccr
Unpack an unsigned pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypack.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``target``. endian(:class:`~pwnypack.target.Target.Endian`):...
def U(data, bits=None, endian=None, target=None): """ Unpack an unsigned pointer for a given target. Args: data(bytes): The data to unpack. bits(:class:`pwnypack.target.Target.Bits`): Override the default word size. If ``None`` it will look at the word size of ``targ...
csn
def get_or_deploy_token(runner) -> Tuple[ContractProxy, int]: """ Deploy or reuse """ token_contract = runner.contract_manager.get_contract(CONTRACT_CUSTOM_TOKEN) token_config = runner.scenario.get('token', {}) if not token_config: token_config = {} address = token_config.get('address') ...
log.debug( "Reusing token", address=to_checksum_address(address), name=token_ctr.contract.functions.name().call(), symbol=token_ctr.contract.functions.symbol().call(), ) return token_ctr, block token_id = uuid.uuid4() now = datetime.now() n...
csn_ccr
Push a step to the end of a pipeline
private function pushPipelineStep($name, $stepConfig) { $lastStep = $this->Steps()->sort("Order DESC")->first(); $order = $lastStep ? $lastStep->Order + 1 : 1; return $this->generateStep($name, $stepConfig, $order); }
csn
Get index for new entry.
def inc(self): """Get index for new entry.""" self.lock.acquire() cur = self.counter self.counter += 1 self.lock.release() return cur
csn
python load rds file
def load_graph_from_rdf(fname): """ reads an RDF file into a graph """ print("reading RDF from " + fname + "....") store = Graph() store.parse(fname, format="n3") print("Loaded " + str(len(store)) + " tuples") return store
cosqa
// Go runs fn in its own goroutine, but does not wait for it to complete. // Call Err or Errs to wait for all the goroutines to complete.
func (g *Group) Go(fn func() error) { g.wg.Add(1) go func() { err := fn() if err != nil { g.mu.Lock() g.errs = append(g.errs, err) g.mu.Unlock() } g.wg.Done() }() }
csn
func (c LoginUiClient) DisplayResetProgress(ctx context.Context, __arg DisplayResetProgressArg)
(err error) { err = c.Cli.Call(ctx, "keybase.1.loginUi.displayResetProgress", []interface{}{__arg}, nil) return }
csn_ccr
public static SanitizedContent filterTelUri(SoyValue value) { value = normalizeNull(value);
return filterTelUri(value.coerceToString()); }
csn_ccr
public function footer() { global $CFG, $DB, $PAGE; // Give plugins an opportunity to touch the page before JS is finalized. $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php'); foreach ($pluginswithfunction as $plugins) { foreach ($plugins as $funct...
} $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer); // Only show notifications when we have a $PAGE context id. if (!empty($PAGE->context->id)) { $this->page->requires->js_call_amd('core/notification', 'init', array( $PAGE...
csn_ccr
public function index() { // $options = $this->getParams('offset', 'limit', 'includes', 'order_by'); $categories = Subbly::api('subbly.category')->all(); return $this->jsonResponse(array( 'categories' => $this->presenter->collection($categories), ));
// return $this->jsonCollectionResponse(array( // 'categories' => $this->presenter->collection($categories) // )); }
csn_ccr
def combine_cache_keys(cls, cache_keys): """Returns a cache key for a list of target sets that already have cache keys. This operation is 'idempotent' in the sense that if cache_keys contains a single key then that key is returned. Note that this operation is commutative but not associative. We use t...
""" if len(cache_keys) == 1: return cache_keys[0] else: combined_id = Target.maybe_readable_combine_ids(cache_key.id for cache_key in cache_keys) combined_hash = hash_all(sorted(cache_key.hash for cache_key in cache_keys)) return cls(combined_id, combined_hash)
csn_ccr
Cast value to a object @return object|mixed
protected function castToObject($value) { if (is_scalar($value) || is_resource($value)) { $value = $this->dontCast($value); } return (object)$value; }
csn
Open external links in browser and internal links in the webview
def acceptNavigationRequest(self, url, kind, is_main_frame): """Open external links in browser and internal links in the webview""" ready_url = url.toEncoded().data().decode() is_clicked = kind == self.NavigationTypeLinkClicked if is_clicked and self.root_url not in ready_url: ...
csn
def deleteSNPs(setName) : """deletes a set of polymorphisms""" con = conf.db try : SMaster = SNPMaster(setName = setName) con.beginTransaction() SNPType = SMaster.SNPType con.delete(SNPType, 'setName = ?', (setName,)) SMaster.delete() con.endTransaction() except KeyError : raise KeyError("Can't delete...
i can't find it in SNPMaster, maybe there's not set by that name" % setName) #~ printf("can't delete the setName %s because i can't find it in SNPMaster, maybe there's no set by that name" % setName) return False return True
csn_ccr
def insertBefore(self, newchild, refchild): """ Insert a new child node before an existing child. It must be the case that refchild is a child of this node; if not, ValueError is raised. newchild is returned. """ for i, childNode in enumerate(self.childNodes):
if childNode is refchild: self.childNodes.insert(i, newchild) newchild.parentNode = self self._verifyChildren(i) return newchild raise ValueError(refchild)
csn_ccr
Converts input to a Shape. Args: x: Shape, str, or None. Returns: Shape or None. Raises: ValueError: If x cannot be converted to a Shape.
def convert_to_shape(x): """Converts input to a Shape. Args: x: Shape, str, or None. Returns: Shape or None. Raises: ValueError: If x cannot be converted to a Shape. """ if x is None: return None if isinstance(x, Shape): return x if isinstance(x, str): x = _parse_string_to_lis...
csn
func NewScanKeys(m libkb.MetaContext) (sk *ScanKeys, err error) { sk = &ScanKeys{ keyOwners: make(map[uint64]*libkb.User), MetaContextified: libkb.NewMetaContextified(m), } defer m.Trace("NewScanKeys", func() error { return err })() var loggedIn bool loggedIn, err = isLoggedInWithError(m) if err != n...
then load their local keys, and their synced secret key: synced, err := sk.me.GetSyncedSecretKey(m) if err != nil { return nil, fmt.Errorf("getsyncedsecret err: %s", err) } ring, err := m.ActiveDevice().Keyring(m) if err != nil { return nil, err } err = sk.coalesceBlocks(m, ring, synced) if err != nil { ...
csn_ccr
Register events for this service provider. @return void
public function registerEvents() { //Store the Kinvey auth token in the user's session, and clear it on logout. Event::listen('auth.login', function($user) { Session::put('kinvey', $user->_kmd['authtoken']); }); Event::listen('auth.logout', function($user) { Session::forget('kinvey'); }); }
csn
public static <S extends Storable> SyntheticStorableReferenceAccess<S> getIndexAccess(StorableIndex<S> index) throws SupportException { // Strip out index property not related to its identity. index = index.clustered(false); synchronized (cCache) { Synthe...
new SyntheticStorableReferenceBuilder<S>(type, index.isUnique()); for (int i=0; i<index.getPropertyCount(); i++) { StorableProperty<S> source = index.getProperty(i); builder.addKeyProperty(source.getName(), index.getPropertyDirection(i)); } ...
csn_ccr
func (o *queryM2M) Clear() (int64, error) { fi := o.fi return
o.qs.Filter(fi.reverseFieldInfo.name, o.md).Delete() }
csn_ccr
Adds a JSON encoded response for a request with the provided URL. @param {string} url The requested URL. @param {string|function} response The returned response as string or callback. @param {string} [method] The HTTP method (e.g. GET, POST), default is GET. @param {int} [status] The desired status, default is 200. @p...
function(url, response, method, status, headers) { var aHeaders = headers || []; aHeaders.push({ "name": "Content-Type", "value": "application/json;charset=utf-8" }); this.addResponse(url, response, method, status, aHeaders); }
csn
Add a new source to the ROI model from a dictionary or an existing source object. Parameters ---------- name : str src_dict : dict or `~fermipy.roi_model.Source` Returns ------- src : `~fermipy.roi_model.Source`
def create_source(self, name, src_dict, build_index=True, merge_sources=True, rescale=True): """Add a new source to the ROI model from a dictionary or an existing source object. Parameters ---------- name : str src_dict : dict or `~fermipy.roi_mod...
csn
protected function getPluralIndex($domain, $n, $fallback) { //Not loaded domain or translation, use a fallback if (!isset($this->plurals[$domain]) || $fallback === true) { return $n == 1 ? 0 : 1; } if (!isset($this->plurals[$domain]['function'])) { $code = se...
} if ($this->plurals[$domain]['count'] <= 2) { return call_user_func($this->plurals[$domain]['function'], $n) ? 1 : 0; } return call_user_func($this->plurals[$domain]['function'], $n); }
csn_ccr
function getLeftEdge(index, cell) { return { index: index,
x: editor.dom.getPos(cell).x }; }
csn_ccr
public RedwoodConfiguration captureStdout(){ tasks.add(new Runnable() { public void run()
{ Redwood.captureSystemStreams(true, false); } }); return this; }
csn_ccr
public function getConnectionString(){ $connection_string = array(); $type = $this->getType(); array_push($connection_string, $type); if($type == self::SQLite){ $filename = 'db.sqlite'; if(isset($this->properties['filename'])) $filename = $this->properties['...
array_push($connection_string, ';dbname='); array_push($connection_string, (isset($this->properties['name']))? $this->properties['name']:null ); } array_push($connection_string, ';charset='); array_push($connection_string, $this->getCharse...
csn_ccr
private static OIdentifiable linkToStream(final StringBuilder buffer, final ORecordSchemaAware<?> iParentRecord, Object iLinked) { if (iLinked == null) // NULL REFERENCE return null; OIdentifiable resultRid = null; ORID rid; final ODatabaseRecord database = ODatabaseRecordThreadLoc...
final OClass schemaClass = ((ODocument) iLinkedRecord).getSchemaClass(); database.save(iLinkedRecord, schemaClass != null ? database.getClusterNameById(schemaClass.getDefaultClusterId()) : null); } else // STORE THE TRAVERSED OBJECT TO KNOW THE RECORD ID. CALL THIS VERSION TO AVOID C...
csn_ccr
Deletes cache entries that match a request. @param array $request Request to delete from cache @return int
public function delete($request) { $entriesCleared = 0; if ($this->exists($request)) { foreach ($this->entries as $entry) { if ($entry['cacheData']) { // delete each results of the manifest if ($this->cache->delete($entry['cacheDat...
csn
func NewCmdLogProfile(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command { return cli.Command{ Name: "profile", Usage: "Analyze timed traces from logs.", Action: func(c *cli.Context) {
cl.ChooseCommand(&CmdLogProfile{Contextified: libkb.NewContextified(g)}, "profile", c) }, Flags: []cli.Flag{ cli.StringFlag{ Name: "p, path", Usage: "Path of logfile to process.", }, }, } }
csn_ccr
Get a flat array of all the user IDs. @param string $status (Default: 'ACTIVE'). @return string[]
public function all($status = 'ACTIVE') { $ids = [$this->data->primary_id]; foreach ($this->data->user_identifier as $identifier) { if (is_null($status) || $identifier->status == $status) { $ids[] = $identifier->value; } } return $ids; }
csn
Reads the genotypes by using the given chromosome reader. @see Genotypes#read(InputStream, Reader) @param <A> the allele type @param <G> the gene type @param <C> the chromosome type @param in the input stream to read the genotype from @param chromosomeReader the used chromosome reader @return a genotype by using the ...
public static < A, G extends Gene<A, G>, C extends Chromosome<G> > List<io.jenetics.Genotype<G>> read(final InputStream in, final Reader<? extends C> chromosomeReader) throws XMLStreamException { return Genotypes.read(in, chromosomeReader); }
csn
public static void trackTrustedMultifactorAuthenticationAttribute( final Authentication authn, final String attributeName) { val newAuthn = DefaultAuthenticationBuilder.newInstance(authn)
.addAttribute(attributeName, Boolean.TRUE) .build(); LOGGER.debug("Updated authentication session to remember trusted multifactor record via [{}]", attributeName); authn.update(newAuthn); }
csn_ccr
def _ReadAttributeValueDateTime( self, attribute_values_data, record_offset, attribute_values_data_offset, attribute_value_offset): """Reads a date time attribute value. Args: attribute_values_data (bytes): attribute values data. record_offset (int): offset of the record relative to the...
record_offset + attribute_values_data_offset + attribute_value_offset) attribute_value_offset -= attribute_values_data_offset + 1 attribute_value_data = attribute_values_data[attribute_value_offset:] try: date_time_attribute_value = self._ReadStructureFromByteStream( attribute_value_data,...
csn_ccr
Sets the attributes hash from a HTTPResponse object from JIRA if it is not nil or is not a json response.
def set_attrs_from_response(response) unless response.body.nil? || (response.body.length < 2) json = self.class.parse_json(response.body) set_attrs(json) end end
csn
public function toXML(DOMElement $parent) : DOMElement { $e = parent::toXML($parent); if (is_bool($this->WantAuthnRequestsSigned)) { $e->setAttribute('WantAuthnRequestsSigned', $this->WantAuthnRequestsSigned ? 'true' : 'false'); } foreach ($this->SingleSignOnService as ...
$ep->toXML($e, 'md:AssertionIDRequestService'); } Utils::addStrings($e, Constants::NS_MD, 'md:AttributeProfile', false, $this->AttributeProfile); foreach ($this->Attribute as $a) { $a->toXML($e); } return $e; }
csn_ccr