query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
// setConnLimit sets the maximum number of free client slots and also drops
// some peers if necessary | func (f *freeClientPool) setLimits(count int, totalCap uint64) {
f.lock.Lock()
defer f.lock.Unlock()
f.connectedLimit = int(totalCap / f.freeClientCap)
if count < f.connectedLimit {
f.connectedLimit = count
}
now := mclock.Now()
for f.connPool.Size() > f.connectedLimit {
i := f.connPool.PopItem().(*freeClie... | csn |
Filter the query on the begin column
Example usage:
<code>
$query->filterByBegin('2011-03-14'); // WHERE begin = '2011-03-14'
$query->filterByBegin('now'); // WHERE begin = '2011-03-14'
$query->filterByBegin(array('max' => 'yesterday')); // WHERE begin > '2011-03-13'
</code>
@param mixed $begin The value to use a... | public function filterByBegin($begin = null, $comparison = null)
{
if (is_array($begin)) {
$useMinMax = false;
if (isset($begin['min'])) {
$this->addUsingAlias(DealerShedulesTableMap::BEGIN, $begin['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
... | csn |
def elementwise(name="", pos=None):
"""
Function auto-map decorator broadcaster.
Creates an "elementwise" decorator for one input parameter. To create such,
it should know the name (for use as a keyword argument and the position
"pos" (input as a positional argument). Without a name, only the
positional ar... | if isinstance(arg, Iterable) and not isinstance(arg, STR_TYPES):
if positional:
data = (func(*(args[:pos] + (x,) + args[pos+1:]),
**kwargs)
for x in arg)
else:
data = (func(*args,
**dict(it.chain(iteritems(kwargs), [(n... | csn_ccr |
Get IPv4 network
:param id_networkv4: ID for NetworkIPv4
:return: IPv4 Network | def get_by_id(self, id_networkv4):
"""Get IPv4 network
:param id_networkv4: ID for NetworkIPv4
:return: IPv4 Network
"""
uri = 'api/networkv4/%s/' % id_networkv4
return super(ApiNetworkIPv4, self).get(uri) | csn |
def diff_toDelta(self, diffs):
"""Crush the diff into an encoded string which describes the operations
required to transform text1 into text2.
E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
Operations are tab-separated. Inserted text is escaped using %xx notation.
Args:
di... | data = data.encode("utf-8")
text.append("+" + urllib.quote(data, "!~*'();/?:@&=+$,# "))
elif op == self.DIFF_DELETE:
text.append("-%d" % len(data))
elif op == self.DIFF_EQUAL:
text.append("=%d" % len(data))
return "\t".join(text) | csn_ccr |
Replaces binding occurrences.
@param array $bindings
@return void | private function replace($bindings)
{
$search = array_keys($bindings);
$replace = array_values($bindings);
foreach ($search as $key => &$value) {
$value = $this->delimiters[0].$value.$this->delimiters[1];
}
array_walk_recursive($this->rules, function(&$value, $k... | csn |
public static function normalizeHost($host)
{
if (is_array($host)) {
return static::normalizeHostArray($host);
| }
if (is_string($host)) {
return static::normalizeHostString($host);
}
return [ $host ];
} | csn_ccr |
## Task
Given a positive integer `n`, calculate the following sum:
```
n + n/2 + n/4 + n/8 + ...
```
All elements of the sum are the results of integer division.
## Example
```
25 => 25 + 12 + 6 + 3 + 1 = 47
``` | def halving_sum(n):
s=0
while n:
s+=n ; n>>=1
return s | apps |
def _restore_group(self, group_id):
"""Get group metadata for a group by id."""
meta | = self.TaskSetModel._default_manager.restore_taskset(group_id)
if meta:
return meta.to_dict() | csn_ccr |
// HandleDeviceCloneNotification is called when a run of the device clone status update
// finds a newly-added, possible clone. It will broadcast the messages to all curious listeners. | func (n *NotifyRouter) HandleDeviceCloneNotification(newClones int) {
if n == nil {
return
}
n.G().Log.Debug("+ Sending device clone notification")
// For all connections we currently have open...
n.cm.ApplyAll(func(id ConnectionID, xp rpc.Transporter) bool {
// If the connection wants the `Deviceclone` notif... | csn |
If view data for this course-module is not yet available, obtains it.
This function is automatically called if any of the functions (marked) which require
view data are called.
View data is data which is needed only for displaying the course main page (& any similar
functionality on other pages) but is not needed in ... | private function obtain_view_data() {
if ($this->state >= self::STATE_BUILDING_VIEW || $this->modinfo->get_user_id() == -1) {
return;
}
$this->obtain_dynamic_data();
$this->state = self::STATE_BUILDING_VIEW;
// Let module make changes at this point
$this->cal... | csn |
Generate genereic controllers | function generateGenericControllers(controllers, models) {
var genericControllers = {},
genericRoute = [];
models.forEach(function(model) {
var persistence = $database.getPersistenceOfModel(model);
if (null == persistence) {
throw new Error('');
... | csn |
def add_new_resource(self):
"""Handle add new resource requests.
"""
parameters_widget = [
self.parameters_scrollarea.layout().itemAt(i) for i in
range(self.parameters_scrollarea.layout().count())][0].widget()
parameter_widgets = [
parameters_widget.ve... | 'unit': '{{ Unit }}',
'units': '{{ Units }}',
'unit abbreviation': '{{ Unit abbreviation }}',
'resource name': '{{ Resource name }}',
'minimum allowed': '{{ Minimum allowed }}',
'maximum allowed': '{{ Maximum allowed }}',
... | csn_ccr |
public function next_sibling()
{
if ($this->parent === null) {
return null;
}
$idx = 0;
$count = count($this->parent->children);
while ($idx < $count && $this !== $this->parent->children[$idx]) {
++$idx;
| }
if (++$idx >= $count) {
return null;
}
return $this->parent->children[$idx];
} | csn_ccr |
public static function exportList($xml)
{
$app = Application::getFacadeApplication();
$db = $app->make(Connection::class);
$bxml = $xml->addChild('blocktypesets');
$rs = $db->executeQuery('select btsID from BlockTypeSets order by btsID asc'); |
while (($btsID = $rs->fetchColumn()) !== false) {
$bts = static::getByID($btsID);
$bts->export($bxml);
}
} | csn_ccr |
Get all child records for given parent entities.
@param string $table The database table
@param array $ids The parent entity ids
@param int $maxLevels The max stop level
@param string Custom index key (default: primary key from model)
@param array $children Internal children return array
@param int $le... | public function getChildRecords(string $table, array $ids = [], $maxLevels = null, string $key = 'id', array $children = [], int $level = 0): array
{
if (null === ($tree = $this->getTreeCache($table, $key))) {
return $this->database->getChildRecords($ids, $table);
}
foreach ($id... | csn |
Retrieve data from one of the nearest stations. This method retrieves all stations in a specific diameter around
the location. It then queries the stations one by one until one station's results could be found.
This is important if a station's files are missing on the ftp.
@param array $nearestStations
@param DateTime... | public function getDataInInterval($coordinatesRequest, DateTime $date, $timeMinuteLimit = 30, $sorted = true)
{
$parameters = [];
$queriedStations = [];
$date = Carbon::instance($date)->setTimezone('utc');
foreach ($this->services as $var => $hourlyService) {
$stations ... | csn |
Tests if the object is defined as an attribute in the namespace
@return [Boolean] whether the object is an attribute | def is_attribute?
info = attr_info
if info
read_or_write = name.to_s =~ /=$/ ? :write : :read
info[read_or_write] ? true : false
else
false
end
end | csn |
Return a set of unset inputs | def get_unset_inputs(self):
""" Return a set of unset inputs """
return set([k for k, v in self._inputs.items() if v.is_empty(False)]) | csn |
def keep_params_s(s, params):
"""
Keep the given parameters from a string
Same as :meth:`keep_params` but does not use the :attr:`params`
dictionary
Parameters
----------
s: str
The string of the parameters like section
params: list of str
... | modified string `s` with only the descriptions of `params`
"""
patt = '(?s)' + '|'.join(
'(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params)
return ''.join(re.findall(patt, '\n' + s.strip() + '\n')).rstrip() | csn_ccr |
def isPointInside(self, xp, yp):
"""Is the given point inside the polygon?
Input:
------------
xp, yp
(floats) Coordinates of point in same units that
array vertices are specified when object created.
Returns:
-----------
**True** / **Fals... |
#Get the vector from each vertex to the given point
pointVec = point - polygon
crossProduct = np.cross(polyVec, pointVec)
if np.all(crossProduct < 0) or np.all(crossProduct > 0):
return True
return False | csn_ccr |
Decode a segwit address. | def decode(addr):
"""Decode a segwit address."""
hrpgot, data = bech32_decode(addr)
# if hrpgot != hrp:
if hrpgot not in BECH32_VERSION_SET:
return (None, None)
decoded = convertbits(data[1:], 5, 8, False)
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None,... | csn |
Get the padding required for a zone.
@param Zone $zone
@return array Array order: name, ttl, type, rdata | private static function getPadding(Zone $zone)
{
$name = $ttl = $type = 0;
foreach ($zone as $resourceRecord) {
$name = max($name, strlen($resourceRecord->getName()));
$ttl = max($ttl, strlen($resourceRecord->getTtl()));
$type = max($type, strlen($resourceRecord-... | csn |
The value of the Literal is the sequence of characters inside
the " or ' characters>.
Literal ::= '"' [^"]* '"'
| "'" [^']* "'"
@throws javax.xml.transform.TransformerException | protected void Literal() throws javax.xml.transform.TransformerException
{
int last = m_token.length() - 1;
char c0 = m_tokenChar;
char cX = m_token.charAt(last);
if (((c0 == '\"') && (cX == '\"')) || ((c0 == '\'') && (cX == '\'')))
{
// Mutate the token to remove the quotes and have the ... | csn |
This method creates a Solr-formatted XML document | def create_document( obj )
solr_doc = Hash.new
model_klazz_array = ActiveFedora::ContentModel.known_models_for( obj )
model_klazz_array.delete(ActiveFedora::Base)
# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from Activ... | csn |
def define_fact(name, &block)
add Sche | ma::Builders::FactBuilder.new(self).build(name, &block)
end | csn_ccr |
// convert time from db. | func (d *dbBase) TimeFromDB(t *time.Time, tz *time.Location) {
*t = t.In(tz)
} | csn |
def parse_code(self, url, html):
"""
Parse the code details and TOC from the given HTML content
:type url: str
:param url: source URL of the page
:type html: unicode
:param html: Content of the HTML
:return: the code
"""
soup = BeautifulSoup(h... | url_code=cleanup_url(url))
# -- Code title/subtitle
div_title = div.find('div', id='titreTexte')
span_subtitle = div_title.find('span',
attrs={'class': 'sousTitreTexte'})
if span_subtitle:
code.title = div_title.text.replac... | csn_ccr |
// Pipeline to use while processing the request. | func (r *BulkIndexRequest) Pipeline(pipeline string) *BulkIndexRequest {
r.pipeline = pipeline
r.source = nil
return r
} | csn |
Table list toggle event handler | def OnTableListToggle(self, event):
"""Table list toggle event handler"""
table_list_panel_info = \
self.main_window._mgr.GetPane("table_list_panel")
self._toggle_pane(table_list_panel_info)
event.Skip() | csn |
function getNextPhase(currentPhase) {
var nextPhase = currentPhase;
// Ensure we have valid swipe (under time and over distance and check if we are out of bound...)
var validTime = validateSwipeTime();
var validDistance = validateSwipeDistance();
var didCancel = didSwipeBackToCancel();
... | else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) ) {
nextPhase = PHASE_END;
}
//Else if we have ended by leaving and didn't reach distance, then cancel
else if (!validDistance && currentPhase==PHASE_END && options.triggerOnTouchLeave) {... | csn_ccr |
Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClosed``, then returns
``None``. Otherwise, returns a :term:... | def send(self, event):
"""Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClosed``, then returns
``N... | csn |
func NewConsumerConf(topic string, partition int32) ConsumerConf {
return ConsumerConf{
Topic: topic,
Partition: partition,
RequestTimeout: time.Millisecond * 50, |
RetryLimit: -1,
RetryWait: time.Millisecond * 50,
RetryErrLimit: 10,
RetryErrWait: time.Millisecond * 500,
MinFetchSize: 1,
MaxFetchSize: 2000000,
StartOffset: StartOffsetOldest,
Logger: nil,
}
} | csn_ccr |
Pick out the fragment or query part from a URL.
:param info: A URL possibly containing a query or a fragment part
:return: the query/fragment part | def get_urlinfo(info):
"""
Pick out the fragment or query part from a URL.
:param info: A URL possibly containing a query or a fragment part
:return: the query/fragment part
"""
# If info is a whole URL pick out the query or fragment part
if '?' in info or '#' in... | csn |
Returns the percentage, current and total number of
jobs in the queue. | def progress(self):
""" Returns the percentage, current and total number of
jobs in the queue.
"""
total = len(self.all_jobs)
remaining = total - len(self.active_jobs) if total > 0 else 0
percent = int(100 * (float(remaining) / total)) if total > 0 else 0
return p... | csn |
Identify if the given session ID is currently valid.
Return True if valid, False if explicitly invalid, None if unknown. | def is_valid(self, context, sid):
"""Identify if the given session ID is currently valid.
Return True if valid, False if explicitly invalid, None if unknown.
"""
record = self._Document.find_one(sid, project=('expires', ))
if not record:
return
return not record._expired | csn |
Returns the Custom Hook model if defined in settings,
otherwise the default Hook model. | def get_hook_model():
"""
Returns the Custom Hook model if defined in settings,
otherwise the default Hook model.
"""
from rest_hooks.models import Hook
HookModel = Hook
if getattr(settings, 'HOOK_CUSTOM_MODEL', None):
HookModel = get_module(settings.HOOK_CUSTOM_MODEL)
return Hoo... | csn |
def compare_hives(fs0, fs1):
"""Compares all the windows registry hive files
returning those which differ.
"""
registries = []
for path in chain(registries_path(fs0.fsroot), user_registries(fs0, fs1)):
| if fs0.checksum(path) != fs1.checksum(path):
registries.append(path)
return registries | csn_ccr |
private function assertValidAttribute($attribute)
{
if ( ! isset($this->documentChangeSet[$attribute])) {
throw new \InvalidArgumentException(sprintf(
'Attribute "%s" | is not a valid attribute of the document "%s" in PreUpdateEventArgs.',
$attribute,
get_class($this->getDocument())
));
}
} | csn_ccr |
Recalculate angles using equation of dipole circular motion
@param timeNew timestamp of method invoke
@return if there is a need to redraw rotation | protected boolean angleRecalculate(final long timeNew) {
// recalculate angle using simple numerical integration of motion equation
float deltaT1 = (timeNew - time1) / 1000f;
if (deltaT1 > TIME_DELTA_THRESHOLD) {
deltaT1 = TIME_DELTA_THRESHOLD;
time1 = timeNew + Math.rou... | csn |
def setUser(request):
"""In standalone mode, change the current user"""
if not settings.PIAPI_STANDALONE or | settings.PIAPI_REALUSERS:
raise Http404
request.session['plugit-standalone-usermode'] = request.GET.get('mode')
return HttpResponse('') | csn_ccr |
python if type array | def is_iterable(value):
"""must be an iterable (list, array, tuple)"""
return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value | cosqa |
public function prepareUrlForNoSession($sUrl)
{
/** @var \OxidEsales\Eshop\Core\StrRegular $oStr */
$oStr = getStr();
// cleaning up session id..
$sUrl = $oStr->preg_replace('/(\?|&(amp;)?)(force_)?(admin_)?sid=[a-z0-9\._]+&?(amp;)?/i', '\1', $sUrl);
$sUrl = $oStr->preg_repl... | $sUrl .= "{$sSep}lang=" . \OxidEsales\Eshop\Core\Registry::getLang()->getBaseLanguage();
$sSep = '&';
}
$oConfig = \OxidEsales\Eshop\Core\Registry::getConfig();
if (!$oStr->preg_match('/[&?](amp;)?cur=[0-9]+/i', $sUrl)) {
$iCur = (int) $oConfig->getShopCurrency();
... | csn_ccr |
Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dictionary containing a list of q-tile tupples for each q-plane
fse... | def qplane(qplane_tile_dict, fseries, return_complex=False):
"""Performs q-transform on each tile for each q-plane and selects
tile with the maximum energy. Q-transform can then
be interpolated to a desired frequency and time resolution.
Parameters
----------
qplane_tile_dict:
Dic... | csn |
Upload Supervisor app configuration from a template. | def upload_supervisor_app_conf(app_name, template_name=None, context=None):
"""Upload Supervisor app configuration from a template."""
default = {'app_name': app_name}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % app_name, u'supervisor/ba... | csn |
Converts each cells in tbe notebook to a PDF named something like
'q04c.pdf'. Places PDFs in the specified folder and returns the list of
created PDF locations. | def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list:
"""
Converts each cells in tbe notebook to a PDF named something like
'q04c.pdf'. Places PDFs in the specified folder and returns the list of
created PDF locations.
"""
html_cells = nb_to_html_cells(nb)
q_nums = nb_to_q_nums(nb... | csn |
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup. | def set_mime_type(self, mime_type):
"""
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup.
"""
try:
self.set_lexer_from_mime_type(mime_type)
except ClassNotFound:
_logger().exception('failed t... | csn |
Returns arginfo name for current method.
@param ClassDefinition|null $classDefinition
@return string | public function getArgInfoName(ClassDefinition $classDefinition = null)
{
if (null != $classDefinition) {
return sprintf(
'arginfo_%s_%s_%s',
strtolower($classDefinition->getCNamespace()),
strtolower($classDefinition->getName()),
st... | csn |
protected function computeYesTransitions() {
$this->yesTransitions = [ [] ];
$this->outputs = [ [] ];
foreach ( $this->searchKeywords as $keyword => $length ) {
$state = 0;
for ( $i = 0; $i < $length; $i++ ) {
$ch = $keyword[$i];
| if ( !empty( $this->yesTransitions[$state][$ch] ) ) {
$state = $this->yesTransitions[$state][$ch];
} else {
$this->yesTransitions[$state][$ch] = $this->numStates;
$this->yesTransitions[] = [];
$this->outputs[] = [];
$state = $this->numStates++;
}
}
$this->outputs[$state][] = $... | csn_ccr |
AMF3 Decode XMLDoc
@param buf
@returns {{len: *, value: (*|String)}} | function amf3decXmlDoc(buf) {
var sLen = amf3decUI29(buf);
var s = sLen & 1;
sLen = sLen >> 1; // The real length without the lowest bit
if (s) return { len: sLen.value + 5, value: buf.slice(5, sLen.value + 5).toString('utf8') };
throw new Error("Error, we have a need to decode a String that is a Re... | csn |
func (v *Adjustment) Configure(value, lower, upper, step_increment, page_increment, page_size float64) {
panic_if_version_older(2, 14, 0, "gtk_adjustment_configure()")
C._gtk_adjustment_configure(v.GAdjustment, | gdouble(value), gdouble(lower), gdouble(upper),
gdouble(step_increment), gdouble(page_increment), gdouble(page_size))
} | csn_ccr |
Cut the line in columns and replies the given column.
@param delimiter is the delmiter to use to cut.
@param column is the number of the column to reply.
@param lineText is the line to cut.
@return the column or {@code null}. | protected static String cut(String delimiter, int column, String lineText) {
if (lineText == null || lineText.isEmpty()) {
return null;
}
final String[] columns = lineText.split(Pattern.quote(delimiter));
if (columns != null && column >= 0 && column < columns.length) {
return columns[column].trim();
}
... | csn |
public function setCip($cip)
{
$this->cip = $cip;
$this->variaveis_adicionais['cip'] | = $this->getCip();
return $this;
} | csn_ccr |
Handle delete_user_commit hook | function user_delete($p)
{
$this->load_engine();
$p['abort'] = $p['abort'] || !$this->engine->delete_user_data($p['username']);
return $p;
} | csn |
protected void handleError(String errMsg) throws Exception {
// log it
LOGGER.log(Level.SEVERE, errMsg);
// and throw an error if this is configured
| if (this.isThrowExceptionOnError()) {
throw new Exception(errMsg);
}
} | csn_ccr |
python see if a file exists | def _file_exists(path, filename):
"""Checks if the filename exists under the path."""
return os.path.isfile(os.path.join(path, filename)) | cosqa |
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
... | def run(toolkit_name, options, verbose=True, show_progress=False):
"""
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function... | csn |
Precomputes a lookup table from linux pids back to existing
Threads. This is used during importing to add information to each
thread about whether it was running, descheduled, sleeping, et
cetera. | function() {
this.threadsByLinuxPid = {};
this.model_.getAllThreads().forEach(
function(thread) {
this.threadsByLinuxPid[thread.tid] = thread;
}.bind(this));
} | csn |
Create a Metrics instance from a bigquery query or table.
Returns:
a Metrics instance.
Args:
sql: A BigQuery table name or a query. | def from_bigquery(sql):
"""Create a Metrics instance from a bigquery query or table.
Returns:
a Metrics instance.
Args:
sql: A BigQuery table name or a query.
"""
if isinstance(sql, bq.Query):
sql = sql._expanded_sql()
parts = sql.split('.')
if len(parts) == 1 or len(pa... | csn |
Wrap a computation in a lazy computation.
@param supplier the computation
@param <A> the value type
@return the new {@link Lazy} | public static <A> Lazy<A> lazy(Supplier<A> supplier) {
return new Later<>(fn0(supplier));
} | csn |
Returns Array of domain names for the MX'ers, used to determine the Provider | def domains
@_domains ||= mxers.map {|m| EmailAddress::Host.new(m.first).domain_name }.sort.uniq
end | csn |
public static function table()
{
$class = get_called_class();
// Table name unknown
if ( ! array_key_exists($class, static::$_table_names_cached))
{
// Table name set in Model
if (property_exists($class, '_table_name'))
{
static::$_table_names_cached[$class] = static::$_table_name; |
}
else
{
static::$_table_names_cached[$class] = \Inflector::tableize($class);
}
}
return static::$_table_names_cached[$class];
} | csn_ccr |
Load the configuration from cache.
@return \Core\Services\Contracts\Config | private function loadConfigFromCache()
{
/** @var \Core\Services\Contracts\Config $config */
$config = DI::getInstance()->get('config');
/** @noinspection PhpIncludeInspection */
$config->set(null, require $this->cachedFile);
return $config;
} | csn |
A context manager that changes the working directory to the given
path, and then changes it back to its previous value on exit. | def working_directory(path):
"""
A context manager that changes the working directory to the given
path, and then changes it back to its previous value on exit.
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd) | csn |
def reset(self):
"""Reset the database
Drop all tables and recreate them
"""
| self.metadata.drop_all(self.engine)
self.metadata.create_all(self.engine) | csn_ccr |
// UploadDeps uploads all of the items in parts. | func (ut *UploadTracker) UploadDeps(parts partitionedDeps) error {
if err := ut.populateSymlinks(parts.links.items); err != nil {
return err
}
if err := ut.tarAndUploadFiles(parts.filesToArchive.items); err != nil {
return err
}
if err := ut.uploadFiles(parts.indivFiles.items); err != nil {
return err
}
... | csn |
public function pause(DeliveryExecution $deliveryExecution, $reason = null)
{
$executionState = $deliveryExecution->getState()->getUri();
$result = false;
if (ProctoredDeliveryExecution::STATE_TERMINATED !== $executionState && ProctoredDeliveryExecution::STATE_FINISHED !== $executionState) ... | if ($session->getState() !== AssessmentTestSessionState::SUSPENDED) {
$session->suspend();
$this->getTestSessionService()->persist($session);
}
$this->getServiceLocator()->get(ExtendedStateService::SERVICE_ID)->persist($session->getSe... | csn_ccr |
r"""
Check that the string is UTF-8. Returns an encode bytestring.
>>> utf8(b'\xe0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Not UTF-8: ... | def utf8(value):
r"""
Check that the string is UTF-8. Returns an encode bytestring.
>>> utf8(b'\xe0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Not UTF-8: ...
"""
try:
if isinstance(value, bytes):
return value.decode('utf-8')
el... | csn |
def file_checksum(fname):
"""Return md5 checksum of file.
Note: only works for files < 4GB.
Parameters
----------
filename : str
File used to calculate checksum.
Returns
-------
checkum : str
"""
size | = os.path.getsize(fname)
with open(fname, "r+") as f:
checksum = hashlib.md5(mmap.mmap(f.fileno(), size)).hexdigest()
return checksum | csn_ccr |
// NewClient creates a new client for accessing the undertaker API. | func NewClient(caller base.APICaller, newWatcher NewWatcherFunc) (*Client, error) {
modelTag, ok := caller.ModelTag()
if !ok {
return nil, errors.New("undertaker client is not appropriate for controller-only API")
}
return &Client{
modelTag: modelTag,
caller: base.NewFacadeCaller(caller, "Undertaker"),
... | csn |
// GetMetaDescription returns the meta description set in the source, if the article has one | func (extr *ContentExtractor) GetMetaDescription(document *goquery.Document) string {
return extr.GetMetaContent(document, "description")
} | csn |
how to add vectors in python with ctypes structure | def vadd(v1, v2):
""" Add two 3 dimensional vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html
:param v1: First vector to be added.
:type v1: 3-Element Array of floats
:param v2: Second vector to be added.
:type v2: 3-Element Array of floats
:return: v1+v2
:r... | cosqa |
public static function getByHandle($atHandle)
{
$db = Loader::db();
$row = $db->GetRow('SELECT * FROM AuthenticationTypes WHERE authTypeHandle=?', [$atHandle]);
if (!$row) {
| throw new Exception(t('Invalid Authentication Type Handle'));
}
$at = self::load($row);
return $at;
} | csn_ccr |
Adds the publish to hour field | private function AddPublishToHourField()
{
$name = 'PublishToHour';
$to = $this->page->GetPublishTo();
$field = Input::Text($name, $to ? $to->ToString('H') : '');
$field->SetHtmlAttribute('data-type', 'hour');
$this->AddField($field);
} | csn |
func (c *Cursor) Profile() interface{} {
if c == nil {
return nil
}
| c.mu.RLock()
defer c.mu.RUnlock()
return c.profile
} | csn_ccr |
func (p *DeployedCCInfoProvider) ChaincodeInfo(chaincodeName string, qe ledger.SimpleQueryExecutor) (*ledger.DeployedChaincodeInfo, error) {
chaincodeDataBytes, err := qe.GetState(lsccNamespace, chaincodeName)
if err != nil || chaincodeDataBytes == nil {
return nil, err
}
chaincodeData := &ccprovider.ChaincodeDat... | err := proto.Unmarshal(chaincodeDataBytes, chaincodeData); err != nil {
return nil, errors.Wrap(err, "error unmarshalling chaincode state data")
}
collConfigPkg, err := fetchCollConfigPkg(chaincodeName, qe)
if err != nil {
return nil, err
}
return &ledger.DeployedChaincodeInfo{
Name: chaincod... | csn_ccr |
Decorator to create memoized properties. | def memoized_property(fget):
"""Decorator to create memoized properties."""
attr_name = '_{}'.format(fget.__name__)
@functools.wraps(fget)
def fget_memoized(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fget(self))
return getattr(self, attr_name)
retur... | csn |
def del_design(self, design_name):
"""
Removes the specified design
design_name <str>
"""
try:
design = self.get_design(design_name)
r = requests.request(
"DELETE",
"%s/%s/_design/%s" % (
self.host,
| self.database_name,
design_name
),
params={"rev" : design.get("_rev")},
auth=self.auth
)
return self.result(r.text)
except:
raise | csn_ccr |
how to define percentage in python | def ratio_and_percentage(current, total, time_remaining):
"""Returns the progress ratio and percentage."""
return "{} / {} ({}% completed)".format(current, total, int(current / total * 100)) | cosqa |
Checks if a service is UP
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_up 'serviceName' | def service_up(s_name, **connection_args):
'''
Checks if a service is UP
CLI Example:
.. code-block:: bash
salt '*' netscaler.service_up 'serviceName'
'''
service = _service_get(s_name, **connection_args)
return service is not None and service.get_svrstate() == 'UP' | csn |
func NextUntil(it Iterator, fn FnKeyCmp) error {
var err error
for it.Valid() && !fn(it.Key()) {
err = it.Next() |
if err != nil {
return err
}
}
return nil
} | csn_ccr |
Return the name of the CloudShell model | def cloudshell_model_name(self):
"""Return the name of the CloudShell model"""
if self.shell_name:
return "{shell_name}.{resource_model}".format(shell_name=self.shell_name,
resource_model=self.RESOURCE_MODEL.replace(" ", ""))
... | csn |
Short description of method buildDeleterBehaviour
@access public
@author Jerome Bogaerts, <jerome@taotesting.com>
@return string | public function buildDeleterBehaviour()
{
return '$(document).ready(function() {
$("#' . $this->buildDeleteButtonId() . '").click(function() {
var $form = $(this).parents("form"),
$fileHandling = $form.find("[name=\'' . $this->getName()... | csn |
// send on tickChan to start a new timer.
// timers are interupted and replaced by new ticks from later steps
// timeouts of 0 on the tickChan will be immediately relayed to the tockChan | func (t *timeoutTicker) timeoutRoutine() {
t.Logger.Debug("Starting timeout routine")
var ti timeoutInfo
for {
select {
case newti := <-t.tickChan:
t.Logger.Debug("Received tick", "old_ti", ti, "new_ti", newti)
// ignore tickers for old height/round/step
if newti.Height < ti.Height {
continue
} ... | csn |
def debugDumpAttr(self, output, depth):
"""Dumps debug information for the attribute """
| libxml2mod.xmlDebugDumpAttr(output, self._o, depth) | csn_ccr |
func logFail(op Op, msg string) {
log.Printf(msg)
if err := reportStatus(status.StatusError, op, msg); err != nil {
log.Printf("Error reporting extension status: %v", err)
}
if err := seqnumfile.Delete(); err != nil {
log.Printf("WARNING: Error | deleting seqnumfile: %v", err)
}
log.Println("Cleaned up .seqnum file.")
log.Println("Exiting with code 1.")
os.Exit(1)
} | csn_ccr |
Adds a submodule to the module.
<P>
INFO: If the module is promoted, all added submodule will be promoted.
@param submodule Module | public void addSubmodule(final Module submodule) {
if (!submodules.contains(submodule)) {
submodule.setSubmodule(true);
if (promoted) {
submodule.setPromoted(promoted);
}
submodules.add(submodule);
}
} | csn |
public function containsClassAnnotation($annotationName)
{
foreach ($this->getClassAnnotations() as $annotation) {
if ($annotation instanceof | $annotationName) {
return true;
}
}
return false;
} | csn_ccr |
func (lru *LRUCache) Items() []Item {
lru.mu.Lock()
defer lru.mu.Unlock()
items := make([]Item, 0, lru.list.Len())
| for e := lru.list.Front(); e != nil; e = e.Next() {
v := e.Value.(*entry)
items = append(items, Item{Key: v.key, Value: v.value})
}
return items
} | csn_ccr |
Makes filename text | def _make_fn_text(self):
"""Makes filename text"""
if not self._f:
text = "(not loaded)"
elif self._f.filename:
text = os.path.relpath(self._f.filename, ".")
else:
text = "(filename not set)"
return text | csn |
Return string at current position + length.
If trim == true then get as much as possible before eos. | def get_length(self, length, trim=0, offset=0):
"""Return string at current position + length.
If trim == true then get as much as possible before eos.
"""
if trim and not self.has_space(offset + length):
return self.string[self.pos + offset:]
elif self.has_space(offs... | csn |
function renderTemplate(contents, data, filename) {
if (!templateCache.hasOwnProperty(contents)) {
var jadeOptions = merge.recursive({}, options.jadeOptions, {filename: filename});
templateCache[contents] | = options.jade.compile(contents, jadeOptions);
}
var locals = merge.recursive({}, data, {locals: locals});
return templateCache[contents](data);
} | csn_ccr |
Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.
As the answer can be very large, return it modulo 109 + 7.
Example 1:
Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (A[i], A[j],... | class Solution:
def threeSumMulti(self, A: List[int], target: int) -> int:
counter = collections.Counter(A)
i, res, l, ckey = 0, 0, len(counter), sorted(list(counter.keys()))
if target % 3 == 0:
res += math.comb(counter[target // 3], 3)
for i in range(l):
ni =... | apps |
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1 | def wrap(s, width=80):
"""
Formats the text input with newlines given the user specified width for
each line.
Parameters
----------
s : str
width : int
Returns
-------
text : str
Notes
-----
.. versionadded:: 1.1
"""
return '\n'.join(textwrap.wrap(str(s... | csn |
public function hex2bin($hexString)
{
$pos = 0;
$result = '';
while ($pos < strlen($hexString)) {
if (strpos(" \t\n\r", $hexString[$pos]) !== false) {
++$pos;
} else {
| $code = hexdec(substr($hexString, $pos, 2));
$pos += 2;
$result .= chr($code);
}
}
return $result;
} | csn_ccr |
Compute noise components from the input image
ANTsR function: `compcor`
this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confounds.py
Arguments
---------
boldImage: input time series image
ncompcor: number of nois... | def compcor( boldImage, ncompcor=4, quantile=0.975, mask=None, filter_type=False, degree=2 ):
"""
Compute noise components from the input image
ANTsR function: `compcor`
this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confou... | csn |
Overridable custom event handler to unhighlight row. Accounts for spurious
caused-by-child events.
@method onEventUnhighlightRow
@param oArgs.event {HTMLEvent} Event object.
@param oArgs.target {HTMLElement} Target element. | function(oArgs) {
//TODO: filter for all spurious events at a lower level
if(!Dom.isAncestor(oArgs.target,Ev.getRelatedTarget(oArgs.event))) {
this.unhighlightRow(oArgs.target);
}
} | csn |
Show tags after discussion body. | public function DiscussionController_AfterDiscussionBody_Handler($Sender) {
// Allow disabling of inline tags.
if (C('Plugins.Tagging.DisableInline', FALSE))
return;
if (!property_exists($Sender->EventArguments['Object'], 'CommentID')) {
$DiscussionID = property_exists($Sender... | csn |
function isPortInUse(port) {
_validatePortFormat(port);
if (isPlatform('unix')) {
if (isPlatform('linux') && fileExists('/proc/net')) {
return _isPortInUseRaw(port);
| } else if (isInPath('netstat')) {
return _isPortInUseNetstat(port);
} else {
throw new Error('Cannot check port status');
}
} else {
throw new Error('Port checking not supported on this platform');
}
} | csn_ccr |
private void writeStringToFile(String str, File file) throws IOException {
if (!file.exists() && file.isDirectory()) {
return;
}
try (BufferedWriter bw = | new BufferedWriter(WriterFactory.newWriter(file, this.encoding))) {
bw.write(str);
}
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.