query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments
def response(self, component_id, component=None, **kwargs): """Add a response which can be referenced. :param str component_id: ref_id to use as reference :param dict component: response fields :param dict kwargs: plugin-specific arguments """ if component_id in self._re...
csn
Ends measuring a cache request. @param string $type Request type, either a miss or a hit @param string $hash The hash of the cache request @param array $tags The cache request tags @param string $sql The underlying SQL query string @param array $parameters The SQL query parame...
public function endMeasuring($type, $hash, $tags, $sql, $parameters) { $name = '[' . ucfirst($type) . '] ' . $sql; $endTime = microtime(true); $params = [ 'hash' => $hash, 'tags' => $tags, 'parameters' => $parameters, ]; $thi...
csn
def apply(self, func, keep_attrs=None, args=(), **kwargs): """Apply a function over the data variables in this dataset. Parameters ---------- func : function Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in th...
foo (dim_0, dim_1) float64 -0.3751 -1.951 -1.945 0.2948 0.711 -0.3948 bar (x) int64 -1 2 >>> ds.apply(np.fabs) <xarray.Dataset> Dimensions: (dim_0: 2, dim_1: 3, x: 2) Dimensions without coordinates: dim_0, dim_1, x Data variables: foo (dim...
csn_ccr
add two polynomials using function in python
def __add__(self, other): """Left addition.""" return chaospy.poly.collection.arithmetics.add(self, other)
cosqa
A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { 'param': {'value': <match type: 1=first, 2=last, 3=every>}, ...
def asyncPipeStrreplace(context=None, _INPUT=None, conf=None, **kwargs): """A string module that asynchronously replaces text. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or strings conf : { 'RULE': [ { ...
csn
def set_param(self, param, value): '''Set a parameter in this configuration set.''' self.data[param] = value
self._object.configuration_data = utils.dict_to_nvlist(self.data)
csn_ccr
public static function isValidError(string $name, $node = null): ?ValidationException { if (\strlen($name) > 1 && $name{0} === '_' && $name{1} === '_') { return new ValidationException( sprintf('Name "%s" must not begin with "__", which is reserved by GraphQL introspection.', $na...
return new ValidationException( sprintf('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "%s" does not.', $name), $node instanceof NodeInterface ? [$node] : null ); } return null; }
csn_ccr
python c structure to dict
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
cosqa
public static Collection<Column> getPrimaryKeyColumns(Table catalogTable) { Collection<Column> columns = new ArrayList<>(); Index catalog_idx = null; try { catalog_idx = CatalogUtil.getPrimaryKeyIndex(catalogTable);
} catch (Exception ex) { // IGNORE return (columns); } assert(catalog_idx != null); for (ColumnRef catalog_col_ref : getSortedCatalogItems(catalog_idx.getColumns(), "index")) { columns.add(catalog_col_ref.getColumn()); } return (columns);...
csn_ccr
Create the Authentication header @return string @throws \Akamai\Open\EdgeGrid\Authentication\Exception\SignerException\InvalidSignDataException @link https://developer.akamai.com/introduction/Client_Auth.html
public function createAuthHeader() { if ($this->timestamp === null) { $this->setTimestamp(); } if (!$this->timestamp->isValid()) { throw new InvalidSignDataException('Timestamp is invalid. Too old?'); } if ($this->nonce === null) { $this-...
csn
// Update changes the passphrase of an existing account.
func (ks *KeyStore) Update(a accounts.Account, passphrase, newPassphrase string) error { a, key, err := ks.getDecryptedKey(a, passphrase) if err != nil { return err } return ks.storage.StoreKey(a.URL.Path, key, newPassphrase) }
csn
Callback for the event onMouseClickClose raised by the popup. @protected
function (evt) { var domEvent = evt.domEvent; if (domEvent.target == this.getTextInputField()) { // Clicking on the input should directly give the focus to the input. // Setting this boolean to false prevents the focus from being given // to this._...
csn
private function resolveAuthenticator(TokenInterface $token) { foreach ($this->authenticators as $authenticator) { if ($authenticator->supports($token)) {
return $authenticator; } } return false; }
csn_ccr
func (p ResourcePersistence) SetCharmStoreResource(id, applicationID string, res charmresource.Resource, lastPolled time.Time) error { if err := res.Validate(); err != nil { return errors.Annotate(err, "bad resource") } csRes := charmStoreResource{ Resource: res, id: id, applicationID: appli...
// This is an "upsert". var ops []txn.Op switch attempt { case 0: ops = newInsertCharmStoreResourceOps(csRes) case 1: ops = newUpdateCharmStoreResourceOps(csRes) default: // Either insert or update will work so we should not get here. return nil, errors.New("setting the resource failed") } ...
csn_ccr
Handles a line received from the prompt. \param string $line A single line of text received from the prompt, with the end-of-line sequence stripped.
protected function handleMessage($line) { $pos = strpos($line, ' '); if ($pos === false) { return; } $pattern = preg_quote(substr($line, 0, $pos), '@'); $pattern = strtr($pattern, array('\\?' => '.?', '\\*' => '.*')); $line = substr($line, $po...
csn
Register a job for executing in batch. @param string $identifier Unique identifier of the job. @param callable $callback Callback that accepts the job $idNum and returns a JobInterface instance. @return void
public function registerJob($identifier, $callback) { if (array_key_exists($identifier, $this->identifierToId)) { $idNum = $this->identifierToId[$identifier]; } else { $idNum = count($this->identifierToId) + 1; $this->idToIdentifier[$idNum] = $identifier; ...
csn
// newVserver returns an initialised vserver struct.
func newVserver(e *Engine) *vserver { return &vserver{ engine: e, ncc: ncclient.NewNCC(e.config.NCCSocket), fwm: make(map[seesaw.AF]uint32), active: make(map[seesaw.IP]bool), lbVservers: make(map[seesaw.IP]*seesaw.Vserver), vips: make(map[seesaw.VIP]bool), overrideChan: make(chan se...
csn
// ParseAnnotationsCPUWeight searches `s.Annotations` for the CPU annotation. If // not found searches `s` for the Windows CPU section. If neither are found // returns `def`.
func ParseAnnotationsCPUWeight(s *specs.Spec, annotation string, def int32) int32 { if m := parseAnnotationsUint64(s.Annotations, annotation, 0); m != 0 { return int32(m) } if s.Windows != nil && s.Windows.Resources != nil && s.Windows.Resources.CPU != nil && s.Windows.Resources.CPU.Shares != nil && *s.Win...
csn
protected function toRtf() { $rtf = ''; // if a word exists if ($this->word) { // if the word is ignored if ($this->isIgnored) { // prepend the ignored control symbol
$rtf = '\\*'; } // append the word and its parameter $rtf .= "\\{$this->word}{$this->parameter}"; // if the word is space-delimited, append the space if ($this->isSpaceDelimited) { $rtf .= ' '; } } return $rtf; }
csn_ccr
def merge_record_extra(record, target, reserved): """ Merges extra attributes from LogRecord object into target dictionary :param record: logging.LogRecord :param target: dict to update :param reserved: dict or list with reserved keys to skip """ for key, value in record.__dict__.items(): ...
keys if (key not in reserved and not (hasattr(key, "startswith") and key.startswith('_'))): target[key] = value return target
csn_ccr
public function info($identities) { $ids = []; $names = []; if (is_array($identities)) { foreach ($identities as $identity) { if (gettype($identity) === 'integer') { // it's the id $ids[] = $identity; } else { // the summoner name $names[] = $identity; } }...
// it's the id $ids = $this->infoByIds($ids); } if (count($names) > 0) { // the summoner name $names = $this->infoByNames($names); } $summoners = $ids + $names; if (count($summoners) == 1) { return reset($summoners); } else { return $summoners; } }
csn_ccr
Retrieve the pageId based on the pageRequest information, as well as the url map. As a default, the homePageId is returned @param {aria.pageEngine.CfgBeans:PageRequest} pageRequest @return {String} the pageId @private
function (pageRequest) { var map = this.__urlMap.urlToPageId, pageId = pageRequest.pageId, url = pageRequest.url; if (pageId) { return pageId; } if (url) { var returnUrl = map[url] || map[url + "/"] || map[url.replace(/\/$/, "")]; ...
csn
Format decimal numbers in this locale.
private static void decimal(CLDR.Locale locale, String[] numbers, DecimalFormatOptions opts) { for (String num : numbers) { BigDecimal n = new BigDecimal(num); StringBuilder buf = new StringBuilder(" "); NumberFormatter fmt = CLDR.get().getNumberFormatter(locale); fmt.formatDecimal(n, buf, ...
csn
Matches route produces configurer and Accept-header in an incoming provider @param route route configurer @param request incoming provider object @return returns {@code true} if the given route has produces Media-Type one of an Accept from an incoming provider
public static boolean matchProduces(InternalRoute route, InternalRequest<?> request) { if (nonEmpty(request.getAccept())) { List<MediaType> matchedAcceptTypes = getAcceptedMediaTypes(route.getProduces(), request.getAccept()); if (nonEmpty(matchedAcceptTypes)) { request.s...
csn
Gets the rating information for this video, if available. The rating is returned as an array containing the keys 'average' and 'numRaters'. null is returned if the rating information is not available. @return array|null The rating information for this video
public function getVideoRatingInfo() { if ($this->getRating() != null) { $returnArray = array(); $returnArray['average'] = $this->getRating()->getAverage(); $returnArray['numRaters'] = $this->getRating()->getNumRaters(); return $returnArray; } else { ...
csn
def _encrypt_data_key(self, data_key, algorithm, encryption_context=None): """Encrypts a data key and returns the ciphertext. :param data_key: Unencrypted data key :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey` or :class:`aws_encryption_sdk.structures.DataKey` ...
""" kms_params = {"KeyId": self._key_id, "Plaintext": data_key.data_key} if encryption_context: kms_params["EncryptionContext"] = encryption_context if self.config.grant_tokens: kms_params["GrantTokens"] = self.config.grant_tokens # Catch any boto3 errors an...
csn_ccr
converting nodeUrl to absolute Url form @param boolean $withFragment @return string
public function getAbsoluteUrl($withFragment=true) { if($this->isCrawlable() === false && empty($this->getFragment())){ $absolutePath = $this->getOriginalUrl(); }else{ if($this->parentLink !==null){ $newUri = \GuzzleHttp\Psr7\UriResol...
csn
func NewDecoder(r io.Reader) *Decoder { client := xml.NewDecoder(r) return &Decoder{
TokenType: StartXML, client: client, } }
csn_ccr
private static GeometricParity geometric(Map<IAtom, Integer> elevationMap, List<IBond> bonds, int i, int[] adjacent, IAtomContainer container) { int nStereoBonds =
nStereoBonds(bonds); if (nStereoBonds > 0) return geometric2D(elevationMap, bonds, i, adjacent, container); else if (nStereoBonds == 0) return geometric3D(i, adjacent, container); return null; }
csn_ccr
public static ControlledAttribute createIceControlledAttribute( long tieBreaker)
{ ControlledAttribute attribute = new ControlledAttribute(); attribute.setTieBreaker(tieBreaker); return attribute; }
csn_ccr
Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify
def notify(self): """ Access the Notify Twilio Domain :returns: Notify Twilio Domain :rtype: twilio.rest.notify.Notify """ if self._notify is None: from twilio.rest.notify import Notify self._notify = Notify(self) return self._notify
csn
void addSchema(JMFSchema schema, Transaction tran) throws MessageStoreException {
addItem(new SchemaStoreItem(schema), tran); }
csn_ccr
// SetGitHub sets the GitHub field's value.
func (s *CodeDestination) SetGitHub(v *GitHubCodeDestination) *CodeDestination { s.GitHub = v return s }
csn
def calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the standard deviation proposed by Glorot et al. .. math:: \sigma = \sqrt{\frac{2}{NK + M}} Args: inmaps (int): Map size of an input Variable, :math:`N`. outmaps (int): Map size of an output Variable, :math:...
= nn.Variable([60,1,28,28]) s = I.calc_normal_std_glorot(x.shape[1],64) w = I.NormalInitializer(s) b = I.ConstantInitializer(0) h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv') References: * `Glorot and Bengio. Understanding the difficulty of t...
csn_ccr
public List<ISubmission> getSubmissionsForSubmitter(ISubmitter submitter, String resourceUrl, String verb)
throws Exception{ return new SubmitterSubmissionsFilter().include(new NormalizingFilter(IRating.VERB).filter(getSubmissions(resourceUrl)), submitter); }
csn_ccr
def collect_garbage(): ''' Completely removed all currently 'uninstalled' packages in the nix store. Tells the user how many store paths were removed and how much space was freed. :return: How much space was freed and how many derivations were removed :rtype: str .. warning:: This is a...
store. .. code-block:: bash salt '*' nix.collect_garbage ''' cmd = _nix_collect_garbage() cmd.append('--delete-old') out = _run(cmd) return out['stdout'].splitlines()
csn_ccr
Initialize the view object $options may contain the following keys: - neverRender - flag dis/enabling postDispatch() autorender (affects all subsequent calls) - noController - flag indicating whether or not to look for view scripts in subdirectories named after the controller - noRender - flag indicating whether or no...
public function initView($path = null, $prefix = null, array $options = array()) { $this->setView($this->getServiceLocator()->get('View')); parent::initView($path, $prefix, $options); }
csn
import urllib import base64 data = urllib.urlopen('http://rosettacode.org/favicon.ico').read() print base64.b64encode(data)
#include <iostream> #include <fstream> #include <vector> typedef unsigned char byte; using namespace std; const unsigned m1 = 63 << 18, m2 = 63 << 12, m3 = 63 << 6; class base64 { public: base64() { char_set = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; } string encode( vector<byte> v...
codetrans_contest
Return list of 3x3-tuples.
def get_3_3_tuple_list(self,obj,default=None): """Return list of 3x3-tuples. """ if is_sequence3(obj): return [self.get_3_3_tuple(o,default) for o in obj] return [self.get_3_3_tuple(obj,default)]
csn
Add some UI to a "utility bar" type structure.
private void setUpUtilBar() { utilBar.setLayout(new ListLayout(ListLayout.Type.FLAT, ListLayout.Alignment.RIGHT, ListLayout.Separator.NONE, false)); WTextField selectOther = new WTextField(); selectOther.setToolTip("Enter text."); utilBar.add(selectOther); utilBar.add(new WButton("Go")); utilBar.add(new WBu...
csn
// float32 version of math.Max
func Max(x, y float32) float32 { return float32(math.Max(float64(x), float64(y))) }
csn
def auth_request_handler(self, callback): """Specifies the authentication response handler function. :param callable callback: the auth request handler function .. deprecated """ warnings.warn("This handler is deprecated. The recommended approach to have
control over " "the authentication resource is to disable the built-in resource by " "setting JWT_AUTH_URL_RULE=None and registering your own authentication " "resource directly on your application.", DeprecationWarning, stacklevel=2) self.auth...
csn_ccr
public static String toJsonObject(String[] arr) { if ( arr == null ) { return null; } StringBuffer sb = new StringBuffer(); sb.append('{'); for ( String
ele : arr ) { if ( sb.length() == 1 ) { sb.append('"').append(ele).append("\":true"); } else { sb.append(",\"").append(ele).append("\":true"); } } sb.append('}'); return sb.toString(); }
csn_ccr
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust). ```clojure solve 13 = 36 ; because 36 is the smalles...
def solve(n): for i in range(int(n**0.5), 0, -1): x = n - i**2 if x > 0 and x % (2*i) == 0: return ((n - i ** 2) // (2 * i)) ** 2 return -1
apps
// MakeMagicEndpoint creates go-kit endpoint function
func MakeMagicEndpoint(magic *Magic) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(Workload) result, err := magic.DoMagic(req) return result, err } }
csn
Render a path with locs, opts and contents block. @api private @param [Middleman::SourceFile] file The file. @param [Hash] locs Template locals. @param [Hash] opts Template options. @param [Proc] block A block will be evaluated to return internal contents. @return [String] The resulting content string. Contract...
def render_file(file, locs, opts, &block) _render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block) end
csn
// ChannelBalance returns the total available channel flow across all open // channels in satoshis.
func (r *rpcServer) ChannelBalance(ctx context.Context, in *lnrpc.ChannelBalanceRequest) (*lnrpc.ChannelBalanceResponse, error) { openChannels, err := r.server.chanDB.FetchAllOpenChannels() if err != nil { return nil, err } var balance btcutil.Amount for _, channel := range openChannels { balance += channel...
csn
def merge_all_cells(cells): """ Loop through list of cells and piece them together one by one Parameters ---------- cells : list of dashtable.data2rst.Cell Returns ------- grid_table : str The final grid table """ current = 0 while len(cells) > 1: count = 0...
merge_cells(cell1, cell2, merge_direction) if current > count: current -= 1 cells.pop(count) else: count += 1 current += 1 if current >= len(cells): current = 0 return cells[0].text
csn_ccr
private function resolveIDsfromESI(Collection $ids, $eseye) { // Finally, grab outstanding ids and resolve their names // using Esi. try { $eseye->setVersion('v3'); $eseye->setBody($ids->flatten()->toArray()); $names = $eseye->invoke('post', '/universe/n...
// until all possible resolvable ids has processed. if ($ids->count() === 1) { // return a singleton unresolvable id as 'unknown' $this->response[$ids->first()] = trans('web::seat.unknown'); } else { //split the chunk in two ...
csn_ccr
Chef has a sequence of N$N$ integers A1,A2,...,AN$A_1, A_2, ..., A_N$. Chef thinks that a triplet of integers (i,j,k)$(i,j,k)$ is good if 1≤i<j<k≤N$1 \leq i < j < k \leq N$ and P$P$ in the following expression contains an odd number of ones in its binary representation: P=[Ai<<(⌊log2(Aj)⌋+⌊log2(Ak)⌋+2)]+[Aj<<(⌊log2(Ak...
from math import * t = int(input()) for _ in range(t): n = int(input()) a = [int(d) for d in input().split()] odd,even = 0,0 for i in range(n): if bin(a[i]).count("1")%2 == 1: odd += 1 else: even +=1 total = 0 if odd >= 3 and even >= 2: total += (odd*(odd-1)*(odd-2))//...
apps
public function consumeOne(MessageInterface $message) { $consumeEvent = new ConsumeEvent($message); try { $this->dispatcher->dispatch(BarbeQEvents::PRE_CONSUME, $consumeEvent); $message->start(); $this->messageDispatcher->dispatch($message->getQueue(),...
$this->adapter->onError($message); $this->dispatcher->dispatch(BarbeQEvents::POST_CONSUME, $consumeEvent); // TODO throw new ConsumerIndigestionException("Error while consuming a message", 0, $e); } }
csn_ccr
def unindent(lines): '''Convert an iterable of indented lines into a sequence of tuples. The first element of each tuple is the indent in number of characters, and the second element is the unindented string. Args: lines: A sequence of strings representing the lines of text in a docstring. ...
A list of tuples where each tuple corresponds to one line of the input list. Each tuple has two entries - the first is an integer giving the size of the indent in characters, the second is the unindented text. ''' unindented_lines = [] for line in lines: unindented_line = lin...
csn_ccr
final public function readGuid() { $C = @unpack('V1V/v2v/N2N', $this->read(16)); list($hex) = @unpack('H*0', pack('NnnNN', $C['V'], $C['v1'], $C['v2'], $C['N1'], $C['N2'])); /* Fixes a bug in PHP versions earlier than Jan 25 2006 */ if (implode('', unpack('H*', pack('H*', 'a'))) == ...
// @codeCoverageIgnoreStart $hex = substr($hex, 0, -1); } // @codeCoverageIgnoreEnd return preg_replace('/^(.{8})(.{4})(.{4})(.{4})/', "\\1-\\2-\\3-\\4-", $hex); }
csn_ccr
public function map(array $configuration) { return [ 'driver' => $this->driver($configuration['driver']), 'host' => $configuration['host'], 'dbname' => $configuration['database'],
'user' => $configuration['username'], 'password' => $configuration['password'], 'charset' => $configuration['charset'], 'prefix' => @$configuration['prefix'] ? $configuration['prefix'] : null ]; }
csn_ccr
Accept user invitation. @param Request $request @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
public function accept(Request $request) { if (! $request->has('token')) abort(404); if (! $invitation = $this->validateToken($request->input('token'))) abort(404); return $this->showAcceptUserInvitationForm($invitation); }
csn
public static function startsWithDirectorySeparator($string, $separator = '') { if (empty($separator)) { $separator = DIRECTORY_SEPARATOR;
} return self::startsWith($string, $separator); }
csn_ccr
Try to choose the view limits intelligently.
def view_limits(self, vmin, vmax): """ Try to choose the view limits intelligently. """ b = self._transform.base if vmax < vmin: vmin, vmax = vmax, vmin if not matplotlib.ticker.is_decade(abs(vmin), b): if vmin < 0: vmin = -matplo...
csn
@Override protected void preparePaintComponent(final Request request) { super.preparePaintComponent(request); // If is an internal AJAX action, set the action type. if (isCurrentAjaxTrigger()) { AjaxOperation operation = AjaxHelper.getCurrentOperation(); if (operation.isInternalAjaxRequest()) { // Wan...
= getCustomTree(); if (custom != null) { checkExpandedCustomNodes(); } // Make sure the ID maps are up to date clearItemIdMaps(); if (getExpandMode() == ExpandMode.LAZY) { if (AjaxHelper.getCurrentOperation() == null) { clearPrevExpandedRows(); } else { addPrevExpandedCurrent(); } } }
csn_ccr
def load_fixture(fixture_file): """ Populate the database from a JSON file. Reads the JSON file FIXTURE_FILE and uses it to populate the database. Fuxture files should consist of a dictionary mapping database names to arrays of objects to store in those databases. """ utils.check_for_local_s...
for item in items: item_id = item["_id"] if item_id in db: old_item = db[item_id] item["_rev"] = old_item["_rev"] if item == old_item: continue db[item_id] = item
csn_ccr
func FilteredBy(pred ResourcePredicate, rls []*metav1.APIResourceList) []*metav1.APIResourceList { result := []*metav1.APIResourceList{} for _, rl := range rls { filtered := *rl filtered.APIResources = nil for i := range rl.APIResources { if pred.Match(rl.GroupVersion, &rl.APIResources[i]) {
filtered.APIResources = append(filtered.APIResources, rl.APIResources[i]) } } if filtered.APIResources != nil { result = append(result, &filtered) } } return result }
csn_ccr
Create a new file entry in the namespace. @throws IOException if file name is invalid {@link FSDirectory#isValidToCreate(String)}. @see ClientProtocol#create(String, FsPermission, String, boolean, short, long)
void startFile(String src, PermissionStatus permissions, String holder, String clientMachine, boolean overwrite, boolean createParent, short replication, long blockSize ) throws IOException { INodeFileUnderConstruction file = startFileInternal(src, permissions, holder, clie...
csn
def _write_parameter_file(params): """ Write the parameter file in the format that elaxtix likes. """ # Get path path = os.path.join(get_tempdir(), 'params.txt') # Define helper function def valToStr(val): if val in [True, False]: return '"%s"' % str(val).lower() ...
v in val] val_ = ' '.join(vals) else: val_ = valToStr(val) # Create line and add line = '(%s %s)' % (key, val_) text += line + '\n' # Write text f = open(path, 'wb') try: f.write(text.encode('utf-8')) finally: f.close() ...
csn_ccr
Stops the playing thread and close
def stop(self): """ Stops the playing thread and close """ with self.lock: self.halting = True self.go.clear()
csn
// dispatchSig launches a goroutine and closes the given stop channel // when SIGTERM, SIGHUP, or SIGINT is received.
func dispatchSig(stop chan<- error) { sigChan := make(chan os.Signal) signal.Notify( sigChan, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGINT, ) go func() { diag.Println("Waiting for signal") sig := <-sigChan diag.Printf("Received signal %v\n", sig) close(stop) }() }
csn
// Get return instance by name
func (d *Provider) Get(name string) (interface{}, error) { d.Block() if d.isCalled(name) { return nil, fmt.Errorf("%s is cyclic dependency (dependency callstack: %v)", name, append(d.callstack, name)) } if instance, exist := d.instances[name]; exist { return instance, nil } if factory, exist := d.factories[na...
csn
def each_event(cycle=0) return enum_for(__method__, cycle) unless
block_given? EventEnumerator.new(self, cycle).each { |v, s, d, i| yield v, s, d, i } end
csn_ccr
public function parseKeyword() { $token = ''; /** * Value to be returned. * * @var Token */ $ret = null; /** * The value of `$this->last` where `$token` ends in `$this->str`. * * @var int */ $iEnd = $th...
} else { $lastSpace = false; } $token .= $this->str[$this->last]; if (($this->last + 1 === $this->len || Context::isSeparator($this->str[$this->last + 1])) && $flags = Context::isKeyword($token) ) { $ret = new Token($toke...
csn_ccr
ManagerEvent addMember(BridgeEnterEvent event) { List<BridgeEnterEvent> remaining = null; synchronized (members) { if (members.put(event.getChannel(), event) == null && members.size() == 2) { remaining = new ArrayList<>(members.val...
logger.info("Members size " + remaining.size() + " " + event); BridgeEvent bridgeEvent = buildBridgeEvent( BridgeEvent.BRIDGE_STATE_LINK, remaining); logger.info("Bridge " + bridgeEvent.getChannel1() + " " + bridgeEvent.getChannel2()); return bridgeEvent; ...
csn_ccr
def scanStoVars(self, strline): """ scan input string line, replace sto parameters with calculated results. """ for wd in strline.split(): if wd in
self.stodict: strline = strline.replace(wd, str(self.stodict[wd])) return strline
csn_ccr
Given a block of ciphertext as a string, and a gpg object, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out.
def _decrypt_ciphertext(cipher): ''' Given a block of ciphertext as a string, and a gpg object, try to decrypt the cipher and return the decrypted string. If the cipher cannot be decrypted, log the error, and return the ciphertext back out. ''' try: cipher = salt.utils.stringutils.to_uni...
csn
Adds permissions classes that should exist for Jwt based authentication, if needed.
def _add_missing_jwt_permission_classes(self, view_class): """ Adds permissions classes that should exist for Jwt based authentication, if needed. """ view_permissions = list(getattr(view_class, 'permission_classes', [])) # Not all permissions are classes, some will be C...
csn
protected function get_release_asset_redirect( $asset, $aws = false ) { if ( ! $asset ) { return false; } // Unset release asset url if older than 5 min to account for AWS expiration. if ( $aws && ( time() - strtotime( '-12 hours', $this->response['timeout'] ) ) >= 300 ) { unset( $this->response['release...
'set_redirect' ], 10, 1 ); add_filter( 'http_request_args', [ $this, 'set_aws_release_asset_header' ] ); $url = $this->add_access_token_endpoint( $this, $asset ); wp_remote_get( $url ); remove_filter( 'http_request_args', [ $this, 'set_aws_release_asset_header' ] ); } if ( ! empty( $this->redirect ) )...
csn_ccr
func (l *Lexer) emit(kind TokenKind)
{ l.produce(kind, l.input[l.start:l.pos]) }
csn_ccr
function BlankField(type, options) { Field.call(this, type, options); this.element = util.createElement(this.document, 'div');
this.onFieldChange = util.createEvent('BlankField.onFieldChange'); }
csn_ccr
// MessageReceived must be called by the protocol upon receiving a message
func (b *Bot) MessageReceived(channel *ChannelData, message *Message, sender *User) { command, err := parse(message.Text, channel, sender) if err != nil { b.SendMessage(channel.Channel, err.Error(), sender) return } if command == nil { b.executePassiveCommands(&PassiveCmd{ Raw: message.Text, Me...
csn
Get instance for current collection. @return \Search\Model\Filter\FilterCollectionInterface
protected function _collection() { if (!isset($this->_collections[$this->_collection])) { $this->_collections[$this->_collection] = new $this->_collectionClass($this); } return $this->_collections[$this->_collection]; }
csn
Checks And Shows Review Message
protected function maybe_prompt() { if ( ! $this->is_time() ) { return; } \add_action( 'admin_footer', array( $this, 'script' ) ); if ( false !== $this->op['notice_callback'] ) { call_user_func_array( $this->op['notice_callback'], array( &$this ) ); } else { \add_action( 'admin_notices', array( $thi...
csn
private void probe(ImmutableMember member) { LOGGER.trace("{} - Probing {}", localMember.id(), member); bootstrapService.getMessagingService().sendAndReceive( member.address(), MEMBERSHIP_PROBE, SERIALIZER.encode(Pair.of(localMember.copy(), member)), false, config.getProbeTimeout()) .whenComplet...
request probes from peers. SwimMember swimMember = members.get(member.id()); if (swimMember != null && swimMember.getIncarnationNumber() == member.incarnationNumber()) { requestProbes(swimMember.copy()); } } }, swimScheduler); }
csn_ccr
func (h *httpForwarder) Accept() (net.Conn, error) { conn
:= <-h.connChan return conn, nil }
csn_ccr
private function getAdditionalTableFields() { $type = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY); $table = $type->getAdditionalAttributeTable(); $fullTableName = $this->getResource()->getTable($table);
$tableDesc = $this->getConnection()->describeTable($fullTableName); $tableFields = array_keys($tableDesc); return array_diff($tableFields, $this->overridenColumns); }
csn_ccr
Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence file (h5)
def stencil(**kwargs): """ Applying genotype calls to multi-way alignment incidence matrix :param alnfile: alignment incidence file (h5), :param gtypefile: genotype calls by GBRS (tsv), :param grpfile: gene ID to isoform ID mapping info (tsv) :return: genotyped version of alignment incidence fi...
csn
selects locale based on availability of translations @param string $errorId @param string $requestedLocale @return string
private function selectLocale(string $errorId, string $requestedLocale = null): string { $properties = $this->properties(); if (null !== $requestedLocale) { if ($properties->containValue($errorId, $requestedLocale)) { return $requestedLocale; } $b...
csn
func (w *Worker) Report() map[string]interface{} { w.mu.Lock() result := map[string]interface{}{ "api-port": w.config.APIPort, "status": w.status, "ports": w.holdable.report(), } if w.config.ControllerAPIPort != 0 { result["api-port-open-delay"]
= w.config.APIPortOpenDelay result["controller-api-port"] = w.config.ControllerAPIPort } w.mu.Unlock() return result }
csn_ccr
A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in.
def efficiency_capacity_demand_difference(slots, events, X, **kwargs): """ A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in. """ overflow = 0 for row, event in enumerate(events): for col, slot in enumerate(slots): ...
csn
func (ctx *CertContext) initServerCert(host string) (err error) { if ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil { if os.IsNotExist(err) { fmt.Printf("Creating new PK at: %s\n", ctx.PKFile) if ctx.PK, err = keyman.GeneratePK(2048); err != nil { return } if err = ctx.PK.WriteToFile(ctx...
it exists: %s\n", err) } } fmt.Printf("Creating new server cert at: %s\n", ctx.ServerCertFile) ctx.ServerCert, err = ctx.PK.TLSCertificateFor(tenYearsFromToday, true, nil, "Lantern", host) if err != nil { return } err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile) if err != nil { return } return nil ...
csn_ccr
Pick a random location for the star making sure it does not overwrite an existing piece of text.
def _respawn(self): """ Pick a random location for the star making sure it does not overwrite an existing piece of text. """ self._cycle = randint(0, len(self._star_chars)) (height, width) = self._screen.dimensions while True: self._x = randint(0, widt...
csn
python rest cookie session managment
def _get_data(self): """ Extracts the session data from cookie. """ cookie = self.adapter.cookies.get(self.name) return self._deserialize(cookie) if cookie else {}
cosqa
Add a property to be injected in the new object @param mixed $value
public function withProperty(string $property, $value): self { return new self( $this->class, $this->properties->put($property, $value), $this->injectionStrategy, $this->instanciator ); }
csn
func (s *ContainerDefinition) SetDockerLabels(v map[string]*string)
*ContainerDefinition { s.DockerLabels = v return s }
csn_ccr
function min(array) { var length = array.length; if (length === 0) { return 0; } var index = -1; var result = array[++index]; while (++index < length) {
if (array[index] < result) { result = array[index]; } } return result; }
csn_ccr
Create a new collaboration object. @param api the API connection used to make the request. @param accessibleBy the JSON object describing who should be collaborated. @param item the JSON object describing which item to collaborate. @param role the role to give the collaborators. @param notify ...
protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item, BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) { String queryString = ""; if (notify != null) { queryString = ne...
csn
Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` files :param kwargs: additional fields to include in the API request...
def create_ssh_key(self, name, public_key, **kwargs): """ Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` fi...
csn
defined depending on which selector was used
def rvm_task(name,&block) if fetch(:rvm_require_role,nil).nil? task name, &block else task name, :roles => fetch(:rvm_require_role), &block end end
csn
Open a session. @param string $path @param string $name @return bool
public function open($path, $name) { $rand = $this->psl['crypt/rand']; /* Set some variables we need later. */ $this->savePath = $path; $this->name = $name; $this->keyCookie = $name.'_secret'; /* Set current and new ID. */ if(isset($_COOKIE[$name])) { $this->currID = $_C...
csn
func (conn *Conn) Signal(ch chan<- *Signal) {
conn.defaultSignalAction((*defaultSignalHandler).addSignal, ch) }
csn_ccr
private function instantiateGroup($group) { if ( !isset($group['instantiate'])) { return;
} foreach ($group['instantiate'] as $nickname => $className) { $this->objectRegistry->register($nickname, new $className()); } }
csn_ccr
HTTP POST required for security.
@RequestMapping( headers = {"org.apereo.portal.url.UrlType=ACTION"}, method = RequestMethod.POST) public void actionRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { final IPortalRequestInfo portalRequestInfo = this.ur...
csn
Recurse through the provided json object, looking for strings that are encrypted @param obj @returns {*}
function containsEncryptedData(obj) { var foundEncrypted = false; if (_.isString(obj)) { foundEncrypted = isEncrypted(obj); } else if (_.isArray(obj)) { for (var i = 0; i < obj.length; i++) { foundEncrypted = foundEncrypted || containsEncryptedData(obj[i]); } } else i...
csn
Deploy a WampServer @return IoServer
private function startWampServer() { if (! $this->serverInstance instanceof RatchetWampServer) { throw new \Exception("{$this->class} must be an instance of ".RatchetWampServer::class." to create a Wamp server"); } // Decorate the server instance with a WampServer $this-...
csn
public function get_activities() { $modinfo = get_fast_modinfo($this->course); $result = array(); foreach ($modinfo->get_cms() as $cm) { if ($cm->completion !=
COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) { $result[$cm->id] = $cm; } } return $result; }
csn_ccr