query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Retrieve the datacenter id associated to a dc_code
def from_dc_code(cls, dc_code): """Retrieve the datacenter id associated to a dc_code""" result = cls.list() dc_codes = {} for dc in result: if dc.get('dc_code'): dc_codes[dc['dc_code']] = dc['id'] return dc_codes.get(dc_code)
csn
public function isDiff($first, $second) { if(! file_exists($first)) throw new NoSuchFileException($first); $second = $this->oFileNameResolver->resolve($first, $second); // If the second file doesn't exist, they're definitely different if(! file_exists($second)) return true; // If the file sizes are ...
if(! ($fh2 = fopen($second, 'rb'))) throw new FileOpenException($second); while(! feof($fh1) && ! feof($fh2)) { $data1 = fread($fh1, static::READ_SIZE); if(false === $data1) throw new FileReadException($first); $data2 = fread($fh2, static::READ_SIZE); if(false === $data2) throw new File...
csn_ccr
Transforms an array into a DateTime. @param array $value Array value. @return DateTime DateTime value.
public function reverseTransform($value) { if ( $value['date'] && $value['time'] ) { return new \DateTime(sprintf( '%s %s', $value['date']->format('Y-m-d'), $value['time']->format('H:i:s') )); } if ( $value['date'] ) { ...
csn
function(proto, key, desc) { var val = desc.value; if (gui.Type.isObject(val)) { if (val.getter ||
val.setter) { if (this._isactive(val)) { desc = this._activeaccessor(proto, key, val); } } } return desc; }
csn_ccr
public function generateSlug($title) { $title = strtolower($title); $title = preg_replace('/[^%a-z0-9 _-]/', '', $title); $title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title); $title = trim($title, '-'); return $title; }
csn_ccr
Set the active DOM Element. @param string $element The Element to set. @return \Xety\Breadcrumbs\Breadcrumbs
public function setListActiveElement(string $element): Breadcrumbs { $this->validateElement('allowedListActiveElement', $element); $this->setOption('listActiveElement', $element); return $this; }
csn
def scoreatpercentile(inlist, percent): """ Returns the score at a given percentile relative to the distribution given by inlist. Usage: lscoreatpercentile(inlist,percent) """ if percent > 1: print("\nDividing percent>1 by 100 in lscoreatpercentile().\n") percent = percent / 100.0 targetc...
cumhist = cumsum(copy.deepcopy(h)) for i in range(len(cumhist)): if cumhist[i] >= targetcf: break score = binsize * ((targetcf - cumhist[i - 1]) / float(h[i])) + (lrl + binsize * i) return score
csn_ccr
Returns a value from the internal params array. @param string $key The param key. @return mixed The param value, or null if not found.
public function getParam($key) { /* Passwords may be stored encrypted. */ switch ($key) { case 'password': if (isset($this->_params[$key]) && ($this->_params[$key] instanceof Horde_Imap_Client_Base_Password)) { return $this->_params[$key]->getPassw...
csn
def convert_to_jbig2(pike, jbig2_groups, root, log, options): """Convert images to JBIG2 and insert into PDF. When the JBIG2 page group size is > 1 we do several JBIG2 images at once and build a symbol dictionary that will span several pages. Each JBIG2 image must reference to its symbol dictionary. If...
jbig2_globals_data = jbig2_symfile.read_bytes() jbig2_globals = pikepdf.Stream(pike, jbig2_globals_data) jbig2_globals_dict = Dictionary(JBIG2Globals=jbig2_globals) elif options.jbig2_page_group_size == 1: jbig2_globals_dict = None else: raise FileNo...
csn_ccr
public static function isValid(string $urlPath): bool { return self::myParse( '/', $urlPath, function ($p, $d, &$e) {
return self::myPartValidator($p, $d, $e); }); }
csn_ccr
func (s *state) Ping() error { return s.APICall("Pinger",
s.pingerFacadeVersion, "", "Ping", nil, nil) }
csn_ccr
public function setElementTemplateForGroupId($groupId, $elementClass, $template) {
$this->elementTemplatesForGroupId[$groupId][strtolower($elementClass)] = $template; return $this; }
csn_ccr
Return schema for model. @param string $model Name of model for return schema. @return array|null Array of schema, or null on failure.
protected function _getSchema($model = null) { $result = null; if (empty($model)) { return $result; } $modelObj = ClassRegistry::init($model, true); if ($modelObj === false) { return $result; } $result = $modelObj->schema(); if (empty($modelObj->virtualFields)) { return $result; } foreac...
csn
func Convert_config_DefaultAdmissionConfig_To_v1_DefaultAdmissionConfig(in *config.DefaultAdmissionConfig,
out *v1.DefaultAdmissionConfig, s conversion.Scope) error { return autoConvert_config_DefaultAdmissionConfig_To_v1_DefaultAdmissionConfig(in, out, s) }
csn_ccr
def blog_months(*args): """ Put a list of dates for blog posts into the template context. """ dates = BlogPost.objects.published().values_list("publish_date", flat=True) date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates] month_dicts = [] for date_dict in date_dicts: ...
month_dicts.append(date_dict) for i, date_dict in enumerate(month_dicts): month_dicts[i]["post_count"] = date_dicts.count(date_dict) return month_dicts
csn_ccr
Returns inline js, in case you don't want to immediately render. @return string
public function getScripts() { $retVal = ''; while ( $this->scripts->valid() ) { $retVal .= "<script type='text/javascript'>\n{$this->scripts->get()}\n</script>\n"; $this->scripts->next(); } return $retVal; }
csn
def _get_resource_raw( self, cls, id, extra=None, headers=None, stream=False, **filters ): """Get an individual REST resource""" headers = headers or {} headers.update(self.session.headers) postfix = "/{}".format(extra) if extra else "" if cls.api_root != "a": ...
filters, cls.datetime_filter_attrs ) url = str(URLObject(url).add_query_params(converted_filters.items())) response = self._get_http_session(cls.api_root).get( url, headers=headers, stream=stream ) return _validate(response)
csn_ccr
function nextShallow(stream) { if (!stream.cursor) return false; var cursor = stream.cursor; cursor.x++; var bbox = stream.bboxes[cursor.z]; if (cursor.x > bbox.maxX) { cursor.x = bbox.minX; cursor.y++; }
if (cursor.y > bbox.maxY) { stream.cursor = false; return false; } return true; }
csn_ccr
Runs callbacks. @param callback_type [:Symbol] The callback type. @param object [Object] The object
def do_callbacks(callback_type, object, options = {}) return if $bot[:callbacks][callback_type].nil? $bot[:callbacks][callback_type].each do |c| c[:block].call object, options end end
csn
compile a CoffeeScript script file to a JavaScript code. filename can be a list or tuple of filenames, then contents of files are concatenated with line feeds. if bare is True, then compile the JavaScript without the top-level function safety wrapper (like the coffee command).
def compile_file(self, filename, encoding="utf-8", bare=False): '''compile a CoffeeScript script file to a JavaScript code. filename can be a list or tuple of filenames, then contents of files are concatenated with line feeds. if bare is True, then compile the JavaScript without the to...
csn
func (b *BlockIterator) Read() (key []byte, minTime int64, maxTime int64, typ byte, checksum uint32, buf []byte, err error) { if err := b.iter.Err(); err != nil { return nil, 0, 0, 0, 0, nil, err } checksum, buf, err = b.r.ReadBytes(&b.entries[0], nil)
if err != nil { return nil, 0, 0, 0, 0, nil, err } return b.iter.Key(), b.entries[0].MinTime, b.entries[0].MaxTime, b.iter.Type(), checksum, buf, err }
csn_ccr
def check_solver(self, image_x, image_y, kwargs_lens): """ returns the precision of the solver to match the image position :param kwargs_lens: full lens model (including solved parameters) :param image_x: point source in image :param image_y: point source in image :retur...
image positions """ source_x, source_y = self._lensModel.ray_shooting(image_x, image_y, kwargs_lens) dist = np.sqrt((source_x - source_x[0]) ** 2 + (source_y - source_y[0]) ** 2) return dist
csn_ccr
The main function for retrieving nodes by prop. Args: full (str): The property/tag name. valu (obj): A lift compatible value for the type. cmpr (str): An optional alternate comparator. Yields: (synapse.lib.node.Node): Node instances.
async def getNodesBy(self, full, valu=None, cmpr='='): ''' The main function for retrieving nodes by prop. Args: full (str): The property/tag name. valu (obj): A lift compatible value for the type. cmpr (str): An optional alternate comparator. Yields...
csn
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn,
batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
csn_ccr
Returns a string representing the JSONPointer path value using URI fragment identifier representation
public String toURIFragment() { try { StringBuilder rval = new StringBuilder("#"); for (String token : this.refTokens) { rval.append('/').append(URLEncoder.encode(token, ENCODING)); } return rval.toString(); } catch (UnsupportedEncodingExce...
csn
def class_name(self, cls, parts=0, aliases=None): # type: (Any, int, Optional[Dict[unicode, unicode]]) -> unicode """Given a class object, return a fully-qualified name. This works for things I've tested in matplotlib so far, but may not be completely general. """ module...
if parts == 0: result = fullname else: name_parts = fullname.split('.') result = '.'.join(name_parts[-parts:]) if aliases is not None and result in aliases: return aliases[result] return result
csn_ccr
func GetVersion() (major, minor, revision int) { var ( maj C.int min C.int rev C.int )
C.glfwGetVersion(&maj, &min, &rev) return int(maj), int(min), int(rev) }
csn_ccr
def drop_table(self, model_class): ''' Drops the database table of the given model class, if it exists.
''' if model_class.is_system_model(): raise DatabaseException("You can't drop system table") self._send(model_class.drop_table_sql(self))
csn_ccr
// ExpectErrorMessagef fails if the error message does not contain the // given string; message formatted per Printf.
func (t *T) ExpectErrorMessagef(err error, msg string, spec string, args ...interface{}) { prefix := fmt.Sprintf(spec, args...) + ": " if err == nil { t.Fatalf("%sExpected error was not returned.", prefix) } else if !strings.Contains(err.Error(), msg) { t.Fatalf("%sError message didn't contain the expected messa...
csn
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place  (The pointer should not be placed outside the array at any time). Given two integers steps and arrLen, return the number of ways such that your poi...
# https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/569521/7-python-approaches-with-Time-and-Space-analysis class Solution: def numWays(self, steps: int, arrLen: int) -> int: r = min(arrLen, steps // 2 + 1) dp = [0, 1] for t in range(steps): ...
apps
func (t *Template) GetAWSKinesisAnalyticsApplicationWithName(name string) (*resources.AWSKinesisAnalyticsApplication, error) { if untyped, ok := t.Resources[name]; ok
{ switch resource := untyped.(type) { case *resources.AWSKinesisAnalyticsApplication: return resource, nil } } return nil, fmt.Errorf("resource %q of type AWSKinesisAnalyticsApplication not found", name) }
csn_ccr
Sets the objects defer state. @param bool $defer @return \Core\Javascript
public function setDefer($defer = false) { $this->defer = is_bool($defer) ? $defer : false; return $this; }
csn
Filter to protect the hawkBit server system management interface against to many requests. @param securityProperties for filter configuration @return the spring filter registration bean for registering a denial of service protection filter in the filter chain
@Bean @ConditionalOnProperty(prefix = "hawkbit.server.security.dos.filter", name = "enabled", matchIfMissing = true) public FilterRegistrationBean<DosFilter> dosSystemFilter(final HawkbitSecurityProperties securityProperties) { final FilterRegistrationBean<DosFilter> filterRegBean = dosFilter(Collectio...
csn
creating custom loggers python
def register_logging_factories(loader): """ Registers default factories for logging standard package. :param loader: Loader where you want register default logging factories """ loader.register_factory(logging.Logger, LoggerFactory) loader.register_factory(logging.Handler, LoggingHandlerFactory...
cosqa
how to get the column names of a data frame in python
def get_obj_cols(df): """ Returns names of 'object' columns in the DataFrame. """ obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == 'object' or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
cosqa
// Validate checks the field values on TcpGrpcAccessLogConfig with the rules // defined in the proto definition for this message. If any rules are // violated, an error is returned.
func (m *TcpGrpcAccessLogConfig) Validate() error { if m == nil { return nil } if m.GetCommonConfig() == nil { return TcpGrpcAccessLogConfigValidationError{ field: "CommonConfig", reason: "value is required", } } { tmp := m.GetCommonConfig() if v, ok := interface{}(tmp).(interface{ Validate() e...
csn
// NewFileCommentsChangePolicyType returns a new FileCommentsChangePolicyType instance
func NewFileCommentsChangePolicyType(Description string) *FileCommentsChangePolicyType { s := new(FileCommentsChangePolicyType) s.Description = Description return s }
csn
python call model name
def get_model(name): """ Convert a model's verbose name to the model class. This allows us to use the models verbose name in steps. """ model = MODELS.get(name.lower(), None) assert model, "Could not locate model by name '%s'" % name return model
cosqa
// wrapHandlerWithName wraps Handler type and returns it including it's name before wrapping
func (l *LARS) wrapHandlerWithName(h Handler) (chain HandlerFunc, handlerName string) { chain = l.wrapHandler(h) handlerName = runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name() return }
csn
Adds a relationship. @param string $name The relationship name @param Yosymfony\Spress\Core\DataSource\ItemInterface $item An item
public function add($name, ItemInterface $item) { if (isset($this->relationships[$name]) === false) { $this->relationships[$name] = []; } unset($this->relationships[$name][$item->getId()]); $this->relationships[$name][$item->getId()] = $item; }
csn
func (o *GetIDOK) WithPayload(payload *models.Customer)
*GetIDOK { o.Payload = payload return o }
csn_ccr
public void identify(final Chain chain, final Set<ProteinModification> potentialModifications) {
identify(Collections.singletonList(chain), potentialModifications); }
csn_ccr
def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipel...
cloud: a DataFlow pipeline option dictionary such as {'num_workers': 3}. If anything but not None, it will run in cloud. Otherwise, it runs locally. Returns: A google.datalab.utils.Job object that can be used to query state from or wait. """ with warnings.catch_warnings(): warnings.simplefil...
csn_ccr
Get a paragraph, given the index of this paragraph. This method returns information about a paragraph.<p> @param paraIndex is the number of the paragraph, in the range <code>[0..countParagraphs()-1]</code>. @return a BidiRun object with the details of the paragraph:<br> <code>start</code> will receive the index of t...
public BidiRun getParagraphByIndex(int paraIndex) { verifyValidParaOrLine(); verifyRange(paraIndex, 0, paraCount); Bidi bidi = paraBidi; /* get Para object if Line object */ int paraStart; if (paraIndex == 0) { paraStart = 0; } else { ...
csn
func (o *NSGatewayTemplate) CreateNSPortTemplate(child *NSPortTemplate) *bambou.Error {
return bambou.CurrentSession().CreateChild(o, child) }
csn_ccr
Fills the slot with null value and calls handleSlotFilled
private static void handleDelayedSlotFill(DelayedSlotFillTask task) { Key slotKey = task.getSlotKey(); Slot slot = querySlotOrAbandonTask(slotKey, true); Key rootJobKey = task.getRootJobKey(); UpdateSpec updateSpec = new UpdateSpec(rootJobKey); slot.fill(null); updateSpec.getNonTransactionalGrou...
csn
public function forceSsl($type) { $host = env('SERVER_NAME'); if (empty($host)) {
$host = env('HTTP_HOST'); } if ('secure' == $type) { $this->redirect('https://' . $host . $this->here); } }
csn_ccr
total columns count, including relations
function updateColsCount() { $this->_colsCount = sizeof($this->flds); foreach($this->_belongsTo as $foreignTable) $this->_colsCount += sizeof($foreignTable->TableInfo()->flds); foreach($this->_hasMany as $foreignTable) $this->_colsCount += sizeof($foreignTable->TableInfo()->flds); }
csn
Returns true if there are no plugins left that should, if possible, be loaded before this plugin. @param plugin The plugin @return true if there are
private boolean areNoneToLoadBefore(GrailsPlugin plugin) { for (String name : plugin.getLoadAfterNames()) { if (getGrailsPlugin(name) == null) { return false; } } return true; }
csn
func (r Network_Storage_Allowed_Host_IpAddress) GetCredential() (resp datatypes.Network_Storage_Credential, err error) {
err = r.Session.DoRequest("SoftLayer_Network_Storage_Allowed_Host_IpAddress", "getCredential", nil, &r.Options, &resp) return }
csn_ccr
Draw the line numbers
@Override public void paintComponent(Graphics g) { super.paintComponent(g); // Determine the width of the space available to draw the line number FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); Insets insets = getInsets(); int availableWidth = getSize().width - insets.le...
csn
Returns literals array for locale provided. If array was not generated earlier, it will be generated and cached. @param Locale $locale @return array An array with localized literals
public function getLocalizedLiteralsForLocale(Locale $locale) { if (isset($this->localizedLiterals[(string)$locale])) { return $this->localizedLiterals[(string)$locale]; } $model = $this->cldrRepository->getModelForLocale($locale); $localizedLiterals['months'] = $this->...
csn
function(tween) { var frames = tween.totalFrames; var frame = tween.currentFrame; var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); var elapsed = (new Date() - tween.getStartTime()); var tweak = 0; if (elapsed < tween.duration * 100...
if (tweak > 0 && isFinite(tweak)) { // adjust if needed if (tween.currentFrame + tweak >= frames) {// dont go past last frame tweak = frames - (frame + 1); } tween.currentFrame += tweak; } }
csn_ccr
Parse the header of an input byte array and then decode using the input array, the codec and the appropirate parameter. :param input_array: the array to be decoded :return the decoded array
def decode_array(input_array): """Parse the header of an input byte array and then decode using the input array, the codec and the appropirate parameter. :param input_array: the array to be decoded :return the decoded array""" codec, length, param, input_array = parse_header(input_array) return...
csn
Returns rules that are required for given reflection. @return RuleInterface[]
public function getRules(Reflector $reflection): array { if ($reflection instanceof ReflectionMethod) { $key = $reflection->getDeclaringClass()->getName().'::'.$reflection->getName(); } elseif ($reflection instanceof ReflectionClass) { $key = $reflection->getName(); }...
csn
The apparent type of a type parameter is the base constraint instantiated with the type parameter as the type argument for the 'this' type.
function getApparentTypeOfTypeParameter(type) { if (!type.resolvedApparentType) { var constraintType = getConstraintOfTypeParameter(type); while (constraintType && constraintType.flags & 16384 /* TypeParameter */) { constraintType = getConstraintOfTypePara...
csn
Reloads default Reveal rules. Resets all class variables and removes all non-default rules. @return void
public static function reload() { if (empty(self::$_initialState)) { foreach ((array) Configure::read('Routing.prefixes') as $prefix) { self::addRule('Page.' . $prefix, array('self', '__isPage'), $prefix); } self::$_initialState = get_class_vars('Reveal'); return; } foreach (self::$_initialState...
csn
Shows the language select to change the language @return \Zend\View\Model\ViewModel
public function headerLanguageAction() { $melisKey = $this->params()->fromRoute('melisKey', ''); $view = new ViewModel(); $view->melisKey = $melisKey; return $view; }
csn
public final void expandParent(int parentPosition) { if (!isExpanded(parentPosition)) { mExpandItemArray.append(parentPosition, true);
int position = positionFromParentPosition(parentPosition); int childCount = childItemCount(parentPosition); notifyItemRangeInserted(position + 1, childCount); } }
csn_ccr
protected function renderLtiErrorPage(LtiException $error, $returnLink = true) { // In regard of the IMS LTI standard, we have to show a back button that refer to the // launch_presentation_return_url url param. So we have to retrieve this parameter before trying to start // te session ...
$this->renderer->setData('consumerLabel', $consumerLabel); } $this->renderer->setData('message', $error->getMessage()); $this->renderer->setTemplate(Template::getTemplate('error.tpl', 'taoLti')); return $this->renderer->render(); }
csn_ccr
private ChunkFetchRequestHandler createChunkFetchHandler(TransportChannelHandler channelHandler, RpcHandler
rpcHandler) { return new ChunkFetchRequestHandler(channelHandler.getClient(), rpcHandler.getStreamManager(), conf.maxChunksBeingTransferred()); }
csn_ccr
public static FactorCreator creator(final String pathServiceSid, final String pathIdentity, final String binding, final String friendlyName,
final Factor.FactorTypes factorType) { return new FactorCreator(pathServiceSid, pathIdentity, binding, friendlyName, factorType); }
csn_ccr
func waitAnyInstanceAddresses( env Environ, ctx context.ProviderCallContext, instanceIds []instance.Id, ) ([]network.Address, error) { var addrs []network.Address for a := AddressesRefreshAttempt.Start(); len(addrs) == 0 && a.Next(); { instances, err := env.Instances(ctx, instanceIds) if err != nil && err != E...
{ logger.Debugf("error getting state instances: %v", err) return nil, err } addrs = getAddresses(ctx, instances) } if len(addrs) == 0 { return nil, errors.NotFoundf("addresses for %v", instanceIds) } return addrs, nil }
csn_ccr
public PreparedStatement prepareStatement(final String sql) throws SQLException { if (parameterizedBatchHandlerFactory == null) { this.parameterizedBatchHandlerFactory = new DefaultParameterizedBatchHandlerFactory(); } final String strippedQuery = Utils.stripQuery(sql); retur...
this, strippedQuery, queryFactory, parameterizedBatchHandlerFactory.get(strippedQuery, protocol)); }
csn_ccr
// jwtFromCookie returns a `jwtExtractor` that extracts token from the named cookie.
func jwtFromCookie(name string) jwtExtractor { return func(c echo.Context) (string, error) { cookie, err := c.Cookie(name) if err != nil { return "", ErrJWTMissing } return cookie.Value, nil } }
csn
## Nova polynomial add This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) ) ...
# return the sum of the two polynomials p1 and p2. def poly_add(p1,p2): if p1 == []: return p2 if p2 == []: return p1 return [p1[0] + p2[0]] + poly_add(p1[1:], p2[1:])
apps
def get_result(self): """ Returns resulting catalogue @rtype: MessageCatalogue
""" for domain in self.domains: if domain not in self.messages: self._process_domain(domain) return self.result
csn_ccr
public static function detectCmdLocationInPaths($cmd, array $paths) : string { foreach ($paths as $path) { $command = $path
. DIRECTORY_SEPARATOR . $cmd; $bin = self::getExecutable($command); if (null !== $bin) { return $bin; } } return ''; }
csn_ccr
def get_usage(self): """Get fitness locations and their current usage.""" resp = requests.get(FITNESS_URL, timeout=30) resp.raise_for_status() soup = BeautifulSoup(resp.text, "html5lib") eastern = pytz.timezone('US/Eastern') output = [] for item in soup.findAll(...
name, "open": "Open" in data[1], "count": int(data[2].rsplit(" ", 1)[-1]), "updated": eastern.localize(datetime.datetime.strptime(data[3][8:].strip(), '%m/%d/%Y %I:%M %p')).isoformat(), "percent": int(data[4][:-1]) }) return output
csn_ccr
// replaceListElement builds a new ListElement from a listItem // Uses the "replace" strategy and identify "same" elements across lists by their index
func (v ElementBuildingVisitor) replaceListElement(meta apply.FieldMetaImpl, item *listItem) (*apply.ListElement, error) { meta.Name = item.Name result := &apply.ListElement{ FieldMetaImpl: meta, ListElementData: item.ListElementData, Values: []apply.Element{}, } // Use the max length to iterate o...
csn
Adds a given product to the list of evidence to matched. @param source the source of the evidence @param name the name of the evidence @param value the value of the evidence @param regex whether value is a regex @param confidence the confidence of the evidence
public void addGivenProduct(String source, String name, String value, boolean regex, Confidence confidence) { givenProduct.add(new EvidenceMatcher(source, name, value, regex, confidence)); }
csn
func messageToPromText(message producers.MetricsMessage) string { var buffer bytes.Buffer for _, d := range message.Datapoints { name := sanitizeName(d.Name) labels := getLabelsForDatapoint(message.Dimensions, d.Tags)
t, err := time.Parse(time.RFC3339, d.Timestamp) if err != nil { log.Warnf("Encountered bad timestamp, %q: %s", d.Timestamp, err) continue } timestampMs := int(t.UnixNano() / 1000000) buffer.WriteString(fmt.Sprintf("%s%s %v %d\n", name, labels, d.Value, timestampMs)) } return buffer.String() }
csn_ccr
Merges with other events. @param EventsInterface $source The data source @return null|array If the source was passed returns null, source data otherwise
public function merge(EventsInterface $source = null) { if (null === $source) { return $this->events; } $this->events = array_merge($this->events, $source->merge()); }
csn
Injects dependencies into the given target object whose lifecycle is not managed by the BeanManager itself. @param target an object with injection points
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void injectFields(Object target) { BeanManager mgr = BeanManagerLookup.getBeanManager(); AnnotatedType annotatedType = mgr.createAnnotatedType(target.getClass()); InjectionTarget injectionTarget = mgr.createInjectionTarget(a...
csn
protected <T> T getResponse(final WebTarget target, final ResponseProcessor<T> responseProcessor, final Request request) { Builder requestBuilder = target.request(); Response response = requestBuilder.buildGet().invoke(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { InputStream in...
} throw t; } } else if (response.getStatus() == UNPROCESSABLE_ENTITY) { String msg = "Response code to " + target.getUri() + " was " + response.getStatusInfo(); response.close(); throw new QuandlUnprocessableEntityException(msg); } else if (response.getStatus() == TOO_MANY_RE...
csn_ccr
def get_wells(self, plate_name=None): '''Gets information about wells. Parameters ---------- plate_name: str, optional name of the parent plate Returns ------- List[Dict[str, str]] id, name and description of each well See also ...
params['plate_name'] = plate_name url = self._build_api_url( '/experiments/{experiment_id}/wells'.format( experiment_id=self._experiment_id ), params ) res = self._session.get(url) res.raise_for_status() return res.json()...
csn_ccr
calculate rows and cols from the region and its resolution. Round if required.
public void fixRowsAndCols() { rows = (int) Math.round((n - s) / ns_res); if (rows < 1) rows = 1; cols = (int) Math.round((e - w) / we_res); if (cols < 1) cols = 1; }
csn
protected function filterNodeByContext(NodeInterface $node, Context $context) { $this->securityContext->withoutAuthorizationChecks(function () use (&$node, $context) { if (!$context->isRemovedContentShown() && $node->isRemoved()) { $node = null; return; ...
$node = null; return; } if (!$context->isInaccessibleContentShown() && !$node->isAccessible()) { $node = null; } }); return $node; }
csn_ccr
def format_permission_object(self, permissions): """Formats a list of permission key names into something the SLAPI will respect. :param list permissions: A list of SLAPI permissions keyNames. keyName of ALL will return all permissions. :returns: list of diction...
# pp(available_permissions) for permission in permissions: # Handle data retrieved directly from the API if isinstance(permission, dict): permission = permission['keyName'] permission = permission.upper() if permission == 'ALL': ...
csn_ccr
def make_archive(self, path): """Create archive of directory and write to ``path``. :param path: Path to archive Ignored:: * build/* - This is used for packing the charm itself and any similar tasks. * */.* - Hidden files are all ignored fo...
relative_path = dirpath[len(self.path) + 1:] if relative_path and not self._ignore(relative_path): zf.write(dirpath, relative_path) for name in filenames: archive_name = os.path.join(relative_path, name) if not self._ignore(archive_name): ...
csn_ccr
// AddSecretAnnotation add secret flag to Annotation.
func (f FlagInfo) AddSecretAnnotation(flags *pflag.FlagSet) FlagInfo { flags.SetAnnotation(f.LongName, "classified", []string{"true"}) return f }
csn
Get debug settings from arguments. --debug: turn on additional debug code/inspection (implies logging.DEBUG) --verbose: turn up logging output (logging.DEBUG) --quiet: turn down logging output (logging.WARNING) Default is logging.INFO
def log_level(conf): """Get debug settings from arguments. --debug: turn on additional debug code/inspection (implies logging.DEBUG) --verbose: turn up logging output (logging.DEBUG) --quiet: turn down logging output (logging.WARNING) Default is logging.INFO """ if conf.debu...
csn
Get the alias of the previous content element @return string The type of the previous content element
public function prevElement () { if (($arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'.$this->pid]) === null) { $objCte = \ContentModel::findPublishedByPidAndTable($this->pid, $this->ptable); if ($objCte === null) { return; } $arrTypes = $GLOBALS['templateTypes'][$this->ptable.'.'...
csn
Real delete a entity in object manager. @param ResourceInterface $resource The resource
protected function doDeleteResourceAction(ResourceInterface $resource): void { try { $this->om->remove($resource->getRealData()); } catch (\Exception $e) { DomainUtil::injectErrorMessage($this->translator, $resource, $e, $this->debug); } }
csn
function registerable (cfgObj) { _.forIn(cfgObj, function (value, key) { if
(registerableCfg.indexOf(key) !== -1) { register(key, cfgObj) } }) }
csn_ccr
func (vp *vplayer) play(ctx context.Context) error { if !vp.stopPos.IsZero() && vp.startPos.AtLeast(vp.stopPos) { if vp.saveStop { return vp.vr.setState(binlogplayer.BlpStopped, fmt.Sprintf("Stop position %v already reached: %v", vp.startPos, vp.stopPos)) } return nil } plan, err := buildReplicatorPlan(vp....
vp.vr.stats.History.Add(&binlogplayer.StatsHistoryRecord{ Time: time.Now(), Message: msg, }) if err := vp.vr.setMessage(msg); err != nil { log.Errorf("Failed to set error state: %v", err) } return err } return nil }
csn_ccr
public function add_class( $class ) { if ( !isset( $this->attr['class'] ) || !is_array( $this->attr['class'] ) ) { $this->_sanitize_class(); } if ( strpos(
$class, ' ' ) !== false ) { $class = explode( ' ', $class ); } if ( is_string( $class ) ) { $class = array( $class ); } foreach ( $class as $c ) { $this->attr['class'][] = $c; } return $this; }
csn_ccr
Inputting a value for the first time
def make_valid_string(self, string=''): """ Inputting a value for the first time """ if not self.is_valid_str(string): if string in self.val_map and not self.allow_dups: raise IndexError("Value {} has already been given to the sanitizer".format(string)) internal_n...
csn
func (b *BufferedOutput) Close() { b.close_once.Do(func()
{ close(b.c) }) b.running.Lock() b.running.Unlock() }
csn_ccr
Sets the productBuiltInTargeting value for this ProposalLineItemConstraints. @param productBuiltInTargeting * Built-in targeting for the created {@link ProposalLineItem}. <p>This attribute is read-only.
public void setProductBuiltInTargeting(com.google.api.ads.admanager.axis.v201805.Targeting productBuiltInTargeting) { this.productBuiltInTargeting = productBuiltInTargeting; }
csn
Get events for this contract instance using eth_getLogs API. This is a stateless method, as opposed to createFilter. It can be safely called against nodes which do not provide eth_newFilter API, like Infura nodes. If there are many events, like ``Transfer`` events for a popular...
def getLogs(self, argument_filters=None, fromBlock=None, toBlock=None, blockHash=None): """Get events for this contract instance using eth_getLogs API. This is a stateless method, as opposed to createFilter. It can be safely called...
csn
A marching cubes Trimesh representation of the voxels. No effort was made to clean or smooth the result in any way; it is merely the result of applying the scikit-image measure.marching_cubes function to self.matrix. Returns --------- meshed: Trimesh object representing...
def marching_cubes(self): """ A marching cubes Trimesh representation of the voxels. No effort was made to clean or smooth the result in any way; it is merely the result of applying the scikit-image measure.marching_cubes function to self.matrix. Returns -------...
csn
private FileFilter createConfigFilesFilter() { SiteConfig config = site.getConfig(); boolean useDefaultConfigFiles = config.useDefaultConfigFiles(); if (useDefaultConfigFiles) { log.debug("Using default config files."); return SiteConfigImpl.DEFAULT_CONFIG_FILES_FILTER; ...
file) { for (File configFile : configFiles) { if (configFile.equals(file)) { return true; } } return false; } }; } }
csn_ccr
Sets default collection @param *string $collection Collection class name @return Eden\Sql\Index
public function setCollection($collection) { //Argument 1 must be a string Argument::i()->test(1, 'string'); if ($collection != self::COLLECTION && !is_subclass_of($collection, self::COLLECTION)) { Exception::i() ->setMessage(Exception::NOT_SUB_CO...
csn
Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration.
def unlock(ctx, pin): """ Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration. """ controller = ctx.obj['controller'] if not controller.is_fips: ctx.fail('This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.') if...
csn
Perform a serial-search on the summed probability array.
static int indexOfSerial(final double[] incr, final double v) { int index = -1; for (int i = 0; i < incr.length && index == -1; ++i) { if (incr[i] >= v) { index = i; } } return index; }
csn
func (g *Generator) String(length, cardinality int) string { if length > 32 { length = 32 } val := g.Uint64(cardinality) b := make([]byte,
8) binary.BigEndian.PutUint64(b, val) _, _ = g.hsh.Write(b) // no need to check err hashed := g.hsh.Sum(nil) g.hsh.Reset() return base32.StdEncoding.EncodeToString(hashed)[:length] }
csn_ccr
func (r *RegisterRequest) ChangesNode(node *Node) bool { // This means it's creating the node. if node == nil { return true } // If we've been asked to skip the node update, then say there are no // changes. if r.SkipNodeUpdate { return false } // Check if any of the node-level fields are being changed. ...
node.Address || r.Datacenter != node.Datacenter || !reflect.DeepEqual(r.TaggedAddresses, node.TaggedAddresses) || !reflect.DeepEqual(r.NodeMeta, node.Meta) { return true } return false }
csn_ccr
from __future__ import annotations from typing import Any from typing import Callable from typing import Generic from typing import Optional from typing import TypeVar from typing import Union T = TypeVar("T") class Maybe(Generic[T]): def __init__(self, value: Union[Optional[T], Maybe[T]] = None): if ...
#include <iostream> #include <cmath> #include <optional> #include <vector> using namespace std; template <typename T> auto operator>>(const optional<T>& monad, auto f) { if(!monad.has_value()) { return optional<remove_reference_t<decltype(*f(*monad))>>(); } return f(*monad)...
codetrans_contest
Read Data From Bucket @param resource $in userfilter.bucket brigade @param int $consumed @return string
protected function _getDataFromBucket($in, &$consumed) { $data = ''; while ($bucket = stream_bucket_make_writeable($in)) { $data .= $bucket->data; $consumed += $bucket->datalen; } return $data; }
csn