Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
362,400 | def preprocess_abstract_list(self, abstract_list):
for abstract_struct in abstract_list:
abs_format = abstract_struct[]
content_type = abstract_struct[]
content_zipped = abstract_struct[]
tcid = abstract_struct[]
trid = abstract_struct[]
... | Preprocess abstracts in database pickle dump format for ISI reader.
For each abstract, creates a plain text file with one sentence per
line, and stores metadata to be included with each statement from
that abstract.
Parameters
----------
abstract_list : list[dict]
... |
362,401 | def print_state(self):
def tile_string(value):
if value > 0:
return % (2 ** value,)
return " "
separator_line = * 25
print(separator_line)
for row in range(4):
print("|" + "|".join([tile_string(v) for v in ... | Prints the current state. |
362,402 | def add_service(self, zeroconf, service_type, name):
self.lock.acquire()
try:
self._internal_add(zeroconf, service_type, name)
finally:
self.lock.release() | Handle callback from zeroconf when a service has been discovered. |
362,403 | def set_file(self, file=None, is_modified=False, is_untitled=False):
LOGGER.debug("> Setting editor file.".format(file))
self.__file = file
self.__is_untitled = is_untitled
self.set_modified(is_modified)
self.set_title()
return True | Sets the editor file.
:param File: File to set.
:type File: unicode
:param is_modified: File modified state.
:type is_modified: bool
:param is_untitled: File untitled state.
:type is_untitled: bool
:return: Method success.
:rtype: bool |
362,404 | def katex_rendering_options(app):
options = trim(app.config.katex_options)
if options.startswith() and options.endswith():
options = trim(options[1:-1])
if options and not options.endswith():
options +=
return options | Strip katex_options from enclosing {} and append , |
362,405 | def get_profile_model():
user_profile_module = getattr(settings, , None)
if user_profile_module:
app_label, model_name = user_profile_module.split()
return get_model(app_label, model_name)
else:
return None | Returns configured user profile model or None if not found |
362,406 | def successful(self):
status = self.status
assert status >= COMPLETED, "status is %s" % status
return (self.status == COMPLETED) | Return True if the job finished with a COMPLETED status, False if it
finished with a CANCELLED or FAILED status. Raise an `AssertionError`
if the job has not completed |
362,407 | def get_int_value(self, section, option, default=0):
try:
return self.parser.getint(section, option)
except NoOptionError:
return int(default) | Get the int value of an option, if it exists. |
362,408 | def __merge_json_values(current, previous):
for value in current:
name = value[]
previous_value = __find_and_remove_value(previous, value)
if previous_value is not None:
flags = value[]
previous_flags = previous_value[]
if flags != previou... | Merges the values between the current and previous run of the script. |
362,409 | def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser, preserve_quotes: bool = False) -> \
Callable[[argparse.Namespace, List], Optional[bool]]:
import functools
def arg_decorator(func: Callable):
@functools.wraps(func)
def cmd_wrapper(cmd2_instance, statement... | A decorator to alter a cmd2 method to populate its ``args`` argument by parsing arguments with the given
instance of argparse.ArgumentParser, but also returning unknown args as a list.
:param argparser: unique instance of ArgumentParser
:param preserve_quotes: if True, then arguments passed to argparse mai... |
362,410 | def is_valid_device_id(device_id):
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A valid device identifier contains "
"only ascii word characters or dashes. "
"Device not added.", device_id)
return valid | Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not. |
362,411 | def create_property(self, model, name, description=None, property_type=PropertyType.CHAR_VALUE, default_value=None,
unit=None, options=None):
if model.category != Category.MODEL:
raise IllegalArgumentError("The model should be of category MODEL")
if not prop... | Create a new property model under a given model.
Use the :class:`enums.PropertyType` to select which property type to create to ensure that you
provide the correct values to the KE-chain backend. The default is a `PropertyType.CHAR_VALUE` which is a
single line text in KE-chain.
:param... |
362,412 | def do_macro(self, args: argparse.Namespace) -> None:
func = getattr(args, , None)
if func is not None:
func(self, args)
else:
self.do_help() | Manage macros |
362,413 | def insert_data(self, data, include_index=False, index_name=None):
gen = data.reset_index(drop=not include_index).iterrows()
else:
gen = enumerate(data)
for index, row in gen:
if is_dataframe:
row = row.to_dict()
elif include_index:
row[index_name] = ind... | Insert the contents of a Pandas DataFrame or a list of dictionaries into the table.
The insertion will be performed using at most 500 rows per POST, and at most 10 POSTs per
second, as BigQuery has some limits on streaming rates.
Args:
data: the DataFrame or list to insert.
include_index: whet... |
362,414 | def traverse_extract_fetch(config, wukey, stop_after_extraction=False):
config.kvlclient.setup_namespace({: (str,)})
try:
data = list(config.kvlclient.get(, (wukey,)))
if data:
if data[0][1]:
logger.info(, data)
return
else:
... | Given a config and a
`wukey=cbor.dumps((folder_name,subfolder_name))`, traverse the
folders to generate queries, issue them to Google, fetch the
results, and ingest them. |
362,415 | def example_lchab_to_lchuv():
print("=== Complex Example: LCHab->LCHuv ===")
lchab = LCHabColor(0.903, 16.447, 352.252)
print(lchab)
lchuv = convert_color(lchab, LCHuvColor)
print(lchuv)
print("=== End Example ===\n") | This function shows very complex chain of conversions in action.
LCHab to LCHuv involves four different calculations, making this the
conversion requiring the most steps. |
362,416 | def does_row_exist(self, table: str, field: str, value: Any) -> bool:
sql = ("SELECT COUNT(*) FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
row = self.fetchone(sql, value)
return True if row[0] >= 1 else False | Checks for the existence of a record by a single field (typically a
PK). |
362,417 | def issubset(list1, list2):
n = len(list1)
for startpos in range(len(list2) - n + 1):
if list2[startpos:startpos+n] == list1:
return True
return False | Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False |
362,418 | def restore_state(self, state):
tile_states = state.get(, {})
for address, tile_state in tile_states.items():
address = int(address)
tile = self._tiles.get(address)
if tile is None:
raise DataError("Invalid dumped state, tile does not exist ... | Restore the current state of this emulated device.
Args:
state (dict): A previously dumped state produced by dump_state. |
362,419 | def sort_tags_by_date(self, tags):
if self.options.verbose:
print("Sorting tags...")
tags.sort(key=lambda x: self.get_time_of_tag(x))
tags.reverse()
return tags | Sort all tags by date.
:param list(dict) tags: All tags.
:rtype: list(dict)
:return: Sorted list of tags. |
362,420 | def deps_status(self):
if not self.deps:
return [self.S_OK]
return [d.status for d in self.deps] | Returns a list with the status of the dependencies. |
362,421 | def xml(self, indent = ""):
xml = indent + "<" + self.__class__.__name__
xml += +self.id +
xml += +xmlescape(self.name) +
xml += +xmlescape(self.description) +
if self.paramflag:
xml += +self.paramflag +
if self.multi:
xml +=
... | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors |
362,422 | def resolve(self, current_file, rel_path):
search_path = [path.dirname(current_file)] + self.search_path
target_path = None
for search in search_path:
if self.exists(path.join(search, rel_path)):
target_path = path.normpath(path.join(search, rel_path))
break
if not target_pa... | Search the filesystem. |
362,423 | def BBI(Series, N1, N2, N3, N4):
bbi = (MA(Series, N1) + MA(Series, N2) +
MA(Series, N3) + MA(Series, N4)) / 4
DICT = {: bbi}
VAR = pd.DataFrame(DICT)
return VAR | 多空指标 |
362,424 | def edge_nei_overlap_bu(CIJ):
ECinfEC
ik, jk = np.where(CIJ)
lel = len(CIJ[ik, jk])
n = len(CIJ)
deg = degrees_und(CIJ)
ec = np.zeros((lel,))
degij = np.zeros((2, lel))
for e in range(lel):
neiik = np.setdiff1d(np.union1d(
np.where(CIJ[ik[e], :]), np.where(CIJ[:, ik... | This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "local bridges", i.e.
edges that link comp... |
362,425 | def translate(cls, val):
if val is None:
return cls.translate_none(val)
elif isinstance(val, string_types):
return cls.translate_str(val)
elif isinstance(val, bool):
return cls.translate_bool(val)
elif isinstance(val, integer_types):
... | Translate each of the standard json/yaml types to appropiate objects. |
362,426 | def action_log_delete(sender, instance, **kwargs):
if instance.pk is not None:
changes = model_instance_diff(instance, None)
log_entry = LogAction.objects.create_log_action(
instance=instance,
action=LogAction.DELETE,
changes=json.dumps(changes),
) | Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead. |
362,427 | def predict_f_samples(self, Xnew, num_samples):
mu, var = self._build_predict(Xnew, full_cov=True)
jitter = tf.eye(tf.shape(mu)[0], dtype=settings.float_type) * settings.jitter
samples = []
for i in range(self.num_latent):
L = tf.cholesky(var[i, :, :] + jitter)
... | Produce samples from the posterior latent function(s) at the points
Xnew. |
362,428 | def get_interfaces(impls):
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(impls, Mapping):
return {name: impls[name... | Get interfaces from their implementations. |
362,429 | def parse_relation(obj: dict) -> BioCRelation:
rel = BioCRelation()
rel.id = obj[]
rel.infons = obj[]
for node in obj[]:
rel.add_node(BioCNode(node[], node[]))
return rel | Deserialize a dict obj to a BioCRelation object |
362,430 | def read_creds_from_environment_variables():
creds = init_creds()
if in os.environ and in os.environ:
creds[] = os.environ[]
creds[] = os.environ[]
if in os.environ:
creds[] = os.environ[]
return creds | Read credentials from environment variables
:return: |
362,431 | def _get_file_size(file_path):
size = getsize(file_path)
file_size = bytearray(4)
pack_into(b"I", file_size, 0, size)
return file_size | Returns the size of the file at the specified file path, formatted as a 4-byte unsigned
integer bytearray. |
362,432 | def parseFile(self, fil) :
f = open(fil)
self.parseStr(f.read())
f.close() | Opens a file and parses it |
362,433 | def reserve_bits(self, num_bits, stream):
padded = self.interp.get_bitfield_padded()
num_bits = PYVAL(num_bits)
if padded:
num_bits = PYVAL(num_bits)
if num_bits + self.reserved_bits > self.max_bits:
return False
if not padded:
... | Used to "reserve" ``num_bits`` amount of bits in order to keep track
of consecutive bitfields (or are the called bitfield groups?).
E.g. ::
struct {
char a:8, b:8;
char c:4, d:4, e:8;
}
:param int num_bits: The number of bits to claim
... |
362,434 | def learn(self,
runs,
dir=1,
periodic=False,
recurrent=True,
randomSpeed=False,
learnRecurrent=False,
envelope=True,):
oldPlotting = self.plotting
self.plotting = False
self.simulate(10, 1, 1, 0, envel... | Traverses a sinusoidal trajectory across the environment, learning during
the process. A pair of runs across the environment (one in each direction)
takes 10 seconds if in a periodic larger environment, and 4 seconds in a
smaller nonperiodic environment.
:param runs: How many runs across the environmen... |
362,435 | def CDPP(flux, mask=[], cadence=):
rmswin = 13
svgwin = 49
if cadence == :
newsize = len(flux) // 30
flux = Downbin(flux, newsize, operation=)
flux_savgol = SavGol(np.delete(flux, mask), win=svgwin)
if len(flux_savgol):
return Scatter(flux_savgol / np.n... | Compute the proxy 6-hr CDPP metric.
:param array_like flux: The flux array to compute the CDPP for
:param array_like mask: The indices to be masked
:param str cadence: The light curve cadence. Default `lc` |
362,436 | def add_root(self, id_):
if (bool(self._rls.get_relationships_by_genus_type_for_source(id_, self._relationship_type).available()) or
bool(self._rls.get_relationships_by_genus_type_for_destination(id_, self._relationship_type).available())):
raise errors.AlreadyExists()
... | Adds a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: AlreadyExists - ``id`` is already in hierarchy
raise: NotFound - ``id`` not found
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionD... |
362,437 | async def do_connect(self, args):
params = args.split()
device =
workdir = None
try:
device = params[0]
except IndexError:
if self.tools.device:
device = self.tools.device
try:
workdir = params[1]
exce... | Connect to the PLM device.
Usage:
connect [device [workdir]]
Arguments:
device: PLM device (default /dev/ttyUSB0)
workdir: Working directory to save and load device information |
362,438 | def write_pdf(matrix, version, out, scale=1, border=None, color=,
background=None, compresslevel=9):
def write_string(writemeth, s):
writemeth(s.encode())
def to_pdf_color(clr):
def to_float(c):
if isinstance(c, float):
if not 0.0 <= c <=... | \
Serializes the QR Code as PDF document.
:param matrix: The matrix to serialize.
:param int version: The (Micro) QR code version
:param out: Filename or a file-like object supporting to write bytes.
:param scale: Indicates the size of a single module (default: 1 which
corresponds to 1 ... |
362,439 | def dkron(A,dA,B,dB, operation=):
if dA is None:
dA_param_num = 0
dA = np.zeros((A.shape[0], A.shape[1],1))
else:
dA_param_num = dA.shape[2]
if dB is None:
dB_param_num = 0
dB = np.zeros((B.shape[0], B.shape[1],1))
else:
dB_param_num = dB.shape[2]
... | Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (or 2D matrix)
Derivarives of B
operation: s... |
362,440 | def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerAdditionVertex, label, cast_to_integer_vertex(left), cast_to_integer_vertex(right)) | Adds one vertex to another
:param left: a vertex to add
:param right: a vertex to add |
362,441 | def clean_pip_env() -> Generator[None, None, None]:
require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None)
try:
yield
finally:
if require_venv is not None:
os.environ[PIP_REQUIRE_VIRTUALENV] = require_venv | A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist. |
362,442 | def mac_address(value,
allow_empty = False,
**kwargs):
if not value and not allow_empty:
raise errors.EmptyValueError( % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError(
... | Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <vali... |
362,443 | def get_ieee_rotation(structure, refine_rotation=True):
sga = SpacegroupAnalyzer(structure)
dataset = sga.get_symmetry_dataset()
trans_mat = dataset[]
conv_latt = Lattice(np.transpose(np.dot(np.transpose(
structure.lattice.matrix), np.linalg.inv(trans_mat)))... | Given a structure associated with a tensor, determines
the rotation matrix for IEEE conversion according to
the 1987 IEEE standards.
Args:
structure (Structure): a structure associated with the
tensor to be converted to the IEEE standard
refine_rotation (... |
362,444 | def get_distance(self, other, lbda=0.5, min_overlap=4):
if self.tree ^ other.tree:
if len(self.tree & other.tree) < min_overlap:
return 0
else:
t1, t2 = self._equalise_leaf_sets(other, False)
tmp_self = KendallColi... | Return the Euclidean distance between vectors v of
two trees. Must have the same leaf set (too lazy to check). |
362,445 | def NRM(f,a,b,best):
WARN = True
if float(f)==0:
print()
if not WARN : sys.exit()
m = (old_div(float(best),float(f))) * TRM(f,a,b)
return float(m) | Calculate NRM expected lab field and estimated ancient field
NRM(blab,best)= (best/blab)*TRM(blab) |
362,446 | def stats(self, name, value):
counter = self.get(name, CounterType.Statistics)
self._calculate_stats(counter, value)
self._update() | Calculates min/average/max statistics based on the current and previous values.
:param name: a counter name of Statistics type
:param value: a value to update statistics |
362,447 | def normalize(self):
corefs = []
types = []
avms = []
for term in self._terms:
if isinstance(term, TypeTerm):
types.append(term)
elif isinstance(term, AVM):
term.normalize()
avms.append(term)
eli... | Rearrange the conjunction to a conventional form.
This puts any coreference(s) first, followed by type terms,
then followed by AVM(s) (including lists). AVMs are
normalized via :meth:`AVM.normalize`. |
362,448 | def _parse(self):
elem_list = []
reading_element = None
reading_docs = None
waiting_docs = False
elem =
raw =
start = 0
end = 0
try:
if self.input_file == :
fd = sys.stdin
... | Parses the input file's content and generates a list of its elements/docstrings.
:returns: the list of elements |
362,449 | def sign_rsa_sha1(base_string, rsa_private_key):
if isinstance(base_string, unicode_type):
base_string = base_string.encode()
alg = _jwt_rs1_signing_algorithm()
key = _prepare_key_plus(alg, rsa_private_key)
s=alg.sign(base_string, key)
return binascii.b2a_base64(s)[:-1].decode() | **RSA-SHA1**
Per `section 3.4.3`_ of the spec.
The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
algorithm as defined in `RFC3447, Section 8.2`_ (also known as
PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To
use this method, the client MUST have established cl... |
362,450 | def log_pdf(self, y, mu, weights=None):
if weights is None:
weights = np.ones_like(mu)
nu = weights / self.scale
return sp.stats.gamma.logpdf(x=y, a=nu, scale=mu / nu) | computes the log of the pdf or pmf of the values under the current distribution
Parameters
----------
y : array-like of length n
target values
mu : array-like of length n
expected values
weights : array-like shape (n,) or None, default: None
c... |
362,451 | async def send_code_request(self, phone, *, force_sms=False):
phone = utils.parse_phone(phone) or self._phone
phone_hash = self._phone_code_hash.get(phone)
if not phone_hash:
try:
result = await self(functions.auth.SendCodeRequest(
phone,... | Sends a code request to the specified phone number.
Args:
phone (`str` | `int`):
The phone to which the code will be sent.
force_sms (`bool`, optional):
Whether to force sending as SMS.
Returns:
An instance of :tl:`SentCode`. |
362,452 | def process_children(self, node, parent, pmod):
for ch in node.i_children:
if ch.keyword in ["rpc", "notification"]: continue
if ch.keyword in ["choice", "case"]:
self.process_children(ch, parent, pmod)
continue
if ch.i_module.i_module... | Process all children of `node`, except "rpc" and "notification". |
362,453 | def update(ctx, opts, owner_repo_identifier, show_tokens, name, token):
owner, repo, identifier = owner_repo_identifier
use_stderr = opts.output != "pretty"
click.secho(
"Updating %(identifier)s entitlement for the %(repository)s "
"repository ... "
% {
"ident... | Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your-repo/abcdef123456'
Full CLI example:
$ cloudsmi... |
362,454 | def set_namespace_view_settings(self):
if self.namespacebrowser:
settings = to_text_string(
self.namespacebrowser.get_view_settings())
code =(u"get_ipython().kernel.namespace_view_settings = %s" %
settings)
self.silent_execute(code) | Set the namespace view settings |
362,455 | def write(self, filename, entities, sortkey=None, columns=None):
if os.path.exists(filename):
raise IOError(%filename)
if sortkey:
entities = sorted(entities, key=lambda x:x[sortkey])
if not columns:
columns = set()
for entity in entities:
columns |= set(entity.keys... | Write entities out to filename in csv format.
Note: this doesn't write directly into a Zip archive, because this behavior
is difficult to achieve with Zip archives. Use make_zip() to create a new
GTFS Zip archive. |
362,456 | def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
return get_paths(scheme, vars, expand)[name] | Return a path corresponding to the scheme.
``scheme`` is the install scheme name. |
362,457 | def search(self,q):
import re
pattern = re.compile("%s" % q)
result = {}
for i in self.allstockno:
b = re.search(pattern, self.allstockno[i])
try:
b.group()
result[i] = self.allstockno[i]
except:
pass
return result | Search. |
362,458 | def get_store(logger: Logger=None) -> :
from trading_bots.conf import settings
store_settings = settings.storage
store = store_settings.get(, )
if store == :
store =
elif store == :
store =
store_cls = load_class_by_name(store)
kwargs = store_cls.configure(store_settin... | Get and configure the storage backend |
362,459 | def interrupt (aggregate):
while True:
try:
log.warn(LOG_CHECK,
_("interrupt; waiting for active threads to finish"))
log.warn(LOG_CHECK,
_("another interrupt will exit immediately"))
abort(aggregate)
break
except Key... | Interrupt execution and shutdown, ignoring any subsequent
interrupts. |
362,460 | def UpsertTrigger(self, collection_link, trigger, options=None):
if options is None:
options = {}
collection_id, path, trigger = self._GetContainerIdWithPathForTrigger(collection_link, trigger)
return self.Upsert(trigger,
path,
... | Upserts a trigger in a collection.
:param str collection_link:
The link to the document collection.
:param dict trigger:
:param dict options:
The request options for the request.
:return:
The upserted Trigger.
:rtype:
dict |
362,461 | def download_image(self):
split = urlsplit(self.url)
filename = split.path.split("/")[-1]
if not os.path.exists(self.cache_directory):
os.makedirs(self.cache_directory)
filepath = os.path.join(self.cache_directory, filename)
data = urllib_request.... | Download the image and return the
local path to the image file. |
362,462 | def remove_hyperedge(self, hyperedge_id):
if not self.has_hyperedge_id(hyperedge_id):
raise ValueError("No such hyperedge exists.")
frozen_nodes = \
self._hyperedge_attributes[hyperedge_id]["__frozen_nodes"]
for node in frozen_nodes:
self._... | Removes a hyperedge and its attributes from the hypergraph.
:param hyperedge_id: ID of the hyperedge to be removed.
:raises: ValueError -- No such hyperedge exists.
Examples:
::
>>> H = UndirectedHypergraph()
>>> hyperedge_list = (["A", "B", "C"],
... |
362,463 | def indication(self, apdu):
if _debug: ServerSSM._debug("indication %r", apdu)
if self.state == IDLE:
self.idle(apdu)
elif self.state == SEGMENTED_REQUEST:
self.segmented_request(apdu)
elif self.state == AWAIT_RESPONSE:
self.await_response(ap... | This function is called for each downstream packet related to
the transaction. |
362,464 | def _cleanup(self, to_clean, allow=()):
if to_clean.keys() == ["links", "library", "version", "meta", "key", "data"]:
to_clean = to_clean["data"]
return dict(
[
[k, v]
for k, v in list(to_clean.items())
if... | Remove keys we added for internal use |
362,465 | def sinterstore(self, destination, *keys):
return self._execute([b, destination] + list(keys)) | This command is equal to :meth:`~tredis.RedisClient.sinter`, but
instead of returning the resulting set, it is stored in destination.
If destination already exists, it is overwritten.
.. note::
**Time complexity**: ``O(N*M)`` worst case where ``N`` is the
cardinality of ... |
362,466 | def _op(self, line, op=None, offset=0):
if op is None:
op = self.op_count[line]
return "line{}_gate{}".format(line, op + offset) | Returns the gate name for placing a gate on a line.
:param int line: Line number.
:param int op: Operation number or, by default, uses the current op count.
:return: Gate name.
:rtype: string |
362,467 | def action(source, func):
if asyncio.iscoroutinefunction(func):
async def innerfunc(arg):
await func(arg)
return arg
else:
def innerfunc(arg):
func(arg)
return arg
return map.raw(source, innerfunc) | Perform an action for each element of an asynchronous sequence
without modifying it.
The given function can be synchronous or asynchronous. |
362,468 | def linkify_hostgroups_realms_hosts(self, realms, hosts, forced_realms_hostgroups=True):
logger.info("Hostgroups / hosts / realms relation")
for hostgroup in self:
hostgroup_realm_name = hostgroup.realm
if hostgroup.realm not in realms:
realm = r... | Link between an hostgroup and a realm is already done in the configuration parsing
function that defines and checks the default satellites, realms, hosts and hosts groups
consistency.
This function will only raise some alerts if hosts groups and hosts that are contained
do not belong th... |
362,469 | def splitOnWords(self, transaction, addrOffset=0):
wordWidth = self.wordWidth
end = addrOffset
for tmp in transaction.walkFlatten(offset=addrOffset):
if isinstance(tmp, OneOfTransaction):
split = [self.splitOnWords(ch, end)
for ch in ... | :return: generator of TransPart instance |
362,470 | def daily_periods(self, range_start=datetime.date.min, range_end=datetime.date.max, exclude_dates=tuple()):
tz = self.timezone
period = self.period
weekdays = self.weekdays
current_date = max(range_start, self.start_date)
end_date = range_end
if self.end_date:
... | Returns an iterator of Period tuples for every day this schedule is in effect, between range_start
and range_end. |
362,471 | def write_file(path, content, mode=):
from peltak.core import context
from peltak.core import log
if context.get(, False):
log.info("Would overwrite <34>{path}<32> with:\n<90>{content}",
path=path,
content=content)
else:
with open(path, mode) ... | --pretend aware file writing.
You can always write files manually but you should always handle the
--pretend case.
Args:
path (str):
content (str):
mode (str): |
362,472 | def sign(self, data, nonce = None):
cls = self.__class__
if not self.__mont_priv:
raise MissingKeyException(
"Cannot sign using this XEdDSA instance, Montgomery private key missing."
)
if not isinstance(data, bytes):
raise TypeError... | Sign data using the Montgomery private key stored by this XEdDSA instance.
:param data: A bytes-like object containing the data to sign.
:param nonce: A bytes-like object with length 64 or None.
:returns: A bytes-like object encoding the signature with length SIGNATURE_SIZE.
If the non... |
362,473 | def properties_operator(cls, name):
def wrapper(self, *args, **kwargs):
output = getattr(super(cls, self), name)(*args, **kwargs)
return cls(output)
wrapped = getattr(cls, name)
wrapper.__name__ = wrapped.__name__
wrapper.__doc__ = wrapped.__doc__
return wrapper | Wraps a container operator to ensure container class is maintained |
362,474 | def render_publ_template(template, **kwargs):
text = render_template(
template.filename,
template=template,
image=image_function(
template=template,
category=kwargs.get(),
entry=kwargs.get()),
**kwargs
)
return text, caching.get_etag(... | Render out a template, providing the image function based on the args.
Returns tuple of (rendered text, etag) |
362,475 | def pop(self, amount=1) -> Union[BitVec, List[BitVec]]:
if amount > len(self.stack):
raise StackUnderflowException
values = self.stack[-amount:][::-1]
del self.stack[-amount:]
return values[0] if amount == 1 else values | Pops amount elements from the stack.
:param amount:
:return: |
362,476 | def get_rrset(self, section, name, rdclass, rdtype,
covers=dns.rdatatype.NONE, deleting=None, create=False,
force_unique=False):
try:
rrset = self.find_rrset(section, name, rdclass, rdtype, covers,
deleting, create, fo... | Get the RRset with the given attributes in the specified section.
If the RRset is not found, None is returned.
@param section: the section of the message to look in, e.g.
self.answer.
@type section: list of dns.rrset.RRset objects
@param name: the name of the RRset
@typ... |
362,477 | def merge(self, sample):
sample.general.assemblyfile =
if len(sample.general.fastqfiles) == 2:
outpath = os.path.join(sample.general.outputdirectory, )
make_path(outpath)
merge_path = os.path.join(self.path, )
make_... | Use bbmerge to merge paired FASTQ files for use in metagenomics pipelines. Create a report with the
total number of reads, and the number of reads that could be paired
:param sample: metadata sample object flagged as a metagenome |
362,478 | def aryule(X, order, norm=, allow_singularity=True):
r
assert norm in [, ]
r = CORRELATION(X, maxlags=order, norm=norm)
A, P, k = LEVINSON(r, allow_singularity=allow_singularity)
return A, P, k | r"""Compute AR coefficients using Yule-Walker method
:param X: Array of complex data values, X(1) to X(N)
:param int order: Order of autoregressive process to be fitted (integer)
:param str norm: Use a biased or unbiased correlation.
:param bool allow_singularity:
:return:
* AR coefficient... |
362,479 | def digit(uni_char, default_value=None):
uni_char = unicod(uni_char)
if default_value is not None:
return unicodedata.digit(uni_char, default_value)
else:
return unicodedata.digit(uni_char) | Returns the digit value assigned to the Unicode character uni_char as
integer. If no such value is defined, default is returned, or, if not
given, ValueError is raised. |
362,480 | def _read_bytes_from_socket(self, msglen):
chunks = []
bytes_recd = 0
while bytes_recd < msglen:
if self.stop.is_set():
raise InterruptLoop("Stopped while reading from socket")
try:
chunk = self.socket.recv(min(msglen - bytes_recd,... | Read bytes from the socket. |
362,481 | def print_stats(self, header=True, file=sys.stdout):
if header:
print("CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}".format(
"HIT", "MISS", "LOAD", "STORE", "EVICT"), file=file)
for s in self.stats():
print("{name:>5} {HIT_count:>6} ({HIT_byte:>8}B) {MIS... | Pretty print stats table. |
362,482 | def __get_initial_center(self, return_index):
index_center = random.randint(0, len(self.__data) - 1)
if return_index:
return index_center
return self.__data[index_center] | !
@brief Choose randomly first center.
@param[in] return_index (bool): If True then return center's index instead of point.
@return (array_like) First center.<br>
(uint) Index of first center. |
362,483 | def SensorsTriggersGet(self, sensor_id, trigger_id = -1):
if trigger_id == -1:
url = .format(sensor_id)
else:
url = .format(sensor_id, trigger_id)
if self.__SenseApiCall__(url, ):
return True
else:
self.__error__ = "api ... | Obtain either all triggers connected to a sensor, or the details of a specific trigger connected to a sensor.
If successful, result can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - Sensor id of the sensor to retrieve triggers from.
... |
362,484 | def write(self, oprot):
oprot.write_struct_begin()
oprot.write_field_begin(name=, type=13, id=None)
oprot.write_map_begin(11, len(self.attributes), 11)
for __key0, __value0 in self.attributes.items():
oprot.write_string(__key0)
oprot.write_string(__valu... | Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_object_detail.OnlineDatabaseObjectDetail |
362,485 | def _check_time_range(time_range, now):
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range[])
_end = dateutil_parser.parse(time_range[])
return bool(_start <= now <= _end)
else:
log.error()
return False | Check time range |
362,486 | def _size(self):
assert isinstance(self, Value)
return int(self.val[0]) - int(self.val[1]) | :return: how many bits is this slice selecting |
362,487 | def compile_command(context, backend, config):
logger = logging.getLogger("boussole")
logger.info(u"Building project")
try:
discovering = Discover(backends=[SettingsBackendJson,
SettingsBackendYaml])
config_filepath, config_engine = discove... | Compile Sass project sources to CSS |
362,488 | def lessThanOrEqual(self, value):
newq = self.copy()
newq.setOp(Query.Op.LessThanOrEqual)
newq.setValue(value)
return newq | Sets the operator type to Query.Op.LessThanOrEqual and sets
the value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThanOrEqual
:usage |>>> from orb import Query as Q
|>>>... |
362,489 | def _find_advisory_targets(name=None,
advisory_ids=None,
**kwargs):
cur_patches = __salt__[](**kwargs)
if advisory_ids:
to_download = advisory_ids
else:
to_download = [name]
if cur_patches.get(name, {}):
... | Inspect the arguments to pkg.patch_installed and discover what advisory
patches need to be installed. Return a dict of advisory patches to install. |
362,490 | def _isobject(self, name, exist):
if exist in [2, 5]:
return False
cmd = % name
resp = self._engine.eval(cmd, silent=True).strip()
return resp == | Test whether the name is an object. |
362,491 | def forward_committor_sensitivity(T, A, B, index):
n = len(T)
set_X = numpy.arange(n)
set_A = numpy.unique(A)
set_B = numpy.unique(B)
set_AB = numpy.union1d(set_A, set_B)
notAB = numpy.setdiff1d(set_X, set_AB, True)
m = len(notAB)
K = T - numpy.diag(numpy.ones(n))
U... | calculate the sensitivity matrix for index of the forward committor from A to B given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
A : array like
List of integer state labels for set A
B : array like
List of integer state label... |
362,492 | def parse_form(self, req, name, field):
return core.get_value(req.POST, name, field) | Pull a form value from the request. |
362,493 | def startLogging(console=True, filepath=None):
global logLevelFilterPredicate
observers = []
if console:
observers.append( FilteringLogObserver(observer=textFileLogObserver(sys.stdout),
predicates=[logLevelFilterPredicate] ))
if filepath is not None and filepath != ""... | Starts the global Twisted logger subsystem with maybe
stdout and/or a file specified in the config file |
362,494 | def buffer(self, byte_offset=0):
contents = self.ptr.contents
ptr = addressof(contents.buffer.contents) + byte_offset
length = contents.length * 4 - byte_offset
return buffer((c_char * length).from_address(ptr).raw) \
if length else None | Get a copy of the map buffer |
362,495 | def as_text(self):
if self.secret_exponent():
return self.wif()
sec_hex = self.sec_as_hex()
if sec_hex:
return sec_hex
return self.address() | Return a textual representation of this key. |
362,496 | def read_all_from_datastore(self):
self._work = {}
client = self._datastore_client
parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id)
for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key):
work_id = entity.key.flat_path[-1]
self.work[work_id] = dict(entit... | Reads all work pieces from the datastore. |
362,497 | def SignFiles(self, filenames):
file_list = " ".join(filenames)
subprocess.check_call("%s %s" % (self._signing_cmdline, file_list))
if self._verification_cmdline:
subprocess.check_call("%s %s" % (self._verification_cmdline, file_list)) | Signs multiple files at once. |
362,498 | def soup(self):
dom = BeautifulSoup()
if len(dom) > 1:
list(dom.children)[1].replaceWith()
soup = Element.soup(self)
dom.append(soup)
for plugin in self.plugins(deduplicate=True):
dom = plugin(dom)
return dom | Running plugins and adding an HTML doctype to the
generated Tag HTML. |
362,499 | def slice(string, start=None, end=None):
if start is None:
start = 0
if end is not None and start >= end:
return ""
if start < 0:
raise NotImplementedError("Negative indexing is currently not supported.")
sum_ = 0
start_index = None
for grapheme_index, grapheme_le... | Returns a substring of the given string, counting graphemes instead of codepoints.
Negative indices is currently not supported.
>>> string = "tamil நி (ni)"
>>> string[:7]
'tamil ந'
>>> grapheme.slice(string, end=7)
'tamil நி'
>>> string[7:]
'ி (ni)'
>>> grapheme.slice(string, 7)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.