query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
protected function _getAbsPath(string $resName): string { foreach ($this->_resDir as $dir) { $absPath = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $resName;
if (file_exists($absPath)) { return $absPath; } } return ""; }
csn_ccr
func (p *siprng) Seed(k [16]byte) { p.k0 = binary.LittleEndian.Uint64(k[0:8])
p.k1 = binary.LittleEndian.Uint64(k[8:16]) p.ctr = 1 }
csn_ccr
Extracts an array of image objects, created from the encoded pixel data using the image related elements in the DICOM object. @note Creates an array of image objects in accordance with the selected image processor. Available processors are :rmagick and :mini_magick. @param [Hash] options the options to use for ext...
def images(options={}) images = Array.new if exists?(PIXEL_TAG) # Gather the pixel data strings, and pick a single frame if indicated by options: strings = image_strings(split_to_frames=true) strings = [strings[options[:frame]]] if options[:frame] if compression? # ...
csn
Generate random numbers @param integer $length @return string
public function randomNumbers($length = 6) { $nums = '0123456789'; $out = $nums[mt_rand(1, strlen($nums)-1)]; for ($p = 0; $p < $length-1; $p++) { $out .= $nums[mt_rand(0, strlen($nums)-1)]; } return $out; }
csn
public function deleteMigration(APIMigration $migration) { $this->createTableIfNeeded(); $conn = $this->getConnection();
$conn->delete($this->tableName, array('migration' => $migration->name)); }
csn_ccr
Generate item document. @param Item $item
public function addItem(Item $item) { $itemUUID = $item->composeUUID(); $this->elementsToUpdate[$itemUUID] = $item; unset($this->elementsToDelete[$itemUUID]); }
csn
func (r *Response) DecodeFrom(resource interface{}, body io.Reader) error { if resource == nil { return errors.New("No resource")
} dec, err := r.MediaType.Decoder(body) if err != nil { return err } if err := dec.Decode(resource); err != nil { return err } return nil }
csn_ccr
def get_rich_menu_image(self, rich_menu_id, timeout=None): """Call download rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image :param str rich_menu_id: ID of the rich menu with the image to be downloaded :param timeout: (optional) ...
:rtype: :py:class:`linebot.models.responses.Content` :return: Content instance """ response = self._get( '/v2/bot/richmenu/{rich_menu_id}/content'.format(rich_menu_id=rich_menu_id), timeout=timeout ) return Content(response)
csn_ccr
def keyevent2tuple(event): """Convert QKeyEvent instance into a tuple""" return (event.type(),
event.key(), event.modifiers(), event.text(), event.isAutoRepeat(), event.count())
csn_ccr
// IsRunning checks if FittedCloud Agent is running
func IsRunning() (string, error) { var ( cmdOut []byte err error path string ) cmd := "fcagent" args := []string{"echo"} if path, err = exec.LookPath(cmd); err != nil { log.Debug(err) } log.Debug(path, args[0]) if cmdOut, err = exec.Command(cmd, args...).Output(); err != nil { log.Debug(err) }...
csn
Unsubscribe from a event given a subject. @param string $sid Subscription ID. @param integer $quantity Quantity of messages. @return void
public function unsubscribe($sid, $quantity = null) { $msg = 'UNSUB '.$sid; if ($quantity !== null) { $msg = $msg.' '.$quantity; } $this->send($msg); if ($quantity === null) { unset($this->subscriptions[$sid]); } }
csn
def update_question(self, question_form): """Updates an existing question. arg: question_form (osid.assessment.QuestionForm): the form containing the elements to be updated raise: IllegalState - ``question_form`` already used in an update transaction ...
raise errors.InvalidArgument('one or more of the form elements is invalid') item_id = Id(question_form._my_map['itemId']).get_identifier() item = collection.find_one({'$and': [{'_id': ObjectId(item_id)}, {'assigned' + self._catalog_name + 'Ids': {'$in': [str(s...
csn_ccr
// setNumFmt provides a function to check if number format code in the range // of built-in values.
func setNumFmt(style *xlsxStyleSheet, formatStyle *formatStyle) int { dp := "0." numFmtID := 164 // Default custom number format code from 164. if formatStyle.DecimalPlaces < 0 || formatStyle.DecimalPlaces > 30 { formatStyle.DecimalPlaces = 2 } for i := 0; i < formatStyle.DecimalPlaces; i++ { dp += "0" } if ...
csn
Decode the given job. @param object $job @return object
protected function decode($job) { $job->payload = json_decode($job->payload); $job->retried_by = collect(json_decode($job->retried_by)) ->sortByDesc('retried_at')->values(); return $job; }
csn
Group up selectors by some key @param array $data @param string $key @return array
public static function groupBy($data, $key) { $res = []; for ($i = 0, $l = sizeof($data); $i < $l; $i++) { $item = $data[$i]; $value = empty($item[$key]) ? __undefined : $item[$key]; if (empty($res[$value])) { $res[$value] = []; } ...
csn
protected function parseProperty(ClassBuilder $classBuilder, NodeStream $stream) { $builder = new PropertyBuilder(); $comments = array(); $propertyNodes = array( TokenParser::NODE_PUBLIC_PROPERTY => 'public', TokenParser::NODE_PROTECTED_PROPERTY => 'protected', ...
$builder->addAccessor($stream->current()->getValue()); $stream->next(); } while ($stream->is(TokenParser::NODE_PROPERTY_COMMENT)) { $comments[] = $stream->current()->getValue(); $stream->next(); } if (count($comments) > 0) { $buil...
csn_ccr
Page should redirect message. @static @param string $encodedurl redirect url @return string
public static function plain_redirect_message($encodedurl) { $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'. $encodedurl .'">'. get_string('continue') .'</a></div>'; return self::p...
csn
def __properties_update(self, properties): """ Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else ...
# See if new properties are different if properties == self.__properties: return False # Store the copy (before storing data) self.__properties = properties self.__updated = True # Store the data # it will cause File...
csn_ccr
public function parse($contents, $includeDefaults = false) { $old_libxml_error = libxml_use_internal_errors(true); $dom = new DOMDocument; if(@$dom->loadHTML($contents) === false) { throw new RuntimeException("Contents is empty"); } libx...
} else if($tag->hasAttribute('property') && $tag->hasAttribute('content')) { $this->addMeta($tag->getAttribute('property'), $tag->getAttribute('content'), self::APPEND); } } if($includeDefaults) { $titles = $dom->getElementsByTagName('title'); if (...
csn_ccr
func (_class VMMetricsClass) GetLastUpdated(sessionID SessionRef, self VMMetricsRef) (_retval time.Time, _err error) { _method := "VM_metrics.get_last_updated" _sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
if _err != nil { return } _selfArg, _err := convertVMMetricsRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self) if _err != nil { return } _result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg) if _err != nil { return } _retval, _err = convertTimeToGo(_method + " -> ", _result.Value)...
csn_ccr
def _get_default_letters(model_admin=None): """ Returns the set of letters defined in the configuration variable DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or list and returns a set. If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET attribute and use...
if callable(default_letters): return set(default_letters()) elif isinstance(default_letters, str): return set([x for x in default_letters]) elif isinstance(default_letters, str): return set([x for x in default_letters.decode('utf8')]) elif isinstance(default_letters, (tuple, list))...
csn_ccr
Initialize from ElementBase interface. @param ElementBase $el @return self
public static function fromElementBase(ElementBase $el): self { // if element is already wrapped if ($el instanceof self) { return $el; } return new self($el->asElement()); }
csn
public function setBodySignedLen($len) { if (true === $len) { $this->showLen = true; $this->maxLen = PHP_INT_MAX; } elseif (false === $len) { $this->showLen = false; $this->maxLen = PHP_INT_MAX;
} else { $this->showLen = true; $this->maxLen = (int) $len; } return $this; }
csn_ccr
Get path for the specified Theme. @param string $slug @return string
public function getThemePath($slug) { if (Str::length($slug) > 3) { $theme = Str::studly($slug); } else { $theme = Str::upper($slug); } return $this->getThemesPath() .DS .$theme .DS; }
csn
An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optional
def groups_to_display(self, value): """An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. Max of 25 groups. :param groups_to_display: Unsubscribe groups to display :type groups_to_display: GroupsToDisplay, list(int), optio...
csn
python delete dictionary entry if exists
def __delitem__ (self, key): """Remove key from dict.""" self._keys.remove(key) super(ListDict, self).__delitem__(key)
cosqa
protected function executeHandler($handler, array $parameters) { if($handler instanceof Closure) { return $this->executeClosureHandler($handler, $parameters); } $handler
= $this->resolveHandler($handler); return $this->executeClassHandler($handler, $parameters); }
csn_ccr
// NewReference will create and initialize a new Reference value
func NewReference(name string, section *Section) *Reference { return &Reference{ section: section, name: name, } }
csn
protected static function _detectLimitClauseStyle($connection_name) { switch(self::get_db($connection_name)->getAttribute(PDO::ATTR_DRIVER_NAME)) { case 'sqlsrv': case 'dblib': case 'mssql':
return One::LIMIT_STYLE_TOP_N; default: return One::LIMIT_STYLE_LIMIT; } }
csn_ccr
def update_where(self, col, value, where_col_list, where_value_list): """ updates the array to set cell = value where col_list == val_list """ if type(col) is str: col_ndx = self.get_col_by_name(col)
else: col_ndx = col #print('col_ndx = ', col_ndx ) #print("updating " + col + " to " , value, " where " , where_col_list , " = " , where_value_list) new_arr = self.select_where(where_col_list, where_value_list) #print('new_arr', new_arr) for r in new_arr: ...
csn_ccr
Starts a new or existing session. @param array $options @return bool @throws \RuntimeException
public function start(array $options = null) { $sessionStatus = \session_status(); if ($sessionStatus === PHP_SESSION_DISABLED) { throw new \RuntimeException('PHP sessions are disabled'); } if ($sessionStatus === PHP_SESSION_ACTIVE) { throw new \RuntimeExcep...
csn
public void loadProvidedPropertiesIfAvailable(File providedPropertiesFile, boolean replaceAllProperties) throws MojoExecutionException { if (providedPropertiesFile.exists()) { Properties providedPropertySet = loadPropertiesFile(providedPropertiesFile); if (replaceAllProperties) { ...
this.properties = providedPropertySet; } else { this.properties.putAll(providedPropertySet); } } }
csn_ccr
def plot(self, f, lfilter=None, plot_xy=False, **kargs): """Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted """ # Python...
self.res if lfilter(*e)] # Mimic the default gnuplot output if kargs == {}: kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS if plot_xy: lines = plt.plot(*zip(*lst_pkts), **kargs) else: lines = plt.plot(lst_pkts, **kargs) # Call show() if matplotlib is...
csn_ccr
protected function print_debug_time() { if (!$this->get_debug()) { return; } $time = $this->query_time(); $message = "Query took: {$time} seconds.\n"; if (CLI_SCRIPT) { echo $message; echo "--------------------------------\n";
} else if (AJAX_SCRIPT) { error_log($message); error_log("--------------------------------"); } else { echo s($message); echo "<hr />\n"; } }
csn_ccr
def set_hparams_from_args(args): """Set hparams overrides from unparsed args list.""" if not args: return hp_prefix = "--hp_" tf.logging.info("Found unparsed command-line arguments. Checking if any " "start with %s and interpreting those as hparams "
"settings.", hp_prefix) pairs = [] i = 0 while i < len(args): arg = args[i] if arg.startswith(hp_prefix): pairs.append((arg[len(hp_prefix):], args[i+1])) i += 2 else: tf.logging.warn("Found unknown flag: %s", arg) i += 1 as_hparams = ",".join(["%s=%s" % (key, val) ...
csn_ccr
public function getTemplateVariables() { return array_merge($this->template_variables, [ 'options' => $this->getOptions(),
'column' => $this->getColumn(), 'key' => $this->getKey(), 'status' => $this, ]); }
csn_ccr
def logger(self, iteration, ret): """Print out relevant information at each epoch""" print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0])) entropies = getEntropies(self.model) print("Entropy and max entropy: ", float(entropies[0]), entropies[1]) print("Training time for epoch=", self.ep...
100.0*ret[noise]["accuracy"])) print("Full epoch time =", self.epoch_time) if ret[0.0]["accuracy"] > 0.7: self.best_noise_score = max(ret[0.1]["accuracy"], self.best_noise_score) self.best_epoch = iteration
csn_ccr
Use this API to unset the properties of pqpolicy resource. Properties that need to be unset are specified in args array.
public static base_response unset(nitro_service client, pqpolicy resource, String[] args) throws Exception{ pqpolicy unsetresource = new pqpolicy(); unsetresource.policyname = resource.policyname; return unsetresource.unset_resource(client,args); }
csn
Check if a selector exists. @param string $css_selector The CSS selector used to get the desired elements. @return boolean Returns if the element does exist.
public function exists($css_selector) { $xpath_selector = $this->_css_toxpath_selector($css_selector); $nodelist = $this->xpath->query($xpath_selector); if ($nodelist->item(0) === null) return false; return true; }
csn
public function renderItem(array $context, CmsItemInterface $item, string $viewType, array $parameters = [], ?string $viewContext = null): string { try { return $this->renderer->renderValue( $item, $this->getViewContext($context, $viewContext), ['v...
'Error rendering an item with value "%s" and value type "%s"', $item->getValue(), $item->getValueType() ); $this->errorHandler->handleError($t, $message); } return ''; }
csn_ccr
Returns the name of the best authentication method that the server has advertised. @return mixed Returns a string containing the name of the best supported authentication method or a PEAR_Error object if a failure condition is encountered. @since 1.1.0
protected function getBestAuthMethod() { $available_methods = explode(' ', $this->esmtp['AUTH']); foreach ($this->auth_methods as $method => $callback) { if (in_array($method, $available_methods)) { return $method; } } return PEAR::raiseError...
csn
add event name to title attribute on mouseover.
function(event, jsEvent, view) { if (view.name !== 'agendaDay') { $(jsEvent.target).attr('title', event.title); } }
csn
def get_event_abi(self, contract_name: str, event_name: str) -> Dict: """ Returns the ABI for a given event. """ # Import locally to avoid web3 dependency during installation via `compile_contracts` from web3.utils.contracts import find_matching_event_abi assert self.contracts, 'Contrac...
contract_abi = self.get_contract_abi(contract_name) return find_matching_event_abi( abi=contract_abi, event_name=event_name, )
csn_ccr
Helper method to assign the meta of the given element The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is then removed from the dictionary. :param meta_data: The loaded meta data :param element_m: The element model that is suppo...
def _copy_element_meta_data_from_meta_file_data(meta_data, element_m, element_name, element_id): """Helper method to assign the meta of the given element The method assigns the meta data of the elements from the given meta data dictionary. The copied meta data is then removed from the dictionar...
csn
with open('unixdict.txt', 'rt') as f: for line in f.readlines(): if not any(c in 'aiou' for c in line) and sum(c=='e' for c in line)>3: print(line.strip())
#include <iostream> #include <fstream> bool test(const std::string &line) { unsigned int e = 0; for (char c : line) { switch(std::tolower(c)) { case 'a': return false; case 'i': return false; case 'o': return false; case 'u': return false; cas...
codetrans_contest
Wait for worker manager.
public function exitWorkerManager(int $sig, array $pid): void { $this->logger->debug('fork manager ['.$pid['pid'].'] exit with ['.$sig.']', [ 'category' => get_class($this), ]); pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED); $this->cleanup(SIGTERM); }
csn
def reset(self): """Delete all data for this experiment.""" for alternative in self.alternatives:
alternative.reset() self.reset_winner() self.increment_version()
csn_ccr
Starts the database instance running on the Data Store machine. Inputs: dataStoreItemName - name of the item to start machineName - name of the machine to start on
def startDataStoreMachine(self, dataStoreItemName, machineName): """ Starts the database instance running on the Data Store machine. Inputs: dataStoreItemName - name of the item to start machineName - name of the machine to start on """ url = self._url + "/...
csn
func IsLoopback(host string) bool { if strings.Contains(host, ":") { var err error host, _, err = net.SplitHostPort(host) if err != nil { return false } } ips, err
:= net.LookupIP(host) if err != nil { return false } for _, ip := range ips { if ip.IsLoopback() { return true } } return false }
csn_ccr
def get_zero_position(self): """ Returns programmed zero position in OTP memory. """ LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB)
MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB) DATA = (MSB << 6) + LSB return DATA
csn_ccr
def _purge(dir, pattern, reason=''): """ delete files in dir that match pattern """ for f in os.listdir(dir): if re.search(pattern, f):
print "Purging file {0}. {1}".format(f, reason) os.remove(os.path.join(dir, f))
csn_ccr
def eprints_description(metadataPolicy, dataPolicy, submissionPolicy=None, content=None): """Generate the eprints element for the identify response. The eprints container is used by the e-print community to describe the content and policies of repositories. For the full specific...
EPRINTS_SCHEMA_LOCATION_XSD)) if content: contentElement = etree.Element('content') for key, value in content.items(): contentElement.append(E(key, value)) eprints.append(contentElement) metadataPolicyElement = etree.Element('metadataPolicy') fo...
csn_ccr
Loads the certificate chain from the URL. This method loads the certificate chain from the certificate cache. If there is a cache miss, the certificate chain is loaded from the certificate URL using the :py:func:`cryptography.x509.load_pem_x509_certificate` method. The x509 back...
def _load_cert_chain(self, cert_url, x509_backend=default_backend()): # type: (str, X509Backend) -> Certificate """Loads the certificate chain from the URL. This method loads the certificate chain from the certificate cache. If there is a cache miss, the certificate chain is loa...
csn
def processEnded(self, reason): """ Connected process shut down """ log_debug("{name} process exited", name=self.name) if self.deferred: if reason.type == ProcessDone: self.deferred.callback(reason.value.exitCode)
elif reason.type == ProcessTerminated: self.deferred.errback(reason) return self.deferred
csn_ccr
android 2.x doesn't support Data-URI spec
function _getAndroid() { var android = false; var sAgent = navigator.userAgent; if (/android/i.test(sAgent)) { // android android = true; var aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i); if (aMat && aMat[1]) { android = parseFloat(aMat[1]); } } return android; }
csn
zEventCustomPopupWasClosed, This is called automatically whenever the CustomPopup that is associated with this time picker is closed. This should be called regardless of the type of event which caused the popup to close. Notes: The popup can be automatically closed for various reasons. 1) The user may press escape. 2)...
@Override public void zEventCustomPopupWasClosed(CustomPopup popup) { popup = null; if (timeMenuPanel != null) { timeMenuPanel.clearParent(); } timeMenuPanel = null; lastPopupCloseTime = Instant.now(); }
csn
public function toPHP($value, Driver $driver) { if ($value === null || strpos($value, '0000-00-00') === 0) { return null; }
$instance = clone $this->_datetimeInstance; $instance = $instance->modify($value); if ($this->setToDateStart) { $instance = $instance->setTime(0, 0, 0); } return $instance; }
csn_ccr
Returns all basic information about the exception in a simple array for further convertion to other languages @param Inspector $inspector @param bool $shouldAddTrace @return array
public static function formatExceptionAsDataArray(Inspector $inspector, $shouldAddTrace) { $exception = $inspector->getException(); $response = [ 'type' => get_class($exception), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), ...
csn
Returns the data cell content. This method renders a hyperlink in the data cell. @param integer $row the row number (zero-based) @return string the data cell content. @since 1.1.16
public function getDataCellContent($row) { $data=$this->grid->dataProvider->data[$row]; if($this->urlExpression!==null) $url=$this->evaluateExpression($this->urlExpression,array('data'=>$data,'row'=>$row)); else $url=$this->url; if($this->labelExpression!==null) $label=$this->evaluateExpression($this-...
csn
// Write writes the compressed form of b to the underlying io.Writer. // Decompressed data blocks are limited to BlockSize, so individual // byte slices may span block boundaries, however the Writer attempts // to keep each write within a single data block.
func (bg *Writer) Write(b []byte) (int, error) { if bg.closed { return 0, ErrClosed } err := bg.Error() if err != nil { return 0, err } c := bg.active var n int for ; len(b) > 0 && err == nil; err = bg.Error() { var _n int if c.next == 0 || c.next+len(b) <= len(c.block) { _n = copy(c.block[c.next:],...
csn
def JobDueToRun(self, job): """Determines if the given job is due for another run. Args: job: The cron job rdfvalue object. Returns: True if it is time to run based on the specified frequency. """ if not job.enabled: return False if job.forced_run_requested: return Tru...
job.last_run_time + job.frequency > now): return False # No currently executing job - lets go. if not job.current_run_id: return True # There is a job executing but we allow overruns. if job.allow_overruns: return True return False
csn_ccr
protected function cleanupVersionedOrphans($baseTable, $childTable) { // Avoid if disabled if ($this->owner->config()->get('versioned_orphans_disabled')) { return; } // Skip if tables are the same (ignore case) if (strcasecmp($childTable, $baseTable) === 0) { ...
$baseTable, "\"{$childTable}\".\"RecordID\" = \"{$baseTable}\".\"RecordID\" AND \"{$childTable}\".\"Version\" = \"{$baseTable}\".\"Version\"" ) ->addWhere("\"{$baseTable}\".\"ID\" IS NULL"); } $count = $orphanedQuery->count(); ...
csn_ccr
fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed to generate diurnal features of windspeed using a cosine function
def fit_cosine_function(wind): """fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed to generate diurnal features of windspeed using a cosine function """ wind_daily = wind.groupby(wind.index.date)....
csn
// Backup takes a backup of the full application stack and returns the filename // that it is written to.
func (dao *ControlPlaneDao) Backup(backupRequest model.BackupRequest, filename *string) (err error) { ctx := datastore.Get() if len(backupRequest.Username) > 0 { ctx.SetUser(backupRequest.Username) } // synchronize the dfs dfslocker := dao.facade.DFSLock(ctx) dfslocker.Lock("backup") defer dfslocker.Unlock() ...
csn
func (f *Function) RollbackVersion(version string) error { f.Log.Info("rolling back") alias, err := f.currentVersionAlias() if err != nil { return err } f.Log.Debugf("current version: %s", *alias.FunctionVersion) if version == *alias.FunctionVersion { return errors.New("Specified version currently deployed...
_, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{ FunctionName: &f.FunctionName, Name: &f.Alias, FunctionVersion: &version, }) if err != nil { return err } f.Log.WithField("current version", version).Info("function rolled back") return nil }
csn_ccr
This function is automatically called at launch
def pyGeno_init() : """This function is automatically called at launch""" global db, dbConf global pyGeno_SETTINGS_PATH global pyGeno_RABA_DBFILE global pyGeno_DATA_PATH if not checkPythonVersion() : raise PythonVersionError("==> FATAL: pyGeno only works with python 2.7 and above, please upgrade your pyth...
csn
Run a case untile the specifiend endtime
def run_until(self, endtime, timeunit='minutes', save=True): """ Run a case untile the specifiend endtime """ integrator = self.case.solver.Integrator integrator.rununtil(endtime, timeunit) if save is True: self.case.save()
csn
public MobicentsSipSession getSipSession(final SipSessionKey key, final boolean create, final SipFactoryImpl sipFactoryImpl, final MobicentsSipApplicationSession sipApplicationSessionImpl) { if(logger.isDebugEnabled()) { logger.debug("getSipSession - key=" + key + ", create=" + create + ", sipApplicationSessionImp...
key.getFromTag()=" + key.getFromTag() + ", key.getToTag()=" + key.getToTag()); } } logger.debug("getSipSession - existing sipSessionImpl=" + sipSessionImpl); } if(sipSessionImpl == null && create) { if(logger.isDebugEnabled()) { logger.debug("getSipSession - creating new sip session"); }...
csn_ccr
// PullPubSubOnDevServer is called on dev server to pull messages from PubSub // subscription associated with given publisher. // // Part of the internal interface, doesn't check ACLs.
func (e *engineImpl) PullPubSubOnDevServer(c context.Context, taskManagerName, publisher string) error { _, sub := e.genTopicAndSubNames(c, taskManagerName, publisher) msg, ack, err := pullSubcription(c, sub, "") if err != nil { return err } if msg == nil { logging.Infof(c, "No new PubSub messages") return n...
csn
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
public static Object _if(EvaluationContext ctx, Object logicalTest, @IntegerDefault(0) Object valueIfTrue, @BooleanDefault(false) Object valueIfFalse) { return Conversions.toBoolean(logicalTest, ctx) ? valueIfTrue : valueIfFalse; }
csn
def _handle_keypad_message(self, data): """ Handle keypad messages. :param data: keypad message to parse :type data: string :returns: :py:class:`~alarmdecoder.messages.Message` """ msg = Message(data) if self._internal_address_mask & msg.mask > 0:
if not self._ignore_message_states: self._update_internal_states(msg) self.on_message(message=msg) return msg
csn_ccr
Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list.
def next(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a single row, and returns the row that occurs after the input row in the original set of rows. If the input row happens to be the last row, we will return an empty list. """ if not row...
csn
func (c *client) BuildPurge(owner, name string, before int) error { param := fmt.Sprintf("before=%d", before) uri :=
fmt.Sprintf(pathBuilds, c.addr, owner, name, param) err := c.delete(uri) return err }
csn_ccr
Get details about the host that is executing habu.
def gather_details(): """Get details about the host that is executing habu.""" try: data = { 'kernel': platform.uname(), 'distribution': platform.linux_distribution(), 'libc': platform.libc_ver(), 'arch': platform.machine(), 'python_version': p...
csn
func handleExtensionsParseDidStart(p *Params) ([]gqlerrors.FormattedError, parseFinishFuncHandler) { fs := map[string]ParseFinishFunc{} errs := gqlerrors.FormattedErrors{} for _, ext := range p.Schema.extensions { var ( ctx context.Context finishFn ParseFinishFunc ) // catch panic from an extension'...
fs[ext.Name()] = finishFn }() } return errs, func(err error) []gqlerrors.FormattedError { errs := gqlerrors.FormattedErrors{} for name, fn := range fs { func() { // catch panic from a finishFn defer func() { if r := recover(); r != nil { errs = append(errs, gqlerrors.FormatError(fmt.Erro...
csn_ccr
Tell whether a variable is an object reference. Due to garbage collection, some objects happen to get the id of a distinct variable. As a consequence, linking is not ready yet and `isreference` returns ``False``.
def isreference(a): """ Tell whether a variable is an object reference. Due to garbage collection, some objects happen to get the id of a distinct variable. As a consequence, linking is not ready yet and `isreference` returns ``False``. """ return False return id(a) != id(copy.copy(a)) ...
csn
func NewPool(parentCtx context.Context) *Pool { baseCtx, baseCancel := context.WithCancel(parentCtx) ctx, cancel := context.WithCancel(baseCtx) return &Pool{
baseCtx: baseCtx, baseCancel: baseCancel, ctx: ctx, cancel: cancel, } }
csn_ccr
private function regenerateTaskById($id) { try { $response = $this->taskQueueService->regenerateTask($id); if ($response) { $this->output->writeln("<info>Regeneration succes</info>"); } else { $this->output->writeln("<error>Regeneration suc...
} } catch (TaskQueueServiceException $e) { $this->output->writeln("<error>Error!:</error>" . $e->getMessage()); } }
csn_ccr
function ( MaterialNode ) { var mappingType = MaterialNode.MappingInformationType; var referenceType = MaterialNode.ReferenceInformationType; if ( mappingType === 'NoMappingInformation' ) { return { dataSize: 1, buffer: [ 0 ], indices: [ 0 ], mappingType: 'AllSame', referenceTyp...
index in the buffer, // for conforming with the other functions we've written for other data. var materialIndices = []; for ( var i = 0; i < materialIndexBuffer.length; ++ i ) { materialIndices.push( i ); } return { dataSize: 1, buffer: materialIndexBuffer, indices: materialIndices, ...
csn_ccr
func (c *thirdPartyResources) Create(resource *extensions.ThirdPartyResource) (result *extensions.ThirdPartyResource, err error) { result = &extensions.ThirdPartyResource{} err
= c.r.Post().Namespace(c.ns).Resource("thirdpartyresources").Body(resource).Do().Into(result) return }
csn_ccr
Delete old jobs. @param checkTimeThreshold threshold for last check time @return the number of jobs deleted
public final int deleteOld(final long checkTimeThreshold) { final CriteriaBuilder builder = getSession().getCriteriaBuilder(); final CriteriaDelete<PrintJobStatusExtImpl> delete = builder.createCriteriaDelete(PrintJobStatusExtImpl.class); final Root<PrintJobStatusExtImpl> root = ...
csn
Chef published a blog post, and is now receiving many queries about it. On day $i$, he receives $Q_i$ queries. But Chef can answer at most $k$ queries in a single day. Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than $k$). The remaining questi...
# cook your dish here t=int(input()) while(t): t=t-1 n,k=list(map(int,input().split())) q=list(map(int,input().split())) days,rem=0,0 for i in range(n): rem+=q[i] if(rem>=k): rem-=k else: days=i+1 break days+=1 if(rem>=k): days+=(rem//k)+1 print(days)
apps
def run(self): """ Play loop, i.e. send all sound chunk by chunk to the soundcard. """ self.running = True def chunks_producer(): while self.running: self.chunks.put(self.next_chunks()) t = Thread(target=chunks_producer) t.start() with self....
while self.running: try: stream.write(self.chunks.get(timeout=self.timeout)) # timeout so stream.write() thread can exit except Empty: self.running = False
csn_ccr
Filter each row of A with tol. i.e., drop all entries in row k where abs(A[i,k]) < tol max( abs(A[:,k]) ) Parameters ---------- A : sparse_matrix theta : float In range [0,1) and defines drop-tolerance used to filter the row of A Returns ------- A_filter : sparse_matr...
def filter_matrix_rows(A, theta): """Filter each row of A with tol. i.e., drop all entries in row k where abs(A[i,k]) < tol max( abs(A[:,k]) ) Parameters ---------- A : sparse_matrix theta : float In range [0,1) and defines drop-tolerance used to filter the row of A Retur...
csn
// Wait blocks the server goroutine until it exits. // It sends an error message if there is any error during // the API execution.
func (s *Server) Wait(waitChan chan error) { if err := s.serveAPI(); err != nil { glog.Errorf("ServeAPI error: %v", err) waitChan <- err return } waitChan <- nil }
csn
func (c *ConfigLocal) DiskBlockCache() DiskBlockCache { c.lock.RLock()
defer c.lock.RUnlock() return c.diskBlockCache }
csn_ccr
def Times(self, val): """ Returns a new point which is pointwise multiplied by val. """
return Point(self.x * val, self.y * val, self.z * val)
csn_ccr
static ArrayTagSet create(Iterable<Tag> tags) { return (tags instanceof ArrayTagSet) ?
(ArrayTagSet) tags : EMPTY.addAll(tags); }
csn_ccr
func NewDateConverter(ctx expr.EvalIncludeContext, n expr.Node) (*DateConverter, error) { dc := &DateConverter{ Node: n, at: time.Now(), ctx: ctx, } dc.findDateMath(n) if dc.err == nil &&
len(dc.TimeStrings) > 0 { dc.HasDateMath = true } if dc.err != nil { return nil, dc.err } return dc, nil }
csn_ccr
Return a copy of source actor which is aligned to target actor through the `Iterative Closest Point` algorithm. The core of the algorithm is to match each vertex in one surface with the closest surface point on the other, then apply the transformation that modify one surface to best match the other (in...
def alignICP(source, target, iters=100, rigid=False): """ Return a copy of source actor which is aligned to target actor through the `Iterative Closest Point` algorithm. The core of the algorithm is to match each vertex in one surface with the closest surface point on the other, then apply the tran...
csn
// OptionOriginHostsPath function returns an option setter for origin hosts file path // to be passed to NewSandbox method.
func OptionOriginHostsPath(path string) SandboxOption { return func(sb *sandbox) { sb.config.originHostsPath = path } }
csn
Create a default error message. To customized this response use a ServiceMonitor.
public Response createErrorResponse(String req, Map<String,String> metaInfo, ServiceException ex) { Request request = new Request(0L); request.setContent(req); Response response = new Response(); String contentType = metaInfo.get(Listener.METAINFO_CONTENT_TYPE); if (contentType ...
csn
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 codec_dict[codec].decode(input_array, param)
csn_ccr
def validate_digit(value, start, end): '''validate if a digit is valid''' if not str(value).isdigit() or
int(value) < start or int(value) > end: raise ValueError('%s must be a digit from %s to %s' % (value, start, end))
csn_ccr
private function totalIndisWithSourcesQuery(): int { return DB::table('individuals') ->select(['i_id']) ->distinct() ->join('link', static function (JoinClause $join): void { $join->on('i_id', '=', 'l_from')
->on('i_file', '=', 'l_file'); }) ->where('l_file', '=', $this->tree->id()) ->where('l_type', '=', 'SOUR') ->count('i_id'); }
csn_ccr
=====Problem Statement===== You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. =====Example===== Www.HackerRank.com → wWW.hACKERrANK.COM Pythonist 2 → pYTHONIST 2 =====Input Format===== A single line containing a string S. =====O...
def swap_case(s): newstring = "" for item in s: if item.isupper(): newstring += item.lower() else: newstring += item.upper() return newstring
apps
Writes primitive double to the output stream @param value value to write
public void writeDouble(double value) { try { buffer.writeInt(8); buffer.writeDouble(value); } catch (Exception e) { throw new BinaryWriteFailedException(e); } }
csn
Registers a composer of a format. :param type: The unique name of the format :param composer: The method to compose data as the format
def register_composer(self, type, composer, **meta): """Registers a composer of a format. :param type: The unique name of the format :param composer: The method to compose data as the format """ try: self.registered_formats[type]['composer'] = composer except...
csn
Import all the given modules
def import_metadata(module_paths): """Import all the given modules""" cwd = os.getcwd() if cwd not in sys.path: sys.path.insert(0, cwd) modules = [] try: for path in module_paths: modules.append(import_module(path)) except ImportError as e: err = RuntimeError(...
csn
Merge the current configuration with the defaults and copy replaced values to the new options.
public function merge_config() { $current = $this->config; $this->config = array(); foreach ($this->replaced_config as $prop => $replacement) { if (isset($current[$prop])) { if ($prop == 'skin_path') { $this->config[$replacement] = preg_r...
csn