query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
protected function setFormMode() { if ($this->getBundleEntity() !== NULL) { $bundle = $this->getBundleEntity()->id(); // Set as variables, since the bundle might be different. $this->postViewDefault = 'post.' . $bundle .
'.default'; $this->postViewProfile = 'post.' . $bundle . '.profile'; $this->postViewGroup = 'post.' . $bundle . '.group'; } }
csn_ccr
and extract the error code accordingly
private JSONObject errorForUnwrappedException(Exception e, JmxRequest pJmxReq) { Throwable cause = e.getCause(); int code = cause instanceof IllegalArgumentException ? 400 : cause instanceof SecurityException ? 403 : 500; return getErrorJSON(code,cause, pJmxReq); }
csn
public function deleteItems($pWithChilds = false) { foreach ($this as $item) {
if ($item->getId()) { $item->delete($pWithChilds); } } return $this; }
csn_ccr
def get_nexusport_binding(port_id, vlan_id, switch_ip, instance_id): """Lists a nexusport binding.""" LOG.debug("get_nexusport_binding() called") return _lookup_all_nexus_bindings(port_id=port_id,
vlan_id=vlan_id, switch_ip=switch_ip, instance_id=instance_id)
csn_ccr
protected function getSearchFilter() { if ($this->searchFilterCache) { return $this->searchFilterCache; } // Check for given FilterClass $params = $this->getRequest()->getVar('q'); if (empty($params['FilterClass'])) { return null; } /...
$filterInfo = new ReflectionClass($filterClass); if (!$filterInfo->implementsInterface(LeftAndMain_SearchFilter::class)) { throw new InvalidArgumentException(sprintf('Invalid filter class passed: %s', $filterClass)); } return $this->searchFilterCache = Injector::inst()->createWith...
csn_ccr
get a formatter instance of specified date style and time style. @param {KISSY.Date.Formatter.Style} dateStyle date format style @param {KISSY.Date.Formatter.Style} timeStyle time format style @param {Object} locale @param {Number} timeZoneOffset time zone offset by minutes @returns {KISSY.Date.Gregorian} @static
function (dateStyle, timeStyle, locale, timeZoneOffset) { locale = locale || defaultLocale; var datePattern = ''; if (dateStyle !== undefined) { datePattern = locale.datePatterns[dateStyle]; } var timePattern = ''; if (timeStyle !==...
csn
Returns a filtered list of products for which a notification should be sent @param \Aimeos\MShop\Product\Item\Iface[] $products List of product items @param \Aimeos\MShop\Common\Item\Lists\Iface[] $listItems List of customer list items @return array Multi-dimensional associative list of list IDs as key and product / p...
protected function getProductList( array $products, array $listItems ) { $result = []; $priceManager = \Aimeos\MShop::create( $this->getContext(), 'price' ); foreach( $listItems as $id => $listItem ) { try { $refId = $listItem->getRefId(); $config = $listItem->getConfig(); if( isset( $produ...
csn
func resolveNumber(pv sqltypes.PlanValue, bindVars map[string]*querypb.BindVariable) (int64, error) { v, err := pv.ResolveValue(bindVars) if err != nil { return 0, err } ret,
err := sqltypes.ToInt64(v) if err != nil { return 0, err } return ret, nil }
csn_ccr
public static function make($action, $url, array $attributes = [], $disabled = false) { return new
static($action, $url, $attributes, $disabled); }
csn_ccr
// NewMockUi returns a fully initialized MockUi instance // which is safe for concurrent use.
func NewMockUi() *MockUi { m := new(MockUi) m.once.Do(m.init) return m }
csn
def run_tasks(self): ''' Runs all assigned task in separate green threads. If the task should not be run, schedule it ''' pool = Pool(len(self.tasks)) for task in self.tasks: # Launch a green thread to schedule the task
# A task will be managed by 2 green thread: execution thread and scheduling thread pool.spawn(self.run, task) return pool
csn_ccr
Detects the language of text within a request. <p>Sample code: <pre><code> try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) { String formattedParent = TranslationServiceClient.formatLocationName("[PROJECT]", "[LOCATION]"); String model = ""; String mimeType = ""; DetectLangu...
public final DetectLanguageResponse detectLanguage(String parent, String model, String mimeType) { if (!parent.isEmpty()) { LOCATION_PATH_TEMPLATE.validate(parent, "detectLanguage"); } DetectLanguageRequest request = DetectLanguageRequest.newBuilder() .setParent(parent) ...
csn
python dict remove any
def _remove_dict_keys_with_value(dict_, val): """Removes `dict` keys which have have `self` as value.""" return {k: v for k, v in dict_.items() if v is not val}
cosqa
Corrects splitting of dn parts @param array $dn Raw DN array @param array $separator Separator that was used when splitting @return array Corrected array @access protected
protected static function correct_dn_splitting($dn = array(), $separator = ',') { foreach ($dn as $key => $dn_value) { $dn_value = $dn[$key]; // refresh value (foreach caches!) // if the dn_value is not in attr=value format, then we had an // unescaped separator character...
csn
Normalize the file extension by ensuring it has the required one. @param file The original file name (must not be <code>null</code>). @param extension The desired extension, will replace the other one if has (must not be <code>null</code>). @return The normalized file with its extension. @throws LionEngineException If...
public static String normalizeExtension(String file, String extension) { Check.notNull(file); Check.notNull(extension); final int length = file.length() + Constant.DOT.length() + extension.length(); final StringBuilder builder = new StringBuilder(length).append(removeExtension(file)...
csn
Apply xslt stylesheet to xml logs file and crate an HTML report file. @param xmlLogsFile @param htmlReportFile
private void prettyprint(String xmlLogsFile, FileOutputStream htmlReportFile) throws Exception { TransformerFactory tFactory = TransformerFactory.newInstance(); // Fortify Mod: prevent external entity injection tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); ...
csn
func (s *DeploymentConfig) SetFailureThresholdPercentage(v int64) *DeploymentConfig {
s.FailureThresholdPercentage = &v return s }
csn_ccr
Take a list of adsorabtes and a corresponding reference system and return a list of dictionaries encoding the stoichiometry factors converting between adsorbates and reference molecules.
def get_stoichiometry_factors(adsorbates, references): """Take a list of adsorabtes and a corresponding reference system and return a list of dictionaries encoding the stoichiometry factors converting between adsorbates and reference molecules. """ stoichiometry = get_atomic_stoichiometry(refere...
csn
function Renderer(str, options) { options = options || {}; options.globals = options.globals || {}; options.functions = options.functions || {}; options.use = options.use || []; options.use = Array.isArray(options.use) ? options.use : [options.use]; options.imports = [join(__dirname, 'functions')].concat(op...
[]; options.filename = options.filename || 'stylus'; options.Evaluator = options.Evaluator || Evaluator; this.options = options; this.str = str; this.events = events; }
csn_ccr
public function autocomplete( $name, $list = [], $selected = [], array $inputAttributes = [], array $spanAttributes = [], $inputOnly = false ) { // Forces the ID attribute $inputAttributes['id'] = $name.'-ms'; if (!isset($inputAttributes['class...
will concatenate the span html unless $selectOnly is passed as false $spanHtml = $inputOnly ? '' : $this->span($name, $list, $selected, $spanAttributes); $inputAttributes = $this->attributes($inputAttributes); return $this->toHtmlString($spanHtml."<input type=\"text\"{$inputAttributes}>"); ...
csn_ccr
// NewTSDBTagValueIteratorAdapter return an iterator which implements tsdb.TagValueIterator.
func NewTSDBTagValueIteratorAdapter(itr TagValueIterator) tsdb.TagValueIterator { if itr == nil { return nil } return &tsdbTagValueIteratorAdapter{itr: itr} }
csn
public function status() { $this->_MBPush(); if (!($fp = $this->_Connect())) { $this->_MBPop(); return false; } $req = pack('nnNN', SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1); // len=4, body=1 if (!($this->_Send($fp, $req, 12)) || ...
$p += 8; $res = array(); for ($i = 0; $i < $rows; ++$i) { for ($j = 0; $j < $cols; ++$j) { list(, $len) = unpack('N*', substr($response, $p, 4)); $p += 4; $res[$i][] = substr($response, $p, $len); $p += $len; } ...
csn_ccr
Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session.
def validate_cookies(session, class_name): """ Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session. """ if not do_we_have_enough_cookies(session.cookies, class_name): return False url = CLASS_URL.format(class...
csn
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Add...
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` ...
csn
func NewCfAPI() *CfAPI { envs := cfenv.CurrentEnv() tokenConfig := &clientcredentials.Config{ ClientID: envs["CLIENT_ID"], ClientSecret: envs["CLIENT_SECRET"], Scopes: []string{}, TokenURL: envs["TOKEN_URL"],
} toReturn := new(CfAPI) toReturn.BaseAddress = envs["CF_API"] toReturn.Client = tokenConfig.Client(oauth2.NoContext) return toReturn }
csn_ccr
Execute a SQL statement using the current connection property. @param string $sql SQL statement to execute @throws PDOException
protected function execSQL($sql) { // Check and ignore empty statements if (trim($sql) == "") { return; } try { $this->totalSql++; if (!$this->autocommit) { $this->conn->beginTransaction(); } $stmt = $this...
csn
def get_revisions(page, page_num=1): """ Returns paginated queryset of PageRevision instances for specified Page instance. :param page: the page instance. :param page_num: the pagination page number. :rtype: django.db.models.query.QuerySet. """ revisions = page.revisions.order_by('-cr...
paginator = Paginator(revisions, 5) try: revisions = paginator.page(page_num) except PageNotAnInteger: revisions = paginator.page(1) except EmptyPage: revisions = paginator.page(paginator.num_pages) return revisions
csn_ccr
// ParseDeviceScanType parses a device scan type.
func ParseDeviceScanType(i interface{}) DeviceScanType { switch ti := i.(type) { case string: lti := strings.ToLower(ti) if lti == DeviceScanQuick.String() { return DeviceScanQuick } else if lti == DeviceScanDeep.String() { return DeviceScanDeep } i, err := strconv.Atoi(ti) if err != nil { return...
csn
Add all items of the given collection to the given list. @param <T> The component type of the list @param listToAddTo The list to add to @param collectionToAdd The elements to add to the list @return <code>true</code> if all items were added, <code>false</code> otherwise @see List#addAll(Collection)
public <T> boolean addAll(List<T> listToAddTo, Collection<? extends T> collectionToAdd) { return listToAddTo.addAll(collectionToAdd); }
csn
public function setFormatter($field, $formatter, $options = null) { // support for field names as array if (is_array($field)) { foreach ($field as $f) { $this->setFormatter($f, $formatter, $options);
} return $this; } if (!isset($this->columns[$field])) { throw new BaseException('Cannot format nonexistant field '.$field); } $this->columns[$field]['type'] = ''; $this->addFormatter($field, $formatter, $options); $this->last_column = $...
csn_ccr
Design a data structure that supports the following two operations: * `addWord` (or `add_word`) which adds a word, * `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter You may assume that all given words contain only...
import re class WordDictionary: def __init__(self): self.data=[] def add_word(self,x): self.data.append(x) def search(self,x): for word in self.data: if re.match(x+"\Z",word): return True return False
apps
Proceeds next drop step. @return array @since 0.2
public function nextDrop() { $drops = $this->countDrops(); if (count($drops)) { $currentStep = Yii::$app->session->get(self::SESSION_KEY, 0); $maxStep = Yii::$app->session->get(self::SESSION_STEPS, 0); if ($currentStep < $maxStep) { $this->t...
csn
Adjust path for executable use in executable file
def resource_path(relative): """Adjust path for executable use in executable file""" if hasattr(sys, "_MEIPASS"): return os.path.join(sys._MEIPASS, relative) return os.path.join(relative)
csn
Turns the given search hash into a URI style query string @method hashToString @for Core @static @param {Object} hash @return {String}
function hashToString(hash) { var keyValuePairs = []; angular.forEach(hash, function (value, key) { keyValuePairs.push(key + "=" + value); }); var params = keyValuePairs.join("&"); return encodeURI(params); }
csn
def iriToURI(iri): """Transform an IRI to a URI by escaping unicode.""" # According to RFC 3987, section 3.1, "Mapping of IRIs to URIs" if isinstance(iri, bytes):
iri = str(iri, encoding="utf-8") return iri.encode('ascii', errors='oid_percent_escape').decode()
csn_ccr
Compares the dimensions of an element to a container and determines collision events with container. @function @param {jQuery} element - jQuery object to test for collisions. @param {jQuery} parent - jQuery object to use as bounding container. @param {Boolean} lrOnly - set to true to check left and right values only. @...
function ImNotTouchingYou(element, parent, lrOnly, tbOnly, ignoreBottom) { return OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) === 0; }
csn
Creates a new interval with the specified duration after the start instant. @param duration the duration to add to the start to get the new end instant, null means zero @return an interval with the start from this interval and a calculated end @throws IllegalArgumentException if the duration is negative
public Interval withDurationAfterStart(ReadableDuration duration) { long durationMillis = DateTimeUtils.getDurationMillis(duration); if (durationMillis == toDurationMillis()) { return this; } Chronology chrono = getChronology(); long startMillis = getStartMillis(); ...
csn
find folder -type l | %prog size Get the size for all the paths that are pointed by the links
def size(args): """ find folder -type l | %prog size Get the size for all the paths that are pointed by the links """ from jcvi.utils.cbook import human_size p = OptionParser(size.__doc__) fp = sys.stdin results = [] for link_name in fp: link_name = link_name.strip() ...
csn
//read a string from the connected client
func (c *Connection) read() string { reply, err := c.bufin.ReadString('\n') if err != nil { fmt.Println("e ", err) } return reply }
csn
Retrieves all queues. :keyword str prefix: Optionally, only return queues that start with this value. :rtype: list :returns: A list of :py:class:`boto.sqs.queue.Queue` instances.
def get_all_queues(self, prefix=''): """ Retrieves all queues. :keyword str prefix: Optionally, only return queues that start with this value. :rtype: list :returns: A list of :py:class:`boto.sqs.queue.Queue` instances. """ params = {} if pref...
csn
// Read reads from a file handle.
func (f *win32File) Read(b []byte) (int, error) { c, err := f.prepareIo() if err != nil { return 0, err } defer f.wg.Done() if f.readDeadline.timedout.isSet() { return 0, ErrTimeout } var bytes uint32 err = syscall.ReadFile(f.handle, b, &bytes, &c.o) n, err := f.asyncIo(c, &f.readDeadline, bytes, err) r...
csn
public function addSubmit($name, $attr = []) { $e = new \FrenchFrogs\Form\Element\Submit($name, $attr); $e->setValue($name);
$e->setOptionAsPrimary(); $this->addAction($e); return $e; }
csn_ccr
Parser for the debugging shell. Treat everything after the first token as one literal entity. Whitespace characters between the first token and the next first non-whitespace character are preserved. For example, ' foo dicj didiw ' is parsed as ( 'foo', ' dicj didiw '...
def parse_line(self, line): """Parser for the debugging shell. Treat everything after the first token as one literal entity. Whitespace characters between the first token and the next first non-whitespace character are preserved. For example, ' foo dicj didiw ' is parsed as...
csn
```if-not:julia,racket Write a function that returns the total surface area and volume of a box as an array: `[area, volume]` ``` ```if:julia Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)` ``` ```if:racket Write a function that returns the total surface area and vo...
def get_size(w, h, d): area = 2*(w*h + h*d + w*d) volume = w*h*d return [area, volume]
apps
def serialize(template, options=SerializerOptions()): """Serialize the provided template according to the language specifications."""
context = SerializerContext(options) context.serialize(flatten(template)) return context.output
csn_ccr
def warn_logging(logger): # type: (logging.Logger) -> Callable """Create a `showwarning` function that uses the given logger. Arguments: logger (~logging.Logger): the logger to use. Returns: function: a function that can be used as the `warnings.showwarning`
callback. """ def showwarning(message, category, filename, lineno, file=None, line=None): logger.warning(message) return showwarning
csn_ccr
def add(self, **kwargs): """Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element. """ new_element = self._message_descriptor._concrete_class(**kwargs) new_element._SetListener(self._message_listener)
self._values.append(new_element) if not self._message_listener.dirty: self._message_listener.Modified() return new_element
csn_ccr
Autoload files and directories. @author Morten Rugaard <moru@nodes.dk> @return void
protected function autoloadFilesAndDirectories() { // Load files/directories from config file $autoload = config('nodes.autoload', null); if (empty($autoload)) { return; } foreach ($autoload as $item) { // Retrieve full path of item $itemP...
csn
Add custom words. Adds one or more words and their translations to the specified custom voice model. Adding a new translation for a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain no more than 20,000 entries. You must use credentials for the instance of...
public ServiceCall<Void> addWords(AddWordsOptions addWordsOptions) { Validator.notNull(addWordsOptions, "addWordsOptions cannot be null"); String[] pathSegments = { "v1/customizations", "words" }; String[] pathParameters = { addWordsOptions.customizationId() }; RequestBuilder builder = RequestBuilder.po...
csn
// Rename changes the name of the Shape to newName. Also updates // the associated API's reference to use newName.
func (s *Shape) Rename(newName string) { if s.AliasedShapeName { panic(fmt.Sprintf("attempted to rename %s, but flagged as aliased", s.ShapeName)) } for _, r := range s.refs { r.OrigShapeName = r.ShapeName r.ShapeName = newName } delete(s.API.Shapes, s.ShapeName) s.OrigShapeName = s.ShapeName s.API.Sh...
csn
function WindowParam(windowParamDict){ if(!(this instanceof WindowParam)) return new WindowParam(windowParamDict) windowParamDict = windowParamDict || {} // Check windowParamDict has the required fields // // checkType('int', 'windowParamDict.topRightCornerX', windowParamDict.topRightCornerX, {required...
// // checkType('int', 'windowParamDict.height', windowParamDict.height, {required: true}); // // Init parent class WindowParam.super_.call(this, windowParamDict) // Set object properties Object.defineProperties(this, { topRightCornerX: { writable: true, enumerable: true, value...
csn_ccr
func (s *Schedule) Validate(c *validation.Context) { if s.GetAmount() < 0 { c.Errorf("amount must be non-negative") } c.Enter("length") s.GetLength().Validate(c) switch n, err := s.Length.ToSeconds(); { case err != nil: c.Errorf("%s", err) case
n == 0: c.Errorf("duration or seconds is required") } c.Exit() c.Enter("start") s.GetStart().Validate(c) c.Exit() }
csn_ccr
Determine the release level of the umbrella package by examining the levels of all affected components and incrementing the umbrella by the highest level of a component release. In other words, if three components are released as patches, the umbrella will be a patch release. If there are any minor releases, the umbre...
private function determineUmbrellaLevel(array $release) { $levels = []; array_walk($release, function ($component) use (&$levels) { $levels[] = $component['level']; }); $levels = array_unique($levels); rsort($levels); // Since we don't use major versions...
csn
def modules_and_args(modules=True, states=False, names_only=False): ''' Walk the Salt install tree and return a dictionary or a list of the functions therein as well as their arguments. :param modules: Walk the modules directory if True :param states: Walk the states directory if True :param na...
salt myminion baredoc.modules_and_args myminion: ---------- [...] at.atrm: at.jobcheck: at.mod_watch: - name at.present: - unique_tag - name - timespec - job...
csn_ccr
func (c *Client) Ping(ctx context.Context)
error { _, _, err := c.pingTimeout(ctx) return err }
csn_ccr
def _GetAction(self, action, text): """Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): mac Wifi log text. Returns: str: a formatted string representing the known (or common) action. If the action is no...
if 'processSystemPSKAssoc' in action: wifi_parameters = self._WIFI_PARAMETERS_RE.search(text) if wifi_parameters: ssid = wifi_parameters.group(1) bssid = wifi_parameters.group(2) security = wifi_parameters.group(3) if not ssid: ssid = 'Unknown' if not bssid...
csn_ccr
public function getRaw() { $params = [ 'index' => $this->getIndex(), 'type' => $this->getType(),
'body' => $this->toDSL(), ]; return $this->connection->searchStatement($params); }
csn_ccr
public static function node($id) { $id = intval($id); if (empty($id)) return null; if (!static::$caching || empty(static::$_nodes[$id])) { $result = static::findOne($id); if (static::$caching) {
static::$_nodes[$id] = $result; } else { return $result; } } return static::$_nodes[$id]; }
csn_ccr
public static base_responses enable(nitro_service client, String monitorname[]) throws Exception { base_responses result = null; if (monitorname != null && monitorname.length > 0) { lbmonitor enableresources[] = new lbmonitor[monitorname.length]; for (int i=0;i<monitorname.length;i++){ enableresources[i] ...
enableresources[i].monitorname = monitorname[i]; } result = perform_operation_bulk_request(client, enableresources,"enable"); } return result; }
csn_ccr
public static void readFully(ReadableByteChannel channel, ByteBuffer dst) throws IOException { int expected = dst.remaining(); while (dst.hasRemaining()) { if (channel.read(dst) < 0) {
throw new EOFException(String.format("Not enough bytes in channel (expected %d).", expected)); } } }
csn_ccr
func (ar AggregatedSendResult) String() string { errMap := map[string]int{} for _, ack := range ar { if ack.error == nil { continue } errMap[ack.Error()]++ } ackCount := ar.AckCount() output := map[string]interface{}{} if ackCount > 0 {
output["successes"] = ackCount } if ackCount < len(ar) { output["failures"] = errMap } b, _ := json.Marshal(output) return string(b) }
csn_ccr
// Fetch collects all children below a given namespace // and concatenates their metric types into a single slice
func (mtt *mttNode) Fetch(ns []string) ([]*metricType, error) { children := mtt.fetch(ns) var mts []*metricType for _, child := range children { for _, mt := range child.mts { mts = append(mts, mt) } } if len(mts) == 0 && len(ns) > 0 { return nil, errorMetricsNotFound("/" + strings.Join(ns, "/")) } retu...
csn
protected void append0 (T item, boolean notify) { if (_count == _size) { makeMoreRoom();
} _items[_end] = item; _end = (_end + 1) % _size; _count++; if (notify) { notify(); } }
csn_ccr
func NewMembersSetPermissionsResult(TeamMemberId string, Role *AdminTier) *MembersSetPermissionsResult { s :=
new(MembersSetPermissionsResult) s.TeamMemberId = TeamMemberId s.Role = Role return s }
csn_ccr
Use the StructureNode relation StructureNode object @see useQuery() @param string $relationAlias optional alias for the relation, to be used as main alias in the secondary query @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' @return \gossi\trixionary\model\Structure...
public function useStructureNodeQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) { return $this ->joinStructureNode($relationAlias, $joinType) ->useQuery($relationAlias ? $relationAlias : 'StructureNode', '\gossi\trixionary\model\StructureNodeQuery'); }
csn
public function performReadonlyTransformation() { // Source and values are DataObject sets. $field = $this->castedCopy(GroupedColorPaletteField_Readonly::class);
$field->setSource($this->getSource()); $field->setReadonly(true); return $field; }
csn_ccr
%prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag Try to match up the expected location and gmap locations for particular genes. translated.ids was generated by fasta.translate --ids. tag must be one of "complete|pseudogene|partial".
def gffselect(args): """ %prog gffselect gmaplocation.bed expectedlocation.bed translated.ids tag Try to match up the expected location and gmap locations for particular genes. translated.ids was generated by fasta.translate --ids. tag must be one of "complete|pseudogene|partial". """ from ...
csn
Set the value of the input matched by given selector.
def set_input_value(self, selector, value): """Set the value of the input matched by given selector.""" script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % (selector, value) self.evaluate(script)
csn
Returns the result filters :rtype: str or None
def get_filters(self): """ Returns the result filters :rtype: str or None """ if self._filters: filters_list = self._filters if isinstance(filters_list[-1], Enum): filters_list = filters_list[:-1] return ' '.join( [fs.v...
csn
def _get_nr_bins(count): """depending on the number of data points, compute a best guess for an optimal number of bins https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width """ if count <= 30: # use the square-root choice, used by Excel and Co
k = np.ceil(np.sqrt(count)) else: # use Sturges' formula k = np.ceil(np.log2(count)) + 1 return int(k)
csn_ccr
def scan_keys(self, count=None): """Iter on all the key related to the current instance fields, using redis SCAN command Parameters ---------- count: int, default to None (redis uses 10) Hint for redis about the number of expected result Yields ------- ...
the way the SCAN command works in redis. """ pattern = self.make_key( self._name, self.pk.get(), '*' ) return self.database.scan_keys(pattern, count)
csn_ccr
protected function handleException($exception) { $app=Yii::app(); if($app instanceof CWebApplication) { if(($trace=$this->getExactTrace($exception))===null) { $fileName=$exception->getFile(); $errorLine=$exception->getLine(); } else { $fileName=$trace['file']; $errorLine=$trace['li...
instanceof CHttpException)?$exception->statusCode:500, 'type'=>get_class($exception), 'errorCode'=>$exception->getCode(), 'message'=>$exception->getMessage(), 'file'=>$fileName, 'line'=>$errorLine, 'trace'=>$exception->getTraceAsString(), 'traces'=>$trace, ); if(!headers_sent()) {...
csn_ccr
func (provider *DashboardProvisionerImpl) GetProvisionerResolvedPath(name string) string { for _, reader := range provider.fileReaders {
if reader.Cfg.Name == name { return reader.resolvedPath() } } return "" }
csn_ccr
def get_alignment_stream(self, plate=None, plate_value=None): """ Gets the alignment stream for a particular plate value :param plate: The plate on which the alignment node lives :param plate_value: The plate value to select the stream from the node :return: The alignment stream...
# TODO: Need to implement alignment nodes that live inside plates raise NotImplementedError("Currently only alignment nodes outside of plates are supported") return self.alignment_node.streams[plate]
csn_ccr
public function setTemplateOptions($name, $options) { if ($options instanceof Zend_Config) { $options = $options->toArray(); } elseif (!is_array($options)) { // require_once 'Zend/Cache/Exception.php'; throw new Zend_Cache_Exception('Options passed must be in'
. ' an associative array or instance of Zend_Config'); } if (!isset($this->_optionTemplates[$name])) { throw new Zend_Cache_Exception('A cache configuration template' . 'does not exist with the name "' . $name . '"'); } $this->_optionTemplates[...
csn_ccr
func (st *bundleSyncTask) checkBundleConditionNeedsUpdate(condition *cond_v1.Condition) bool { now := meta_v1.Now() condition.LastTransitionTime = now needsUpdate := cond_v1.PrepareCondition(st.bundle.Status.Conditions, condition) if needsUpdate && condition.Status == cond_v1.ConditionTrue { st.bundleTransition...
case smith_v1.BundleInProgress: eventType = core_v1.EventTypeNormal reason = smith.EventReasonBundleInProgress case smith_v1.BundleReady: eventType = core_v1.EventTypeNormal reason = smith.EventReasonBundleReady default: st.logger.Sugar().Errorf("Unexpected bundle condition type %q", condition.Type...
csn_ccr
public function isExternal() { $parentLink = $this->parentLink; if($parentLink===null){ //parentLink is null in case of baseUrl return false; }
$isExternal = $this->getHost() !== "" && ($this->getHost() != $parentLink->getHost()); return $isExternal; }
csn_ccr
function unmountAll(expressions) { each(expressions, function(expr) { if (expr instanceof Tag$1) { expr.unmount(true); } else
if (expr.tagName) { expr.tag.unmount(true); } else if (expr.unmount) { expr.unmount(); } }); }
csn_ccr
all other JS engines should be just fine
function (method) { var str = '' + method, i = str.indexOf(SUPER) ; return i < 0 ? false : isBoundary(str.charCodeAt(i - 1)) && isBoundary(str.charCodeAt(i + 5)); }
csn
maps verbosity options to log level
def configure_log_level(v, vv, vvv) if vvv log.level = ::Logger::DEBUG elsif vv log.level = ::Logger::INFO elsif v log.level = ::Logger::WARN else log.level = ::Logger::ERROR end end
csn
python dictionary case insensitive
def keys_to_snake_case(camel_case_dict): """ Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary. :param camel_case_dict: Dictionary with the keys to convert. :type camel_case_dict: Di...
cosqa
Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include Returns ------- Class1AffinityPredicto...
def filter_networks(self, predicate): """ Return a new Class1AffinityPredictor containing a subset of this predictor's neural networks. Parameters ---------- predicate : Class1NeuralNetwork -> boolean Function specifying which neural networks to include ...
csn
public String getValidationScript(TestContext context) { try { if (validationScriptResourcePath != null) { return context.replaceDynamicContentInString(FileUtils.readToString(FileUtils.getFileResource(validationScriptResourcePath, context), Charset.forName(con...
return context.replaceDynamicContentInString(validationScript); } else { return ""; } } catch (IOException e) { throw new CitrusRuntimeException("Failed to load validation script resource", e); } }
csn_ccr
protected static function GetWordListQuery($aTerms, $sLanguageId, $aFieldRestrictions = null, $sTypeOfFieldRestriction = 'OR') { $aTableQueries = array(); // get affected tables $aTableList = array(); foreach ($aTerms as $sTerm) { $sTableName = TdbShopSearchIndexer::GetIn...
$sTmpQuery .= " AND `{$sTermTable}`.`shop_search_field_weight_id` IN {$aFieldRestrictionQueries[$sTermTable]}"; } $sTmpQuery .= ')'; $aTableQueries[$sTermTable][] = $sTmpQuery; if (false == TdbShopSearchIndexer::searchWithAND()) { //OR `{$sSoundTable}`...
csn_ccr
def flatten(self, in_place=True): """ Merge all datasets into a single dataset. The default dataset is the last dataset to be merged, as it is considered to be the primary source of information and should overwrite all existing fields with the same key. Args: in_pla...
Returns: MultiTaskData: If the in_place flag is set to False. """ new_dataset = TaskData() for i, dataset in enumerate(self._datasets): if i != self._default_index: new_dataset.merge(dataset) new_dataset.merge(self.default_dataset) # ...
csn_ccr
public Vector3i add(Vector3ic v) {
return add(v.x(), v.y(), v.z(), thisOrNew()); }
csn_ccr
Start the input channel. While it isn't needed yet, the chain from which the start is coming from is in the parameter list. This method will only be called from the chain implementation. Regardless of what chains are referenced by the channel, if the state is initialized or quiesced, then the channel will be started. ...
private boolean startChannelInChain(Channel targetChannel, Chain chain) throws ChannelException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "startChannelInChain"); } // No need to check parameters since this is called from internal only. ...
csn
Synchronizes the specified fields names and sends the corresponding packet. @param <T> the type of the caller @param caller the caller @param syncNames the sync names
private <T, S extends ISyncableData> void doSync(T caller, String... syncNames) { @SuppressWarnings("unchecked") ISyncHandler<T, S> handler = (ISyncHandler<T, S>) getHandler(caller); if (handler == null) return; S data = handler.getSyncData(caller); int indexes = getFieldIndexes(handler, syncNames); Ma...
csn
Sets the billingaddress of the customer item. @param MShop_Common_Item_Address_Interface $address Billingaddress of the customer item
public function setPaymentAddress( MShop_Common_Item_Address_Interface $address ) { if ( $address === $this->_billingaddress && $address->isModified() === false ) { return; } $this->_billingaddress = $address; $this->setModified(); }
csn
Get append max limit type from the input @param extractType Extract type @param maxLimit @return Max limit type
private static AppendMaxLimitType getAppendLimitType(ExtractType extractType, String maxLimit) { LOG.debug("Getting append limit type"); AppendMaxLimitType limitType; switch (extractType) { case APPEND_DAILY: limitType = AppendMaxLimitType.CURRENTDATE; break; case APPEND_HOURLY: ...
csn
func (s *scheduler) HandleGomitEvent(e gomit.Event) { switch v := e.Body.(type) { case *scheduler_event.MetricCollectedEvent: log.WithFields(log.Fields{ "_module": "scheduler-events", "_block": "handle-events", "event-namespace": e.Namespace(), "task-id": v.TaskID, "metric-c...
task.UnsubscribePlugins() s.taskWatcherColl.handleTaskEnded(v.TaskID) case *scheduler_event.TaskDisabledEvent: log.WithFields(log.Fields{ "_module": "scheduler-events", "_block": "handle-events", "event-namespace": e.Namespace(), "task-id": v.TaskID, "disabled-reason": v....
csn_ccr
Return the current UnitState for the fleet cluster Args: machine_id (str): filter all UnitState objects to those originating from a specific machine unit_name (str): filter all UnitState objects to those related to a specific...
def list_unit_states(self, machine_id=None, unit_name=None): """Return the current UnitState for the fleet cluster Args: machine_id (str): filter all UnitState objects to those originating from a specific machine unit_name (str): filter all UnitSt...
csn
python json store boolean
def from_json(value, **kwargs): """Coerces JSON string to boolean""" if isinstance(value, string_types): value = value.upper() if value in ('TRUE', 'Y', 'YES', 'ON'): return True if value in ('FALSE', 'N', 'NO', 'OFF'): return False ...
cosqa
public void callProcedure(AuthUser user, boolean isAdmin, int timeout, ProcedureCallback cb, String procName, Object[] args) { // since we know the caller, th...
DEFAULT_INTERNAL_ADAPTER_NAME, isAdmin, connectionId()); assert(m_dispatcher != null); // JHH: I have no idea why we need to do this, but CL crashes if we don't. Sigh. try { task = MiscUtils.roundTripForCL(task); } catch (Exception e) { String msg =...
csn_ccr
def onekgreek_tei_xml_to_text(): """Find TEI XML dir of TEI XML for the First 1k Years of Greek corpus.""" if not bs4_installed: logger.error('Install `bs4` and `lxml` to parse these TEI files.') raise ImportError xml_dir = os.path.expanduser('~/cltk_data/greek/text/greek_text_first1kgreek/d...
_, xml_name = os.path.split(xml_path) xml_name = xml_name.rstrip('.xml') xml_name += '.txt' with open(xml_path) as file_open: soup = BeautifulSoup(file_open, 'lxml') body = soup.body text = body.get_text() new_plaintext_path = os.path.join(new_dir, xml_name)...
csn_ccr
Translate an assignment to an array element. @param lval The array assignment expression @param result The value being assigned to the given array element @param context The enclosing context @return
private Context translateArrayAssign(WyilFile.Expr.ArrayAccess lval, Expr rval, Context context) { // Translate src and index expressions Pair<Expr, Context> p1 = translateExpressionWithChecks(lval.getFirstOperand(), null, context); Pair<Expr, Context> p2 = translateExpressionWithChecks(lval.getSecondOperand(), n...
csn
Add either select_related or prefetch_related to fields of the qs
def optimize(qs, info_dict, field_map): """Add either select_related or prefetch_related to fields of the qs""" fields = collect_fields(info_dict) for field in fields: if field in field_map: field_name, opt = field_map[field] qs = (qs.prefetch_related(field_name) ...
csn
opens a new Recorder for writing. The recorder gets a new ID. The lifecycle of the dataRecorder is managed by the current implementation of {@link @return created dataRecorder
private IXADataRecorder createXADataRecorder() { try { long xaDataRecorderId = this.messageSeqGenerator.generate(); // create a new Logger IDataLogger dataLogger = this.dataLoggerFactory.instanciateLogger(Long.toString(xaDataRecorderId)); // create a new XADataLogger...
csn
Given the hash, this function will remove it from the cache. @param string $hash The user defined hash of the data @param string $namespace Delete multiple items by a namespace @return boolean
public function delete($hash = null, $namespace = null) { if ($this->cacheProvider instanceof iNamespacedCache) { return $this->cacheProvider->delete($hash, $namespace); } return $this->cacheProvider->delete($hash); }
csn
recovers the data of the dataLogger and provides the recovered data to the connection via the replaylistener
@Override public void recover() { // not revoverable if (this.getCoreConnection() == null || !ImplementorUtils.isImplementationOf(getCoreConnection(), IXADataRecorderAware.class)) { return; } IXADataRecorderAware con = ImplementorUtils.cast(getCoreConnection(), IXADataR...
csn