Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,200 | def get_encrpyted_path(original_path, surfix=default_surfix):
p = Path(original_path).absolute()
encrypted_p = p.change(new_fname=p.fname + surfix)
return encrypted_p.abspath | Find the output encrypted file /dir path (by adding a surfix).
Example:
- file: ``${home}/test.txt`` -> ``${home}/test-encrypted.txt``
- dir: ``${home}/Documents`` -> ``${home}/Documents-encrypted`` |
342,201 | def close(self) -> None:
if not self._closed:
self._async_client.close()
self._io_loop.close()
self._closed = True | Closes the HTTPClient, freeing any resources used. |
342,202 | def setup_logging(default_path=, default_level=logging.INFO, env_key=):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, ) as file:
try:
config = yaml.safe_load(file.read())
... | Logging setup. |
342,203 | def _dataset_info(dataset):
info = {}
info["uri"] = dataset.uri
info["uuid"] = dataset.uuid
tot_size = sum([dataset.item_properties(i)["size_in_bytes"]
for i in dataset.identifiers])
info["size_int"] = tot_size
info["size_str"] = sizeof_fmt(tot_size)
info["cr... | Return information about dataset as a dict. |
342,204 | def dataset(self):
if self.dataset_format:
return ".".join([self.dataset_name, self.dataset_format])
return self.dataset_name | Qualify the dataset_name with the dataset_format if supplied
:return: dataset name
:rtype: str |
342,205 | def tri_diag_solve(a, b, c, d):
n = len(a)
a, b, c, d = map(numpy.array, (a, b, c, d))
c[0] /= b[0]
d[0] /= b[0]
for i in range(1, n):
m = b[i] - a[i] * c[i - 1]
c[i] /= m
d[i] = (d[i] - a[i] * d[i - 1]) / m
x = d
for i in range(n - 2, -1, -1):
x[i] -= c[... | Solve a[i] * x[i-1] + b[i] * x[i] + c[i] * x[i+1] = d[i] for x[i]
Adapted from: http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm. |
342,206 | def currentPixmapRect(self):
pixmap = self.currentPixmap()
rect = self.rect()
size = pixmap.size()
x = rect.center().x() - (size.width() / 2.0)
y = rect.center().y() - (size.height() / 2.0)
return QtCore.QRect(x, y, size.width(), si... | Returns the rect that defines the boundary for the current pixmap
based on the size of the button and the size of the pixmap.
:return <QtCore.QRect> |
342,207 | def set_content(self, content):
if self.allows_content:
self.content = content.strip()
else:
raise UNTLStructureException(
% (self.tag,)
) | Set textual content for the object/node.
Verifies the node is allowed to contain content, and throws an
exception if not. |
342,208 | def locked_delete(self):
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).filter_by(**filters).delete() | Delete credentials from the SQLAlchemy datastore. |
342,209 | def resolve(input, representation, resolvers=None, **kwargs):
resultdict = query(input, representation, resolvers, **kwargs)
result = resultdict[0][] if resultdict else None
if result and len(result) == 1:
result = result[0]
return result | Resolve input to the specified output representation |
342,210 | def changeThreadTitle(self, title, thread_id=None, thread_type=ThreadType.USER):
thread_id, thread_type = self._getThread(thread_id, thread_type)
if thread_type == ThreadType.USER:
return self.changeNickname(
title, thread_id, thread_id=thread_id, threa... | Changes title of a thread.
If this is executed on a user thread, this will change the nickname of that user, effectively changing the title
:param title: New group thread title
:param thread_id: Group ID to change title of. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_th... |
342,211 | def Nads_in_slab(self):
return sum([self.composition.as_dict()[a] for a \
in self.ads_entries_dict.keys()]) | Returns the TOTAL number of adsorbates in the slab on BOTH sides |
342,212 | def ensure_overlap_ratio(self, required_ratio=0.5):
msg = \
for i in range(0, len(self) - 1):
b1 = self[i]
b2 = self[i + 1]
try:
ratio = b1.intersection_ratio(b2)
except ValueError:
ratio = 0
... | Ensure that every adjacent pair of frequency bands meets the overlap
ratio criteria. This can be helpful in scenarios where a scale is
being used in an invertible transform, and something like the `constant
overlap add constraint
<https://ccrma.stanford.edu/~jos/sasp/Constant_Overlap_Ad... |
342,213 | def timespan_type(arg):
try:
arg = parse_timespan(arg)
except ValueError:
raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg)))
return arg | An argparse type representing a timespan such as 6h for 6 hours. |
342,214 | def bind_bottom_up(lower, upper, __fval=None, **fval):
if __fval is not None:
fval.update(__fval)
lower.payload_guess = lower.payload_guess[:]
lower.payload_guess.append((fval, upper)) | Bind 2 layers for dissection.
The upper layer will be chosen for dissection on top of the lower layer, if
ALL the passed arguments are validated. If multiple calls are made with the same # noqa: E501
layers, the last one will be used as default.
ex:
>>> bind_bottom_up(Ether, SNAP, type=0x1234)... |
342,215 | def update(cls,table, dic, Id):
if dic:
req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format() + " RETURNING * "
r = abstractRequetesSQL.formate(req, SET=dic, table=table, args=dict(dic, __id=Id))
return MonoExecutant(r)
return MonoExecutant... | Update row with Id from table. Set fields given by dic. |
342,216 | def get_characteristic_handle_from_uuid(self, uuid):
ch = self.get_characteristic_from_uuid(uuid)
return None if ch is None else ch.char_handle | Given a characteristic UUID, return its handle.
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, otherwise an integer handle. |
342,217 | def metric_arun_2010(topic_word_distrib, doc_topic_distrib, doc_lengths):
cm1 = np.linalg.svd(topic_word_distrib, compute_uv=False)
return np.sum(cm1*np.log(cm1/cm2)) + np.sum(cm2*np.log(cm2/cm1)) | Rajkumar Arun, V. Suresh, C. E. Veni Madhavan, and M. N. Narasimha Murthy. 2010. On finding the natural number of
topics with latent dirichlet allocation: Some observations. In Advances in knowledge discovery and data mining,
Mohammed J. Zaki, Jeffrey Xu Yu, Balaraman Ravindran and Vikram Pudi (eds.). Springer ... |
342,218 | def _match_getters(self, query, getters=None):
if getters is None:
getters = self._getters
if query in getters:
name, response = getters[query]
logger.debug( % name)
response = response.format(self._properties[name].get_value())
retur... | Tries to match in getters
:param query: message tuple
:type query: Tuple[bytes]
:return: response if found or None
:rtype: Tuple[bytes] | None |
342,219 | def create_firewall_rule(self, protocol, action, **kwargs):
body = {: protocol, : action}
if in kwargs:
body[] = kwargs[]
if in kwargs:
body[] = kwargs[]
if in kwargs:
body[] = kwargs[]
if in kwargs:
body[] = kwargs[]
... | Create a new firlwall rule |
342,220 | def setAllEntriesFromParList(self, aParList, updateModel=False):
theParamList = self._taskParsObj.getParList()
if len(aParList) != len(theParamList):
showwarning(message="Attempting to set parameter values from a "+ \
"list of different length ("+... | Set all the parameter entry values in the GUI to the values
in the given par list. If 'updateModel' is True, the internal
param list will be updated to the new values as well as the GUI
entries (slower and not always necessary). Note the
corresponding TparDisplay method. |
342,221 | def on_moved(self, event):
if not self._event_error:
pathtools_options = {
: self.patterns,
: self.ignore_patterns,
: self.case_sensitive,
}
if match_path(event.dest_p... | Called when a file or a directory is moved or renamed.
Many editors don't directly change a file, instead they make a
transitional file like ``*.part`` then move it to the final filename.
Args:
event: Watchdog event, either ``watchdog.events.DirMovedEvent`` or
``wat... |
342,222 | def _repr_html_(self):
rows =
s =
for k, v in self.__dict__.items():
rows += s.format(k=k, v=v)
html = .format(rows)
return html | Jupyter Notebook magic repr function. |
342,223 | def get_line_color(self, increment=1):
i = self.line_colors_index
self.line_colors_index += increment
if self.line_colors_index >= len(self.line_colors):
self.line_colors_index = self.line_colors_index-len(self.line_colors)
if self.line_colors_index >= len(self... | Returns the current color, then increments the color by what's specified |
342,224 | def dump_flags(efl):
if efl is None:
return
efl_dump = % ((efl & 0x3000) >> 12)
if efl & 0x100000:
efl_dump +=
else:
efl_dump +=
if efl & 0x80000:
efl_dump +=
else:
efl_dump +=
if ... | Dump the x86 processor flags.
The output mimics that of the WinDBG debugger.
Used by L{dump_registers}.
@type efl: int
@param efl: Value of the eFlags register.
@rtype: str
@return: Text suitable for logging. |
342,225 | def contract_from_file(fname):
f = open(fname)
j = f.read()
f.close()
return Contract(json.loads(j)) | Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load |
342,226 | def _orderedCleanDict(attrsObj):
def _filt(k, v):
if attr.has(v):
return not not any(attr.astuple(v))
return not not v
return attr.asdict(attrsObj,
dict_factory=OrderedDict,
recurse=False,
filter=_filt) | -> dict with false-values removed
Also evaluates attr-instances for false-ness by looking at the values of their properties |
342,227 | def init_config(self, app):
config_apps = [, ]
flask_talisman_debug_mode = [""]
for k in dir(config):
if any([k.startswith(prefix) for prefix in config_apps]):
app.config.setdefault(k, getattr(config, k))
if app.config[]:
app.config.setde... | Initialize configuration.
:param app: An instance of :class:`~flask.Flask`. |
342,228 | def call(method: Method, *args: Any, **kwargs: Any) -> Any:
return validate_args(method, *args, **kwargs)(*args, **kwargs) | Validates arguments and then calls the method.
Args:
method: The method to call.
*args, **kwargs: Arguments to the method.
Returns:
The "result" part of the JSON-RPC response (the return value from the method).
Raises:
TypeError: If arguments don't match function signature... |
342,229 | def rdp(M, epsilon=0, dist=pldist, algo="iter", return_mask=False):
if algo == "iter":
algo = partial(rdp_iter, return_mask=return_mask)
elif algo == "rec":
if return_mask:
raise NotImplementedError("return_mask=True not supported with algo=\"rec\"")
algo = rdp_rec
... | Simplifies a given array of points using the Ramer-Douglas-Peucker
algorithm.
Example:
>>> from rdp import rdp
>>> rdp([[1, 1], [2, 2], [3, 3], [4, 4]])
[[1, 1], [4, 4]]
This is a convenience wrapper around both :func:`rdp.rdp_iter`
and :func:`rdp.rdp_rec` that detects if the input is a ... |
342,230 | def get_narrow_url(self, instance):
text = instance[0]
request = self.context["request"]
query_params = request.GET.copy()
page_query_param = self.get_paginate_by_param()
if page_query_param and page_query_param in query_params:
del query_p... | Return a link suitable for narrowing on the current item. |
342,231 | def http_request(url, post_data=None):
logger.debug( % url)
buf = bio()
curl = pycurl.Curl()
curl.setopt(curl.URL, url.encode(, ))
if config()[][]:
curl.setopt(curl.SSL_VERIFYPEER, 0)
curl.setopt(curl.SSL_VERIFYHOST, 0)
if config()[][]:
curl.setopt(cu... | Make an HTTP request to a given URL with optional parameters. |
342,232 | def _write_json_blob(encoded_value, pipeline_id=None):
default_bucket = app_identity.get_default_gcs_bucket_name()
if default_bucket is None:
raise Exception(
"No default cloud storage bucket has been set for this application. "
"This app was likely created before v1.9.0, please see: "
"ht... | Writes a JSON encoded value to a Cloud Storage File.
This function will store the blob in a GCS file in the default bucket under
the appengine_pipeline directory. Optionally using another directory level
specified by pipeline_id
Args:
encoded_value: The encoded JSON string.
pipeline_id: A pipeline id t... |
342,233 | def hover(self, node):
if self.popup == False: return
if self.popup == True or self.popup.node != node:
if self.popup_text.has_key(node.id):
texts = self.popup_text[node.id]
else:
texts = None
self.popup = pop... | Displays a popup when hovering over a node. |
342,234 | def comments(self, case_id=None, variant_id=None, username=None):
logger.debug("Looking for comments")
comment_objs = self.query(Comment)
if case_id:
comment_objs = comment_objs.filter_by(case_id=case_id)
if variant_id:
comment_objs = comment_objs.filte... | Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant |
342,235 | def fixed_params(self):
fp = CombinedBounds(self.k.fixed_params, self.noise_k.fixed_params)
if self.mu is not None:
fp = CombinedBounds(fp, self.mu.fixed_params)
return fp | Combined fixed hyperparameter flags for the kernel, noise kernel and (if present) mean function. |
342,236 | def shallow_run(self):
self.n_points = len(self.date)
if not self.err.any():
self.err = np.ones(len(self.mag)) * np.std(self.mag)
elif not self.err.all():
np.putmask(self.err, self.err==0, np.median(self.err))
self.we... | Derive not-period-based features. |
342,237 | def reorder(self, module=None):
module = module._mdl if module is not None else ffi.NULL
lib.EnvReorderAgenda(self._env, module) | Reorder the Activations in the Agenda.
If no Module is specified, the current one is used.
To be called after changing the conflict resolution strategy. |
342,238 | def igetattr(self, name, context=None):
if name in self.special_attributes:
yield self.special_attributes.lookup(name)
return
try:
mro = self.super_mro()
except exceptions.SuperError as exc:
raise exceptions.AttributeIn... | Retrieve the inferred values of the given attribute name. |
342,239 | def locate_neighbourhood(self, lat, lng):
method =
q = % (lat, lng)
try:
result = self.service.request(, method, q=q)
return self.get_neighbourhood(result[],
result[])
except APIError:
pass | Find a neighbourhood by location. Uses the locate-neighbourhood_ API
call.
.. _locate-neighbourhood:
https://data.police.uk/docs/method/neighbourhood-locate/
:param lat: The latitude of the location.
:type lat: float or str
:param lng: The longitude of the location.... |
342,240 | def parse_input_object_type_definition(lexer: Lexer) -> InputObjectTypeDefinitionNode:
start = lexer.token
description = parse_description(lexer)
expect_keyword(lexer, "input")
name = parse_name(lexer)
directives = parse_directives(lexer, True)
fields = parse_input_fields_definition(lexer)
... | InputObjectTypeDefinition |
342,241 | def _recycle(self):
origin = self._origin
if origin == 0:
return False
available = self._extent - origin
self._data[:available] = self._data[origin:self._extent]
self._extent = available
self._origin = 0
return True | Reclaim buffer space before the origin.
Note: modifies buffer size |
342,242 | def log_likelihood(self, x, x_dims=(128, 128), standard=False):
mu, std, h, w = self.params
shape = tf.stack([32, x_dims[0], x_dims[1], self.num_latent, 1, 1])
x_reshape = tf.reshape(x, shape)
c = - 0.5 * math.log(2 * math.pi)
if standard is False:
density = ... | Calculate Log Likelihood with particular mean and std
x must be 2D. [batch_size * eqsamples* iwsamples, num_latent] |
342,243 | def unpack(word):
r
if not isinstance(word, str):
return word
val, = struct.unpack(, word.encode())
return val | r"""
>>> PackedAttributes.unpack(0)
0
>>> PackedAttributes.unpack('\x00\x00\x00\x01')
1
>>> PackedAttributes.unpack('abcd')
1633837924 |
342,244 | def value_counts(self, dropna=True):
from pandas import Index, Series
data = self._data[~self._mask]
value_counts = Index(data).value_counts()
array = value_counts.values
index = value_counts.index.astype(object)
i... | Returns a Series containing counts of each category.
Every category will have an entry, even those with a count of 0.
Parameters
----------
dropna : boolean, default True
Don't include counts of NaN.
Returns
-------
counts : Series
See Also... |
342,245 | def handle_oncogene_results(permutation_result, num_permutations):
mycols = [, , ,
, ,
, , ]
permutation_df = pd.DataFrame(permutation_result, columns=mycols)
permutation_df[] = mypval.bh_fdr(permutation_df[])
permutation_df[] = mypval.bh_fdr(permutation_df[])
... | Takes in output from multiprocess_permutation function and converts to
a better formatted dataframe.
Parameters
----------
permutation_result : list
output from multiprocess_permutation
Returns
-------
permutation_df : pd.DataFrame
formatted output suitable to save |
342,246 | def _post_run_hook(self, runtime):
outputs = self.aggregate_outputs(runtime=runtime)
self._melodic_dir = outputs.out_dir
NIWORKFLOWS_LOG.info()
return super(MELODICRPT, self)._post_run_hook(runtime) | generates a report showing nine slices, three per axis, of an
arbitrary volume of `in_files`, with the resulting segmentation
overlaid |
342,247 | def VerifyCipherSignature(self, remote_public_key):
if self.cipher_metadata.signature and remote_public_key:
stats_collector_instance.Get().IncrementCounter("grr_rsa_operations")
remote_public_key.Verify(self.serialized_cipher,
self.cipher_metadata.signature)
r... | Verifies the signature on the encrypted cipher block.
This method returns True if the signature verifies correctly with
the key given.
Args:
remote_public_key: The remote public key.
Returns:
None
Raises:
rdf_crypto.VerificationError: A signature and a key were both given but
... |
342,248 | def _data(self, cube, weighted, prune):
result = []
for slice_ in cube.slices:
if cube.has_mr:
return self._mr_index(cube, weighted, prune)
num = slice_.margin(axis=0, weighted=weighted, prune=prune)
den = slice_.margin(weighted=weighted, prun... | ndarray representing table index by margin. |
342,249 | def ensure_open(f, mode=):
r
fin = f
if isinstance(f, basestring):
if len(f) <= MAX_LEN_FILEPATH:
f = find_filepath(f) or f
if f and (not hasattr(f, ) or not hasattr(f, )):
if f.lower().endswith():
return gzip.open(f, mode=mode)
... | r""" Return a file pointer using gzip.open if filename ends with .gz otherwise open()
TODO: try to read a gzip rather than relying on gz extension, likewise for zip and other formats
TODO: monkey patch the file so that .write_bytes=.write and .write writes both str and bytes
>>> fn = os.path.join(DATA_PAT... |
342,250 | def validate_context(self):
if self.context and len(self.context) != len(set(self.context)):
LOGGER.error()
raise Exception() | Make sure there are no duplicate context objects
or we might end up with switched data
Converting the tuple to a set gets rid of the
eventual duplicate objects, comparing the length
of the original tuple and set tells us if we
have duplicates in the tuple or not |
342,251 | def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs):
objs_and_attrs = [
(real_env, [
"reward_range", "observation_space", "action_space", "frame_height",
"frame_width"
]),
(hparams, ["frame_stack_size", "intrinsic_reward_scale"])
]
kwargs = {
attr: getat... | Extracts simulated env kwargs from real_env and loop hparams. |
342,252 | def _get_destination_folder(json_spec, folder_name=None):
dest_folder = folder_name or json_spec.get() or
if not dest_folder.endswith():
dest_folder = dest_folder +
return dest_folder | Returns destination project in which the workflow should be created.
It can be set in the json specification or by --destination option supplied
with `dx build`.
The order of precedence is:
1. --destination, -d option,
2. 'folder' specified in the json file. |
342,253 | def write_backup_meta_data(self):
auto_backup_meta_file = os.path.join(self._tmp_storage_path, FILE_NAME_AUTO_BACKUP)
storage.storage_utils.write_dict_to_json(self.meta, auto_backup_meta_file) | Write the auto backup meta data into the current tmp-storage path |
342,254 | def create_executable_script(filepath, body, program=None):
program = program or "python"
if callable(body):
from rez.utils.sourcecode import SourceCode
code = SourceCode(func=body)
body = code.source
if not body.endswith():
body +=
with open(filepath, ) as f:
... | Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the script, 'python' if None |
342,255 | def _format_variant(self, case_id, gemini_variant, individual_objs,
index=0, add_all_info=False):
chrom = gemini_variant[]
if chrom.startswith() or chrom.startswith():
chrom = chrom[3:]
variant_dict = {
:chrom,
:str(gemini_var... | Make a puzzle variant from a gemini variant
Args:
case_id (str): related case id
gemini_variant (GeminiQueryRow): The gemini variant
individual_objs (list(dict)): A list of Individuals
index(int): The index of the variant
Returns:... |
342,256 | def get_nameserver_detail_output_show_nameserver_nameserver_portsymb(self, **kwargs):
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_nameserver_detail, "output")
show_nam... | Auto Generated Code |
342,257 | def _process(self, metric):
metric = self.key + + str(metric)
self.graphite._process(metric) | Process a metric by sending it to graphite |
342,258 | def _parse_ip(addr):
try:
address = netaddr.IPAddress(addr.strip())
except (ValueError, netaddr.AddrFormatError):
return None
if address.version == 6:
try:
return address.ipv4()
except netaddr.AddrConversionError:
pass
return addr... | Helper function to convert an address into an IPAddress object.
Canonicalizes IPv6-mapped (or compatible) IPv4 addresses into IPv4
addresses. Returns None if the address cannot be parsed. |
342,259 | def compare_dicts(d1, d2):
a = json.dumps(d1, indent=4, sort_keys=True)
b = json.dumps(d2, indent=4, sort_keys=True)
diff = ( + .join(difflib.ndiff(
a.splitlines(),
b.splitlines())))
return diff | Returns a diff string of the two dicts. |
342,260 | def validated(self, *args, **kwargs):
always_return_document = kwargs.pop(, False)
self.validate(*args, **kwargs)
if self._errors and not always_return_document:
return None
else:
return self.document | Wrapper around :meth:`~cerberus.Validator.validate` that returns
the normalized and validated document or :obj:`None` if validation
failed. |
342,261 | def prep_vep_cache(dbkey, ref_file, tooldir=None, config=None):
if config is None: config = {}
resource_file = os.path.join(os.path.dirname(ref_file), "%s-resources.yaml" % dbkey)
if os.path.exists(resource_file):
with open(resource_file) as in_handle:
resources = yaml.safe_load(in_... | Ensure correct installation of VEP cache file. |
342,262 | def GetArtifactCollectorArgs(flow_args, knowledge_base):
args = rdf_artifacts.ClientArtifactCollectorArgs()
args.knowledge_base = knowledge_base
args.apply_parsers = flow_args.apply_parsers
args.ignore_interpolation_errors = flow_args.ignore_interpolation_errors
args.max_file_size = flow_args.max_file_siz... | Prepare bundle of artifacts and their dependencies for the client.
Args:
flow_args: An `ArtifactCollectorFlowArgs` instance.
knowledge_base: contains information about the client
Returns:
rdf value object containing a list of extended artifacts and the
knowledge base |
342,263 | def autodoc_tuple2doc(module):
modulename = module.__name__
for membername, member in inspect.getmembers(module):
for tuplename, descr in _name2descr.items():
tuple_ = getattr(member, tuplename, None)
if tuple_:
logstring = f
if logstring not ... | Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS`
of `Models` into the respective docstring. |
342,264 | def get_decl_pair(self):
def get_tp():
decl = "struct "
if self.tpname is not None:
decl += self.tpname
if self.inherit is not None:
decl += " : " + self.inherit
yield decl
yield "{"
... | See Declarator.get_decl_pair. |
342,265 | def tan(x):
if isinstance(x, UncertainFunction):
mcpts = np.tan(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.tan(x) | Tangent |
342,266 | def get_importer(self):
try:
importer_path = settings.TRACK_IMPORTER_CLASS
except AttributeError:
raise ImproperlyConfigured()
try:
dot = importer_path.rindex()
except ValueError:
raise ImproperlyConfigured(t a Track Importer modul... | Resolve importer from TRACK_IMPORTER_CLASS setting. |
342,267 | async def pfmerge(self, dest, *sources):
all_k = []
all_hll_objects = list()
for hll_key in sources:
all_hll_objects.append(await self.get(hll_key))
random_hash_slot = self._random_id()
dest_data = await self.get(dest)
... | Merge N different HyperLogLogs into a single one.
Cluster impl:
Very special implementation is required to make pfmerge() work
But it works :]
It works by first fetching all HLL objects that should be merged and
move them to one hashslot so that pfmerge operation... |
342,268 | def protein_header_split_generator(elements, headers, ns):
for el in elements:
header_not_matching = False
for protein in el.findall( % ns[]):
if not any((re.search(h, protein.text) for h in headers)):
header_not_matching = True
break
if heade... | Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately |
342,269 | def output(self, value):
return super(Map, self).output(self.stream, value) | SPL output port assignment expression.
Arguments:
value(str): SPL expression used for an output assignment. This can be a string, a constant, or an :py:class:`Expression`.
Returns:
Expression: Output assignment expression that is valid as a the context of this operator. |
342,270 | def get_solution(self, parameters=None):
if not self.has_solution():
raise IllegalState()
try:
if not self.get_text():
return self.get_text().text
if not parameters:
parameters = self.get_parameters()
return self._g... | stub |
342,271 | def load_from_dict(dct=None, **kwargs):
dct = dct or dict()
dct.update(kwargs)
def _load_from_dict(metadata):
return dict(dct)
return _load_from_dict | Load configuration from a dictionary. |
342,272 | def moveEvent(self, event):
if not self.isMaximized() and not self.fullscreen_flag:
self.window_position = self.pos()
QMainWindow.moveEvent(self, event)
self.sig_moved.emit(event) | Reimplement Qt method |
342,273 | def subtract_and_get(self, delta):
with self._lock.exclusive:
self._value -= delta
return self._value | Atomically subtracts `delta` from the current value.
:param delta: The delta to subtract. |
342,274 | def log(self, severity, message):
self._err.write("%s %s\n" % (severity, message))
self._err.flush() | Logs messages about the state of this modular input to Splunk.
These messages will show up in Splunk's internal logs.
:param severity: ``string``, severity of message, see severities defined as class constants.
:param message: ``string``, message to log. |
342,275 | def scanJoiner(self, xEUI=, strPSKd=):
print % self.port
timeout = 500
if not isinstance(xEUI, str):
eui64 = self.__convertLongToString(xEUI)
if len(eui64) < 16:
eui64 = eui64.zfill(16)
print eui64
... | scan Joiner
Args:
xEUI: Joiner's EUI-64
strPSKd: Joiner's PSKd for commissioning
Returns:
True: successful to add Joiner's steering data
False: fail to add Joiner's steering data |
342,276 | def forward_backward_pd(x, f, g, L, h, tau, sigma, niter,
callback=None, **kwargs):
r
m = len(L)
if not all(isinstance(op, Operator) for op in L):
raise ValueError()
if not all(op.is_linear for op in L):
raise ValueError()
if not all(x in op.domain... | r"""The forward-backward primal-dual splitting algorithm.
The algorithm minimizes the sum of several convex functionals composed with
linear operators::
min_x f(x) + sum_i g_i(L_i x) + h(x)
where ``f``, ``g_i`` are convex functionals, ``L_i`` are linear
operators, and ``h`` is a convex and di... |
342,277 | def validate_integer(option, value):
if isinstance(value, integer_types):
return value
elif isinstance(value, string_type):
try:
return int(value)
except ValueError:
raise ValueError("The value of %s must be "
"an integer" % (opti... | Validates that 'value' is an integer (or basestring representation). |
342,278 | def predict_features(self, df_features, df_target, idx=0, **kwargs):
X = df_features.values
y = df_target.values
clf = ard(compute_score=True)
clf.fit(X, y.ravel())
return np.abs(clf.coef_) | For one variable, predict its neighbouring nodes.
Args:
df_features (pandas.DataFrame):
df_target (pandas.Series):
idx (int): (optional) for printing purposes
kwargs (dict): additional options for algorithms
Returns:
list: scores of each feat... |
342,279 | def has_error(self):
return next(
(True for cr in self.component_results
if cr.has_error()),
False
) | Returns whether there was a business logic error when fetching data
for any components for this property.
Returns:
boolean |
342,280 | def stratSRS2(f, G, y0, tspan, Jmethod=Jkpw, dW=None, J=None):
return _Roessler2010_SRK2(f, G, y0, tspan, Jmethod, dW, J) | Use the Roessler2010 order 1.0 strong Stochastic Runge-Kutta algorithm
SRS2 to integrate a Stratonovich equation dy = f(y,t)dt + G(y,t)\circ dW(t)
where y is d-dimensional vector variable, f is a vector-valued function,
G is a d x m matrix-valued function giving the noise coefficients and
dW(t) is a ve... |
342,281 | def _run(self, data, store, signal, context, *,
success_callback=None, stop_callback=None, abort_callback=None):
if data is None:
data = MultiTaskData()
data.add_dataset(self._name)
try:
if self._callback_init is not None:
self._... | The internal run method that decorates the public run method.
This method makes sure data is being passed to and from the task.
Args:
data (MultiTaskData): The data object that has been passed from the
predecessor task.
store (DataStoreDocument... |
342,282 | def point_in_multipolygon(point, multipoly):
coords_array = [multipoly[]] if multipoly[
] == "MultiPolygon" else multipoly[]
for coords in coords_array:
if _point_in_polygon(point, coords):
return True
return False | valid whether the point is located in a mulitpolygon (donut polygon is not supported)
Keyword arguments:
point -- point geojson object
multipoly -- multipolygon geojson object
if(point inside multipoly) return true else false |
342,283 | def get_authserver(self, domainid, serverid):
return self.api_call(
ENDPOINTS[][],
dict(domainid=domainid, serverid=serverid)) | Get an Authentication server |
342,284 | def _fail(response):
message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url)
try:
message += ", message:{}".format(response.json()["message"])
except (ValueError, KeyError):
pass
raise ApiFailure(message, respon... | Raise an ApiFailure pertaining to the given response |
342,285 | def read(self):
tic = datetime.now()
with open(self.filename, "rb") as fp_:
header = np.memmap(fp_, dtype=_HEADERTYPE, mode="r", shape=(1, ))
data = np.memmap(fp_, dtype=_SCANTYPE, offset=22016, mode="r")
logger.debug("Reading time %s", str(datetime.now() - tic)... | Read the data. |
342,286 | def oil(data_set=):
if not data_available(data_set):
download_data(data_set)
oil_train_file = os.path.join(data_path, data_set, )
oil_trainlbls_file = os.path.join(data_path, data_set, )
oil_test_file = os.path.join(data_path, data_set, )
oil_testlbls_file = os.path.join(data_path, data... | The three phase oil data from Bishop and James (1993). |
342,287 | def generate_key(action, path_or_id, settings=None, default=" (default)"):
settings = " {}".format(str(sorted(settings.items()))) if settings else default
return "{}: {}{}".format(action.upper(), path_or_id, settings) | generate_key: generate key used for caching
Args:
action (str): how video is being processed (e.g. COMPRESSED or DOWNLOADED)
path_or_id (str): path to video or youtube_id
settings (dict): settings for compression or downloading passed in by user
default (str): if ... |
342,288 | def _create_conversion_trie(strict):
t = pygtrie.CharTrie()
for beta, uni in _map.BETACODE_MAP.items():
if strict:
t[beta] = uni
else:
diacritics = beta[1:]
perms = itertools.permutations(diacritics)
... | Create the trie for betacode conversion.
Args:
text: The beta code text to convert. All of this text must be betacode.
strict: Flag to allow for flexible diacritic order on input.
Returns:
The trie for conversion. |
342,289 | def get_all(self):
with mutex:
items = self.values.items()
result = []
for k, v in items:
if not k or k == MetricDict.EMPTY_KEY:
key = None
else:
key = decoder.decode(k)
result.append((key, sel... | Returns a list populated by tuples of 2 elements, first one is
a dict with all the labels and the second elemnt is the value
of the metric itself |
342,290 | def pagerank_weighted(graph, initial_value=None, damping=0.85):
if initial_value == None: initial_value = 1.0 / len(graph.nodes())
scores = dict.fromkeys(graph.nodes(), initial_value)
iteration_quantity = 0
for iteration_number in range(100):
iteration_quantity += 1
convergence_ach... | Calculates PageRank for an undirected graph |
342,291 | def readline(self, timeout=500):
poll_result = self.poller.poll(timeout)
if poll_result:
line = self.io.readline().strip()
if self.io == sys.stdin and line == "[":
line = self.io.readline().strip()
try:
... | Try to read our I/O for 'timeout' milliseconds, return None otherwise.
This makes calling and reading I/O non blocking ! |
342,292 | def expand_paths(path):
pr = itertools.product
parts = MAGIC_BRACKETS.findall(path)
if not path:
return
if not parts:
return [path]
permutations = [[(p[0], i, 1) for i in p[1].split()] for p in parts]
return [_replace_all(path, i) for i in pr(*permutations)] | When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '../a/b.py', '../b/a.py', '../b/b... |
342,293 | def filter_on_demands(ava, required=None, optional=None):
if required is None:
required = {}
lava = dict([(k.lower(), k) for k in ava.keys()])
for attr, vals in required.items():
attr = attr.lower()
if attr in lava:
if vals:
for val in vals:
... | Never return more than is needed. Filters out everything
the server is prepared to return but the receiver doesn't ask for
:param ava: Attribute value assertion as a dictionary
:param required: Required attributes
:param optional: Optional attributes
:return: The possibly reduced assertion |
342,294 | def delete_alert(self, alert):
if not in alert:
return [False, ]
res = requests.delete(self.url + + str(alert[]), headers=self.hdrs, verify=self.ssl_verify)
if not self._checkResponse(res):
return [False, self.lasterr]
return [True, None] | **Description**
Deletes an alert.
**Arguments**
- **alert**: the alert dictionary as returned by :func:`~SdcClient.get_alerts`.
**Success Return Value**
``None``.
**Example**
`examples/delete_alert.py <https://github.com/draios/python-sdc-client... |
342,295 | def mavlink_packet(self, m):
if m.get_type() == "ADSB_VEHICLE":
id = + str(m.ICAO_address)
if id not in self.threat_vehicles.keys():
self.threat_vehicles[id] = ADSBVehicle(id=id, state=m.to_dict())
for mp in self.module_matchin... | handle an incoming mavlink packet |
342,296 | def get_addr(iface=, iface_type=):
if platform.system() in [, ]:
if iface_type == :
_AF_FAMILY = psutil.AF_LINK
elif iface_type in [, ]:
_AF_FAMILY = getattr(socket, .format(iface_type.upper()))
else:
raise SystemError()
else:
raise System... | 获取网络接口 ``iface`` 的 ``mac``
- 如果系统类型为 ``mac``, 使用 ``psutil``
- 其他使用 ``socket``
:param iface: ``网络接口``
:type iface: str
:return: ``mac地址/空``
:rtype: str/None |
342,297 | def ripping_of_cds():
install_package()
install_file_legacy(path=, username=env.user)
run()
install_file_legacy()
run() | Install the tools ripit and burnit in order to rip and burn audio cds.
More info: http://forums.debian.net/viewtopic.php?f=16&t=36826 |
342,298 | def is_symmetric(self, symprec=0.1):
sg = SpacegroupAnalyzer(self, symprec=symprec)
return sg.is_laue() | Checks if slab is symmetric, i.e., contains inversion symmetry.
Args:
symprec (float): Symmetry precision used for SpaceGroup analyzer.
Returns:
(bool) Whether slab contains inversion symmetry. |
342,299 | def _bse_cli_get_versions(args):
name = args.basis.lower()
metadata = api.get_metadata(args.data_dir)
if not name in metadata:
raise KeyError(
"Basis set {} does not exist. For a complete list of basis sets, use the command".format(
name))
version_data = {k: v[... | Handles the get-versions subcommand |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.