Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
339,500 | def requires_auth(func):
@six.wraps(func)
def wrapper(self, *args, **kwargs):
if self.token_expired:
self.authenticate()
return func(self, *args, **kwargs)
return wrapper | Handle authentication checks.
.. py:decorator:: requires_auth
Checks if the token has expired and performs authentication if needed. |
339,501 | def reportFailed(self, *args, **kwargs):
return self._makeApiCall(self.funcinfo["reportFailed"], *args, **kwargs) | Report Run Failed
Report a run failed, resolving the run as `failed`. Use this to resolve
a run that failed because the task specific code behaved unexpectedly.
For example the task exited non-zero, or didn't produce expected output.
Do not use this if the task couldn't be run because ... |
339,502 | def _set_logger(logger_name, level=logging.INFO):
log = logging.getLogger(logger_name)
log.setLevel(level)
ch = logging.StreamHandler(None)
ch.setLevel(level)
formatter = logging.Formatter(DebugFmtString)
ch.setFormatter(formatter)
l... | Convenience function to quickly configure full debug output
to go to the console. |
339,503 | def to_seq(o) -> Optional[ISeq]:
if o is None:
return None
if isinstance(o, ISeq):
return _seq_or_nil(o)
if isinstance(o, ISeqable):
return _seq_or_nil(o.seq())
return _seq_or_nil(lseq.sequence(o)) | Coerce the argument o to a ISeq. If o is None, return None. |
339,504 | def _create_column(values, dtype):
"Creates a column from values with dtype"
if str(dtype) == "tensor(int64)":
return numpy.array(values, dtype=numpy.int64)
elif str(dtype) == "tensor(float)":
return numpy.array(values, dtype=numpy.float32)
else:
raise OnnxRuntimeAssertionError("... | Creates a column from values with dtype |
339,505 | def local_minima(img, min_distance = 4):
r
fits = numpy.asarray(img)
minfits = minimum_filter(fits, size=min_distance)
minima_mask = fits == minfits
good_indices = numpy.transpose(minima_mask.nonzero())
good_fits = fits[minima_mask]
order = good_fits.argsort()
return good_indices[o... | r"""
Returns all local minima from an image.
Parameters
----------
img : array_like
The image.
min_distance : integer
The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.
Returns
-------
indices : sequence
... |
339,506 | def git_tags() -> str:
try:
subprocess.check_call([, , ])
except CalledProcessError:
pass
cmd = [, , , ]
rv = subprocess.check_output(cmd).decode()
if rv == :
raise NoGitTagsException()
return rv | Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags. |
339,507 | def expand_counts(df, column, values=None):
d = counts_to_dicts(df, column)
if len(d) > 0:
if values is None:
values = set(np.concatenate(d.apply(lambda c: c.keys()).values))
for value in values:
name = values[value] if type(values) is dict else str(value)
... | expand a column containing value:count dictionaries |
339,508 | def get(self, digest, chunk_size=1024 * 128):
return self.conn.client.blob_get(self.container_name, digest,
chunk_size) | Return the contents of a blob
:param digest: the hex digest of the blob to return
:param chunk_size: the size of the chunks returned on each iteration
:return: generator returning chunks of data |
339,509 | def invertDictMapping(d):
inv_map = {}
for k, v in d.items():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
return inv_map | Invert mapping of dictionary (i.e. map values to list of keys) |
339,510 | def set(self, othernode):
self.__class__ = othernode.__class__
self.clean()
if len(othernode) > 0:
for k, v in othernode.items():
self[k] = v
for k, v in vars(othernode).items():
setattr(self, k, v) | allow to completly mutate the node into any subclasses of Node |
339,511 | def pwm_max_score(self):
if self.max_score is None:
score = 0
for row in self.pwm:
score += log(max(row) / 0.25 + 0.01)
self.max_score = score
return self.max_score | Return the maximum PWM score.
Returns
-------
score : float
Maximum PWM score. |
339,512 | def _generate_requirements(self):
if not self._pip_packages:
return
reqs =
for req in self._pip_packages:
reqs += "{}\n".format(req)
reqs_include = {
: reqs,
:,
: }
if not in self._files:
se... | Generate the info to create requirements.txt in the toookit. |
339,513 | def tx_tmpdir(data=None, base_dir=None, remove=True):
base_dir = base_dir or os.getcwd()
tmpdir_base = utils.get_abspath(_get_base_tmpdir(data, base_dir))
utils.safe_makedir(tmpdir_base)
tmp_dir = tempfile.mkdtemp(dir=tmpdir_base)
try:
yield tmp_dir
finally:
if remove:
... | Context manager to create and remove a transactional temporary directory.
Handles creating a transactional directory for running commands in. Will
use either the current directory or /tmp/bcbiotx.
Creates an intermediary location and time specific directory for global
temporary directories to prevent ... |
339,514 | def init_widget(self):
w = self.widget
w.setAdapter(self.adapter)
w.setOnItemSelectedListener(w.getId())
w.onItemSelected.connect(self.on_item_selected)
w.onNothingSelected.connect(self.on_nothing_selected)
super(AndroidSpinner, self).init_widget() | Initialize the underlying widget. |
339,515 | def obfn_reg(self):
r
l1 = np.sum(mp_wl1*np.abs(self.obfn_gvar()))
return (self.lmbda*l1, l1) | r"""Compute regularisation term, :math:`\| x \|_1`, and
contribution to objective function. |
339,516 | def read(self, timeout=20.0):
start = time()
while len(self.rcv_data) == 0:
sleep(0)
if time() - start > timeout:
raise DAPAccessIntf.De... | read data on the IN endpoint associated to the HID interface |
339,517 | def save_wif_file(self, path: str) -> None:
version = 1
seed_fi = b"\x01" + self.seed
sha256_v1 = libnacl.crypto_hash_sha256(seed_fi)
sha256_v2 = libnacl.crypto_hash_sha256(sha256_v1)
checksum = sha256_v2[0:2]
wif_key = Base... | Save a Wallet Import Format file (WIF) v1
:param path: Path to file |
339,518 | def get_methods(self, node):
methods = [
m
for m in node.values()
if isinstance(m, astroid.FunctionDef)
and not decorated_with_property(m)
and self.show_attr(m.name)
]
return sorted(methods, key=lambda n: n.name) | return visible methods |
339,519 | def interleaves(self, info):
return info.byte_offset == self.component_type.size * self.components | Does the buffer interleave with this one? |
339,520 | def construct_end_message(self):
app_count = self.dfk.task_count
site_count = len([x for x in self.dfk.config.executors if x.managed])
app_fails = len([t for t in self.dfk.tasks if
self.dfk.tasks[t][] in FINAL_FAILURE_STATES])
message = {: self.uuid,
... | Collect the final run information at the time of DFK cleanup.
Returns:
- Message dict dumped as json string, ready for UDP |
339,521 | def write_ase(atoms, db_file, stdout=sys.stdout, user=None, data=None, **key_value_pairs):
db_ase = ase.db.connect(db_file)
_normalize_key_value_pairs_inplace(key_value_pairs)
id = db_ase.write(atoms, data=data, **key_value_pairs)
stdout.write(.format(id))
unique_id = db_ase.get(id)[]
retur... | Connect to ASE db |
339,522 | def find(self, **kwargs):
matches = self.findall(**kwargs)
num_matches = len(matches)
if not num_matches:
msg = "No %s matching: %s." % (self.resource_class.__name__, kwargs)
raise exc.NotFound(404, msg)
if num_matches > 1:
msg = "More than on... | Finds a single item with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side. |
339,523 | def compiled_foreign_keys(self):
def get_column_args(column):
tmp = []
for arg_name, arg_val in column.items():
if arg_name not in (, , ):
if arg_name in (, ):
arg_val = .format(arg_val)
tmp.append(... | Returns compiled foreign key definitions |
339,524 | def get_members(self, show=True, proxy=None, timeout=0):
title = self.params.get()
pageid = self.params.get()
if not title and not pageid:
raise LookupError("needs category title or pageid")
self._get(, show, proxy, timeout)
while self.data.get():
... | GET Mediawiki:API (action=query) category members
https://www.mediawiki.org/wiki/API:Categorymembers
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
Optional arguments:
- [show]: <bool> echo page data if true
... |
339,525 | def condon_errors(source, theta_n, psf=None):
alphas = {: (3. / 2, 3. / 2),
: (5. / 2, 1. / 2),
: (5. / 2, 1. / 2),
: (1. / 2, 5. / 2),
: (1. / 2, 5. / 2),
: (1. / 2, 5. / 2)}
major = source.a / 3600.
minor = source.b / 3600... | Calculate the parameter errors for a fitted source
using the description of Condon'97
All parameters are assigned errors, assuming that all params were fit.
If some params were held fixed then these errors are overestimated.
Parameters
----------
source : :class:`AegeanTools.models.SimpleSource... |
339,526 | def ticker(rest):
"Look up a ticker symbols use Yahoosl1t1p2http://finance.yahoo.com/d/quotes.csv?s=%(ticker)s&f=%(format)soh... could not find information for symbol %s" % ticker
return % locals() | Look up a ticker symbol's current trading value |
339,527 | def attach(self, **kwargs):
return self.client.api.attach(self.id, **kwargs) | Attach to this container.
:py:meth:`logs` is a wrapper around this method, which you can
use instead if you want to fetch/stream container output without first
retrieving the entire backlog.
Args:
stdout (bool): Include stdout.
stderr (bool): Include stderr.
... |
339,528 | def encodeValue(self, value, toBeAdded=True):
encodedValue = np.array(self.encoder.encode(value), dtype=realDType)
if toBeAdded:
self.encodings.append(encodedValue)
self.numEncodings+=1
return encodedValue | Value is encoded as a sdr using the encoding parameters of the Field |
339,529 | def create_extracted_license(self, lic):
licenses = list(self.graph.triples((None, self.spdx_namespace.licenseId, lic.identifier)))
if len(licenses) != 0:
return licenses[0][0]
else:
license_node = BNode()
type_triple = (license_node, RDF.type, self... | Handle extracted license.
Return the license node. |
339,530 | def partition_block(block):
result = [block]
if not block.is_partitionable:
return result
EDP = END_PROGRAM_LABEL +
for i in range(len(block) - 1):
if i and block.asm[i] == EDP:
block, new_block = block_partition(block, i - 1)
LABELS[END_PROGRAM_LABEL].... | If a block is not partitionable, returns a list with the same block.
Otherwise, returns a list with the resulting blocks, recursively. |
339,531 | def _ParseRecordLogline(self, parser_mediator, structure):
date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()
try:
datetime_iso8601 = self._GetISO8601String(structure.date_time)
date_time.CopyFromStringISO8601(datetime_iso8601)
except ValueError:
parser_mediator.Produc... | Parses a logline record structure and produces events.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file. |
339,532 | def add_snmp_community(self, **kwargs):
community = kwargs.pop()
callback = kwargs.pop(, self._callback)
config = ET.Element()
snmp_server = ET.SubElement(config, ,
xmlns=("urn:brocade.com:mgmt:"
"br... | Add SNMP Community to NOS device.
Args:
community (str): Community string to be added to device.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
... |
339,533 | def _get_ontology(ontology):
onto_name = onto_path = onto_url = None
if os.path.exists(ontology):
onto_name = os.path.split(os.path.abspath(ontology))[1]
onto_path = os.path.abspath(ontology)
onto_url = ""
else:
discovered_file = _discover_ontology(ontolog... | Return the (name, path, url) to the short ontology name.
:param ontology: path to the file or url. |
339,534 | def _module_info_to_proto(module_info, export_scope=None):
def strip_name_scope(name_scope):
return ops.strip_name_scope(name_scope, export_scope)
def process_leafs(value):
return strip_name_scope(_graph_element_to_path(value))
module_info_def = module_pb2.SonnetModule(
module_name=module_info.mo... | Serializes `module_into`.
Args:
module_info: An instance of `ModuleInfo`.
export_scope: Optional `string`. Name scope to remove.
Returns:
An instance of `module_pb2.SonnetModule`. |
339,535 | def _init_client(self, from_archive=False):
return MattermostClient(self.url, self.api_token,
max_items=self.max_items,
sleep_for_rate=self.sleep_for_rate,
min_rate_to_sleep=self.min_rate_to_sleep,
... | Init client |
339,536 | def stop(self):
self.ready = False
sock = getattr(self, "socket", None)
if sock:
if not isinstance(self.bind_addr, basestring):
try:
host, port = sock.getsockname()[:2]
except socket.error, x:
... | Gracefully shutdown a server that is serving forever. |
339,537 | def _kafka_failure(self, item, spider, response):
item[] = False
item[] = traceback.format_exc()
item[] = spider.name
item = self._clean_item(item)
self.logger.error("Failed to send page to Kafka", item) | Callback for failed send |
339,538 | def one_step(
objective_function,
population,
population_values=None,
differential_weight=0.5,
crossover_prob=0.9,
seed=None,
name=None):
with tf.compat.v1.name_scope(
name, ,
[population, population_values, differential_weight, crossover_prob]):
population, _ = _ensure_... | Performs one step of the differential evolution algorithm.
Args:
objective_function: A Python callable that accepts a batch of possible
solutions and returns the values of the objective function at those
arguments as a rank 1 real `Tensor`. This specifies the function to be
minimized. The inpu... |
339,539 | def timestamp_any(value):
return int(calendar.timegm(dateutil.parser.parse(value).utctimetuple())) | Convert timestamp string to time in seconds since epoch.
Most timestamps strings are supported in fact this wraps the
dateutil.parser.parse() method. This is SLOW use the other timestamp_*()
functions if possible.
Args:
value: A timestamp string.
Returns:
The time in seconds since... |
339,540 | def methodcallPayload(self, methodname, obj, namespace, **kwargs):
if isinstance(obj, CIMInstanceName):
path = obj.copy()
path.host = None
path.namespace = None
localpath = cim_xml.LOCALINSTANCEPATH(
cim_xml.LOCALNAMESPACEPATH(
... | Generate the XML payload for an extrinsic methodcall. |
339,541 | def vcsNodeState_originator_switch_info_switchIpV4Address(self, **kwargs):
config = ET.Element("config")
vcsNodeState = ET.SubElement(config, "vcsNodeState", xmlns="urn:brocade.com:mgmt:brocade-vcs")
originator_switch_info = ET.SubElement(vcsNodeState, "originator-switch-info")
... | Auto Generated Code |
339,542 | def getIDsFromFiles(files):
if type(files) is str:
files=glob.glob(files+"/*.*")
IDs=[]
for fname in files:
if fname[-4:].lower()==:
ext=fname.split()[-1]
IDs.append(os.path.basename(fname).replace(+ext,))
return sorted(IDs) | given a path or list of files, return ABF IDs. |
339,543 | def _get_initialized_channels_dict_for_service(self, org_id, service_id):
fn = self._get_channels_info_file(org_id, service_id)
if (os.path.isfile(fn)):
return pickle.load( open( fn, "rb" ) )
else:
return {} | return {channel_id: channel} |
339,544 | def mask(array, predicates, new_value, ty):
weld_obj = WeldObject(encoder_, decoder_)
array_var = weld_obj.update(array)
if isinstance(array, WeldObject):
array_var = array.obj_id
weld_obj.dependencies[array_var] = array
predicates_var = weld_obj.update(predicates)
if isinstan... | Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
new_value (WeldObject / Numpy.ndarray / str): mask value
... |
339,545 | def get_file_service_properties(self, timeout=None):
s File service, including
Azure Storage Analytics.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: The file service properties.
:rtype:
:class:`~azure.storage.common.models.S... | Gets the properties of a storage account's File service, including
Azure Storage Analytics.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: The file service properties.
:rtype:
:class:`~azure.storage.common.models.ServiceProperties` |
339,546 | def get_synth_input_fn(height, width, num_channels, num_classes):
def input_fn(is_training, data_dir, batch_size, *args, **kwargs):
images = tf.zeros((batch_size, height, width, num_channels), tf.float32)
labels = tf.zeros((batch_size, num_classes), tf.int32)
return tf.data.Dataset.from_tensors((imag... | Returns an input function that returns a dataset with zeroes.
This is useful in debugging input pipeline performance, as it removes all
elements of file reading and image preprocessing.
Args:
height: Integer height that will be used to create a fake image tensor.
width: Integer width that will be used t... |
339,547 | def should_build(self, fpath, meta):
if meta.get(, self.default_template) in self.inc_layout:
if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath):
return False
else:
return True
return True | Checks if the file should be built or not
Only skips layouts which are tagged as INCREMENTAL
Rebuilds only those files with mtime changed since previous build |
339,548 | def delete(self, storagemodel:object, modeldefinition = None) -> bool:
deleted = False
if (storagemodel.id != ) and (storagemodel.pop_receipt != ) and (not storagemodel.id is None) and (not storagemodel.pop_receipt is None):
try:
modeldefinition[].delete_message(stor... | delete the message in queue |
339,549 | def resize(self, dims):
width, height = dims[:2]
self.dims = (width, height)
self.logger.debug("renderer reconfigured to %dx%d" % (
width, height))
self.surface = agg.Draw(self.rgb_order, self.dims, ) | Resize our drawing area to encompass a space defined by the
given dimensions. |
339,550 | def get_tree(config=None):
path = os.path.dirname(os.path.abspath(__file__))
pypath = os.path.realpath(os.path.join(path, , ))
if pypath not in sys.path:
sys.path.append(pypath)
os.chdir(pypath)
from tree.tree import Tree
tree = Tree(config=config)
return tree | Get the tree for a given config
Parameters:
config (str):
The name of the tree config to load
Returns:
a Python Tree instance |
339,551 | def create_sockets(self):
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
rep = context.socket(zmq.REP)
if "REQ" in ports:
rep.bind(
"tcp://*:{port}".format(port=ports["REQ"])
... | create zmq sockets |
339,552 | def _parse_arguments():
parser = argparse.ArgumentParser(
description=
)
parser.add_argument(
,
,
action=,
help=
)
parser.add_argument(
,
,
help=
)
parser.add_argument(
,
,
action=,
help=
... | Constructs and parses the command line arguments for eg. Returns an args
object as returned by parser.parse_args(). |
339,553 | def _pool_put(pool_semaphore, tasks, put_to_pool_in, pool_size, id_self, \
is_stopping):
log.debug( % id_self)
last_tasks = {}
for task in xrange(tasks.lenght):
last_tasks[task] = -1
stop_tasks = []
while True:
if is... | (internal) Intended to be run in a seperate thread. Feeds tasks into
to the pool whenever semaphore permits. Finishes if self._stopping is
set. |
339,554 | def calculate_similarity(container1=None,
container2=None,
comparison=None,
metric=None):
if metric is None:
metric = information_coefficient
if comparison == None:
comparison = compare_containers(container1=contai... | calculate_similarity will calculate similarity of two containers
by files content, default will calculate
2.0*len(intersect) / total package1 + total package2
Parameters
==========
container1: container 1
container2: container 2 must be defined or
metric a function to take a total... |
339,555 | def _acking(self, params=None):
while self._is_running:
try:
t, num_try, (ip, port), packet = self._to_ack.get(
timeout=self._select_timeout
)
except queue.Empty:
continue
diff = t ... | Packet acknowledge and retry loop
:param params: Ignore
:type params: None
:rtype: None |
339,556 | def apply_defaults(self, instance):
for field, spec in self.doc_spec.iteritems():
field_type = spec[]
if field not in instance:
if in spec:
default = spec[]
if callable(default):
instance[field] = d... | Applies the defaults described by the this schema to the given
document instance as appropriate. Defaults are only applied to
fields which are currently unset. |
339,557 | def set_pattern_step_time(self, patternnumber, stepnumber, timevalue):
_checkPatternNumber(patternnumber)
_checkStepNumber(stepnumber)
_checkTimeValue(timevalue, self.time_max)
address = _calculateRegisterAddress(, patternnumber, stepnumber)
self.write_register(... | Set the step time.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* timevalue (integer??): 0-900 |
339,558 | def set_lcm_config(config_mode=None,
config_mode_freq=None,
refresh_freq=None,
reboot_if_needed=None,
action_after_reboot=None,
refresh_mode=None,
certificate_id=None,
configuration_id=No... | For detailed descriptions of the parameters see:
https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig
config_mode (str): How the LCM applies the configuration. Valid values
are:
- ApplyOnly
- ApplyAndMonitor
- ApplyAndAutoCorrect
config_mode_freq (int): How often, in... |
339,559 | def update(self, domain, type_name, search_command, body):
return self._request(domain, type_name, search_command, , body) | Update entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
this resource verbatim.
search_command (string): Search comman... |
339,560 | def merge_nodes(self, partition, consider_comms=None):
if (consider_comms is None):
consider_comms = self.consider_comms
diff = _c_leiden._Optimiser_merge_nodes(self._optimiser, partition._partition, consider_comms)
partition._update_internal_membership()
return diff | Merge nodes for *optimising* the partition.
Parameters
----------
partition
The partition for which to merge nodes.
consider_comms
If ``None`` uses :attr:`consider_comms`, but can be set to
something else.
Returns
-------
float
Improvement in quality function.
... |
339,561 | def cancelRequest(self, requestId, reason=None, _=None):
if reason is None:
reason = CancelledError()
tReq = self.requests.pop(requestId)
tReq.d.errback(reason) | Cancel a request: remove it from requests, & errback the deferred.
NOTE: Attempts to cancel a request which is no longer tracked
(expectResponse == False and already sent, or response already
received) will raise KeyError |
339,562 | def _per_era_supply(self, block_height):
coins = 0
for era in self.supply_data[]:
end_block = era[]
start_block = era[]
reward = era[]
if not end_block or block_height <= end_block:
blocks_this_era = block_height - start_block
... | Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era. |
339,563 | def unreferenced_vert(script):
if script.ml_version == :
filter_xml =
else:
filter_xml =
util.write_filter(script, filter_xml)
return None | Check for every vertex on the mesh: if it is NOT referenced by a face,
removes it.
Args:
script: the FilterScript object or script filename to write
the filter to.
Layer stack:
No impacts
MeshLab versions:
2016.12
1.3.4BETA |
339,564 | def place(self, part: str, val: Union[, ]):
if part.startswith():
if self.param and self.param != part:
err =
raise ParamAlreadyExist(err.format(part, self=self))
self.param = val
self.param_name = part
return val
... | place a leaf node |
339,565 | def func_desc_poco(self, step):
desc = {
"touch": u"点击UI组件 {name}".format(name=step.get("text", "")),
}
if step[] in desc:
return desc.get(step[])
else:
return self._translate_desc(step) | 把对应的poco操作显示成中文 |
339,566 | def increment_timeperiod(time_qualifier, timeperiod, delta=1):
pattern = define_pattern(timeperiod)
t = datetime.strptime(timeperiod, pattern)
if time_qualifier == QUALIFIER_HOURLY:
t = t + timedelta(hours=delta)
return t.strftime(SYNERGY_HOURLY_PATTERN)
elif time_qualifier == QU... | method performs simple increment/decrement of the timeperiods
For instance: 2010010119 with delta=1 -> 2010010120
Or 2010010000 with delta=-1 -> 2009120000, etc |
339,567 | def guess_lexer_for_filename(_fn, _text, **options):
fn = basename(_fn)
primary = {}
matching_lexers = set()
for lexer in _iter_lexerclasses():
for filename in lexer.filenames:
if _fn_matches(fn, filename):
matching_lexers.add(lexer)
primary[lexer... | Lookup all lexers that handle those filenames primary (``filenames``)
or secondary (``alias_filenames``). Then run a text analysis for those
lexers and choose the best result.
usage::
>>> from pygments.lexers import guess_lexer_for_filename
>>> guess_lexer_for_filename('hello.html', '<%= @... |
339,568 | def tangent(obj, params, **kwargs):
normalize = kwargs.get(, True)
if isinstance(obj, abstract.Curve):
if isinstance(params, (list, tuple)):
return ops.tangent_curve_single_list(obj, params, normalize)
else:
return ops.tangent_curve_single(obj, params, normalize)
... | Evaluates the tangent vector of the curves or surfaces at the input parameter values.
This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or
multiple parameter positions.
:param obj: input shape
:type obj: abstract.Curve or abstract.Surface
:param param... |
339,569 | def alloc_retrieve_subnet_info(self, tenant_id, direc):
serv_obj = self.get_service_obj(tenant_id)
subnet_dict = self.retrieve_dcnm_subnet_info(tenant_id, direc)
if subnet_dict:
return subnet_dict
ip_subnet_dict = self.get_next_ip(tenant_id, direc)
subnet_dic... | Allocate and store Subnet.
This function initially checks if subnet is allocated for a tenant
for the in/out direction. If not, it calls routine to allocate a subnet
and stores it on tenant object. |
339,570 | def find_person_by_id(self, person_id):
url =
params = {
: self.client_id,
: person_id
}
r = requests.get(url, params=params)
check_error(r)
return r.json() | doc: http://open.youku.com/docs/docs?id=87 |
339,571 | def log_the_survey_settings(
log,
pathToYamlFile):
import yaml
from datetime import datetime, date, time
now = datetime.now()
now = now.strftime("%Y%m%dt%H%M%S")
fileName = pathToYamlFile
stream = file(fileName, )
yamlContent = yaml.load(st... | *Create a MD log of the survey settings*
**Key Arguments:**
- ``log`` -- logger
- ``pathToYamlFile`` -- yaml results file
**Return:**
- None |
339,572 | def times(x, y):
def decorator(fn):
def wrapped(*args, **kwargs):
n = random.randint(x, y)
for z in range(1, n):
fn(*args, **kwargs)
return wrapped
return decorator | Do something a random amount of times
between x & y |
339,573 | def filter(self, **kwargs):
value__nevaluevalueothervaluevalue
selfCopy = self.__copy__()
return IndexedRedisQuery._filter(selfCopy, **kwargs) | filter - Add filters based on INDEXED_FIELDS having or not having a value.
Note, no objects are actually fetched until .all() is called
Use the field name [ model.objects.filter(some_field='value')] to filter on items containing that value.
Use the field name suffxed with '__ne' for a negation filter [ mo... |
339,574 | def _wavReadData(fid,
size:int,
channels:int,
encoding:str,
bigendian:bool) -> np.ndarray:
bits = int(encoding[3:])
if bits == 8:
data = np.fromfile(fid, dtype=np.ubyte, count=size)
if channels > 1:
data = d... | adapted from scipy.io.wavfile._read_data_chunk
assume we are at the data (after having read the size) |
339,575 | def _deserialize(self, value, attr, data):
value = super(SanitizedHTML, self)._deserialize(value, attr, data)
return bleach.clean(
value,
tags=self.tags,
attributes=self.attrs,
strip=True,
).strip() | Deserialize string by sanitizing HTML. |
339,576 | def read_scenarios(filename):
filename = os.path.abspath(filename)
blocks = {}
parser = ConfigParser()
return blocks | Read keywords dictionary from file.
:param filename: Name of file holding scenarios .
:return Dictionary of with structure like this
{{ 'foo' : { 'a': 'b', 'c': 'd'},
{ 'bar' : { 'd': 'e', 'f': 'g'}}
A scenarios file may look like this:
[jakarta_flood]
hazard: /path/t... |
339,577 | def H_donor_count(mol):
mol.require("Valence")
return sum(1 for _, a in mol.atoms_iter() if a.H_donor) | Hydrogen bond donor count |
339,578 | def __get_default_settings(self):
LOGGER.debug("> Accessing default settings file!".format(UiConstants.settings_file))
self.__default_settings = QSettings(
umbra.ui.common.get_resource_path(UiConstants.settings_file), QSettings.IniFormat) | Gets the default settings. |
339,579 | def update_network(network,
update_nodes = True,
update_links = True,
update_groups = True,
update_scenarios = True,
**kwargs):
log.info("Updating Network %s", network.name)
user_id = kwargs.get()
try:
net_i = db.DBSession.query(Network).filter(Network.id == network.id... | Update an entire network |
339,580 | def execute(self, offset=0, **query):
_params = self._build_query(**query)
self._page_offset = offset
_params.update(
offset=self._page_offset,
limit=min(self._page_size, self._limit)
)
logger.debug( %
(_params[], _params[])... | Executes a query. Additional query parameters can be passed
as keyword arguments.
Returns: The request parameters and the raw query response. |
339,581 | def create(cls, value):
if isinstance(value, bytes):
value = value.decode()
if isinstance(value, str):
comma_separated_exprs = cls._split_modifier_expr(value)
if len(comma_separated_exprs) > 1:
return cls.merge([cls.create(x) for x in comma_separated_exprs])
action = cls.MOD... | Interpret value as either a list or something to extend another list with.
Note that we accept tuple literals, but the internal value is always a list.
:param value: The value to convert. Can be an instance of ListValueComponent, a list, a tuple,
a string representation of a list or tuple (... |
339,582 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.field_name is not None:
_dict[] = self.field_name
if hasattr(self, ) and self.field_type is not None:
_dict[] = self.field_type
return _dict | Return a json dictionary representing this model. |
339,583 | def get_dimension_type(self, dim):
dim_obj = self.get_dimension(dim)
if dim_obj and dim_obj.type is not None:
return dim_obj.type
return self.interface.dimension_type(self, dim_obj) | Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Declared type of values along the dimension |
339,584 | def flex_loader(alias):
if not alias.startswith():
return
try:
if alias.startswith():
import pyamf.flex.messaging
elif alias.startswith():
import pyamf.flex
elif alias.startswith():
import pyamf.flex.data
return CLASS_CACHE[alias... | Loader for L{Flex<pyamf.flex>} framework compatibility classes.
@raise UnknownClassAlias: Trying to load an unknown Flex compatibility class. |
339,585 | def logpdf(self, mu):
if self.transform is not None:
mu = self.transform(mu)
return -np.log(float(self.sigma0)) - (0.5*(mu-self.mu0)**2)/float(self.sigma0**2) | Log PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) |
339,586 | def dictify_device_meta(device_object):
try:
if isinstance(device_object[][][], str) or \
isinstance(device_object[][][], unicode):
device_object[][][] =\
json.loads(device_object[][][])
except ValueError as err:
print("dictify: {0}".format(err))
... | Input: Portals device object.
Output: The same device object with the device meta
converted to a python dictionary. |
339,587 | def _init_metadata(self):
super(edXNumericResponseQuestionFormRecord, self)._init_metadata()
QuestionTextFormRecord._init_metadata(self)
QuestionFilesFormRecord._init_metadata(self) | stub |
339,588 | def tolocal(self):
from thunder.series.readers import fromarray
if self.mode == :
logging.getLogger().warn()
pass
return fromarray(self.toarray(), index=self.index, labels=self.labels) | Convert to local mode. |
339,589 | def safety_set_allowed_area_send(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z, force_mavlink1=False):
return self.send(self.safety_set_allowed_area_encode(target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z), force_mavlink1=force_mavlink1) | Set a safety zone (volume), which is defined by two corners of a cube.
This message can be used to tell the MAV which
setpoints/MISSIONs to accept and which to reject.
Safety areas are often enforced by national or
competition regulations.
... |
339,590 | def delays(self, delays=[]):
if delays:
return self._session.put(
self.__v1() + "/delays", data=json.dumps(delays)).json()
else:
return self._session.get(self.__v1() + "/delays").json() | Gets / Sets the delays. |
339,591 | def _create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False):
url = self.TEMPLATE_CREATE_EMBEDDED_DRAFT_URL
payload = {
: self... | Helper method for creating embedded template drafts.
See public function for params. |
339,592 | def result(self, result):
if result is None:
raise ValueError("Invalid value for `result`, must not be `None`")
allowed_values = ["OK", "ERROR"]
if result not in allowed_values:
raise ValueError(
"Invalid value for `result` ({0}), must be one ... | Sets the result of this ResponseStatus.
:param result: The result of this ResponseStatus. # noqa: E501
:type: str |
339,593 | def params_section(thing, doc, header_level):
lines = []
class_doc = doc["Parameters"]
return type_list(
inspect.signature(thing),
class_doc,
"
) | Generate markdown for Parameters section.
Parameters
----------
thing : functuon
Function to produce parameters from
doc : dict
Dict from numpydoc
header_level : int
Number of `#`s to use for header
Returns
-------
list of str
Markdown for examples secti... |
339,594 | def _handle_candles(self, dtype, data, ts):
self.log.debug("_handle_candles: %s - %s - %s", dtype, data, ts)
channel_id, *data = data
channel_identifier = self.channel_directory[channel_id]
entry = (data, ts)
self.candles[channel_identifier].put(entry) | Stores OHLC data received via wss in self.candles[chan_id].
:param dtype:
:param data:
:param ts:
:return: |
339,595 | def updateAcqEraEndDate(self, acquisition_era_name ="", end_date=0):
try:
self.dbsAcqEra.UpdateAcqEraEndDate( acquisition_era_name, end_date)
except dbsException as de:
dbsExceptionHandler(de.eCode, de.message, self.logger.exception, de.message)
except HTTPError ... | API to update the end_date of an acquisition era
:param acquisition_era_name: acquisition_era_name to update (Required)
:type acquisition_era_name: str
:param end_date: end_date not zero (Required)
:type end_date: int |
339,596 | def grid(self, force_rerun=False):
log.debug(.format(self.id))
if not self.receptormol2_path or not self.box_path:
return ValueError()
gridscript = op.join(self.dock_dir, "{}_grid.in".format(self.id))
out_name = op.join(self.dock_dir, "{}_grid.out".format(self.id))... | Create the scoring grid within the dummy box.
Args:
force_rerun (bool): If method should be rerun even if output file exists |
339,597 | def link(self, src, dst, label=None):
dst = self._normalize(dst)
self._tag(dst, label)
self._ensure_parent(dst)
abs_src = src
abs_dst = os.path.join(self.chroot, dst)
safe_copy(abs_src, abs_dst, overwrite=False) | Hard link file from ``src`` to ``chroot/dst`` with optional label.
May raise anything os.link can raise, e.g.
IOError(Errno 21 'EISDIR')
May raise ChrootTaggingException if dst is already in a fileset
but with a different label. |
339,598 | def _psdn(timeseries, method_func, *args, **kwargs):
try:
timeseries, other = timeseries
except ValueError:
return method_func(timeseries, kwargs.pop(), *args, **kwargs)
else:
return method_func(timeseries, other, kwargs.pop(),
*args, **kwarg... | Generate a PSD using a method function with FFT arguments in samples
All arguments are presumed to be in sample counts, not physical units
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`, `tuple`
the data to process, or a 2-tuple of series to correlate
method_func : `call... |
339,599 | def mergeNewMSBWT(mergedDir, inputBwtDirs, numProcs, logger):
re allowed to use
@param logger - output goes here
NOTE: in practice, since we
msbwts[i] = MultiStringBWT.loadBWT(dirName, logger)
mergedLength += msbwts[i].totalSize
binSize = 2**28
... | This function will take a list of input BWTs (compressed or not) and merge them into a single BWT
@param mergedFN - the destination for the final merged MSBWT
@param inputBWTFN1 - the fn of the first BWT to merge
@param inputBWTFN2 - the fn of the second BWT to merge
@param numProcs - number of processe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.