Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,400 | def edit(self,
billing_email=None,
company=None,
email=None,
location=None,
name=None):
json = None
data = {: billing_email, : company,
: email, : location, : name}
self._remove_none(data)
if data:... | Edit this organization.
:param str billing_email: (optional) Billing email address (private)
:param str company: (optional)
:param str email: (optional) Public email address
:param str location: (optional)
:param str name: (optional)
:returns: bool |
344,401 | def create_deep_linking_urls(self, url_params):
url = "/v1/url/bulk/%s" % self.branch_key
method = "POST"
self._check_param(value=url_params, type=list, sub_type=dict, optional=False)
return self.make_api_call(method, url, json_params=url_params) | Bulk Creates Deep Linking URLs
See the URL https://dev.branch.io/references/http_api/#bulk-creating-deep-linking-urls
:param url_params: Array of values returned from "create_deep_link_url(..., skip_api_call=True)"
:return: The response |
344,402 | def _add_element_by_names(src, names, value, override=False, digit=True):
if src is None:
return False
else:
if names and names[0]:
head, *rest = names
if isinstance(src, list):
if force_list(digit)[0] and head.isdigit():
... | Internal method recursive to Add element into a list or dict easily using
a path.
============= ============= =======================================
Parameter Type Description
============= ============= =======================================
src list or dict ... |
344,403 | def delete_collection_namespaced_role(self, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_collection_namespaced_role_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_role_with_http_info(namespace, **... | delete collection of Role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_role(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
... |
344,404 | def select_file(self, filters=all_true, recursive=True):
for p in self.select(filters, recursive):
if p.is_file():
yield p | Select file path by criterion.
**中文文档**
根据filters中定义的条件选择文件。 |
344,405 | def refreshCatalogs(self):
to_refresh = self.refreshcatalog[:]
to_reindex = self.reindexcatalog.keys()
to_reindex = to_reindex[:]
done = []
for catalog_to_refresh in to_refresh:
logger.info(
.format(catalog_to_refresh))
ca... | It reindexes the modified catalogs but, while cleanAndRebuildCatalogs
recatalogs all objects in the database, this method only reindexes over
the already cataloged objects.
If a metacolumn is added it refreshes the catalog, if only a new index
is added, it reindexes only those new index... |
344,406 | def decode_base64_and_inflate(value):
decoded = base64.b64decode(value)
try:
result = zlib.decompress(decoded, -15)
except Exception:
result = decoded
return result.decode() | base64 decodes and then inflates according to RFC1951
:param value: a deflated and encoded string
:type value: string
:returns: the string after decoding and inflating
:rtype: string |
344,407 | def fromfile(cls, f):
filter = cls()
filter._setup(*unpack(cls.FILE_FMT, f.read(calcsize(cls.FILE_FMT))))
nfilters, = unpack(b, f.read(calcsize(b)))
if nfilters > 0:
header_fmt = b + b*nfilters
bytes = f.read(calcsize(header_fmt))
filter_lengt... | Deserialize the ScalableBloomFilter in file object `f'. |
344,408 | def _get_newest_ts_in_table(self, table_name):
logger.debug(
, table_name
)
q = "SELECT TIMESTAMP_TO_SEC(MAX(timestamp)) AS max_ts %s;" % (
self._from_for_table(table_name)
)
res = self._run_query(q)
ts = int(res[0][])
logger.debug... | Return the timestamp for the newest record in the given table.
:param table_name: name of the table to query
:type table_name: str
:return: timestamp of newest row in table
:rtype: int |
344,409 | def _stdin_ready_posix():
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) | Return True if there's something to read on stdin (posix version). |
344,410 | def getRtplotWins(self):
try:
if self.isFF():
return
elif self.isDrift():
xbin = self.wframe.xbin.value()
ybin = self.wframe.ybin.value()
nwin = 2*self.wframe.npair.value()
ret = str(xbin) + + str(... | Returns a string suitable to sending off to rtplot when
it asks for window parameters. Returns null string '' if
the windows are not OK. This operates on the basis of
trying to send something back, even if it might not be
OK as a window setup. Note that we have to take care
here ... |
344,411 | def check_AP_raw(abf,n=10):
timePoints=get_AP_timepoints(abf)[:n]
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP shape (n=%d)"%n,xlabel="ms")
Ys=abf.get_data_around(timePoints,padding=.2)
Xs=(np.arange(len(Ys[0]))-len(Ys[0])/2)*1000/abf.rate
for i in range(1,len(Y... | X |
344,412 | def segwit_address(self):
if self._segwit_address is None and self.is_compressed:
self._segwit_address = multisig_to_segwit_address(self.public_keys,
self.m, version=self.version)
return self._segwit_address | The public segwit nested in P2SH address you share with others to
receive funds. |
344,413 | def format_energy_results(energy):
if not energy:
return {}
result = {}
cpuenergy = Decimal(0)
for pkg, domains in energy.items():
for domain, value in domains.items():
if domain == DOMAIN_PACKAGE:
cpuenergy += value
result[.format(pkg)] =... | Take the result of an energy measurement and return a flat dictionary that contains all values. |
344,414 | def forwards(apps, schema_editor):
Event = apps.get_model(, )
for ev in Event.objects.filter(kind=):
ev.kind =
ev.save()
for ev in Event.objects.filter(kind=):
ev.kind =
ev.save() | Change Events with kind 'movie' to 'cinema'
and Events with kind 'play' to 'theatre'.
Purely for more consistency. |
344,415 | def _long2bytes(n, blocksize=0):
s =
pack = struct.pack
while n > 0:
s = pack(, n & 0xffffffffL) + s
n = n >> 32
for i in range(len(s)):
if s[i] <> :
break
else:
s =
i = 0
s = s[i:]... | Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front
of the byte string with binary zeros so that the length is a multiple
of blocksize. |
344,416 | def dump(node, config):
if config.is_node(node):
fields = OrderedDict()
for name in config.fields_iter(node):
attr = config.field_val(node, name)
if attr is not None:
fields[name] = dump(attr, config)
return {"type": config.node_type(node), "data"... | Convert a node tree to a simple nested dict
All steps in this conversion are configurable using DumpConfig
dump dictionary node: {"type": str, "data": dict} |
344,417 | def patch(self, url: StrOrURL,
*, data: Any=None, **kwargs: Any) -> :
return _RequestContextManager(
self._request(hdrs.METH_PATCH, url,
data=data,
**kwargs)) | Perform HTTP PATCH request. |
344,418 | def impute_dataframe_range(df_impute, col_to_max, col_to_min, col_to_median):
columns = df_impute.columns
if not set(columns) <= set(col_to_median.keys()) or \
not set(columns) <= set(col_to_max.keys()) or \
not set(columns) <= set(col_to_min.keys()):
raise ValueError(... | Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values
from the provided dictionaries.
This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by
* ``-inf`` -> by value in col_to_min
* ``+inf`` -> by valu... |
344,419 | def random(self, num_bytes):
return pyhsm.basic_cmd.YHSM_Cmd_Random(self.stick, num_bytes).execute() | Get random bytes from YubiHSM.
The random data is DRBG_CTR seeded on each startup by a hardware TRNG,
so it should be of very good quality.
@type num_bytes: integer
@return: Bytes with random data
@rtype: string
@see: L{pyhsm.basic_cmd.YHSM_Cmd_Random} |
344,420 | def lock(remote=None):
def _do_lock(repo):
success = []
failed = []
if not os.path.exists(repo[]):
try:
with salt.utils.files.fopen(repo[], ):
pass
except (IOError, OSError) as exc:
msg = (
... | Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked. |
344,421 | def Q_weir_rectangular_full_SIA(h1, h2, b):
r
Q = 2/3.*2**0.5*(0.615 + 0.000615/(h1 + 0.0016))*b*g**0.5*h1 \
+ 0.5*(h1/(h1+h2))**2*b*g**0.5*h1**1.5
return Q | r'''Calculates the flow rate across a full-channel rectangular weir from
the height of the liquid above the crest of the weir, the liquid depth
beneath it, and the width of the channel. Model from [1]_ as reproduced in
[2]_.
Flow rate is given by:
.. math::
Q = \frac{2}{3}\sqrt{2}\left(0.6... |
344,422 | def privkey_to_wif(rawkey, compressed=True, net=BC):
k = net.wifprefix + rawkey
if compressed:
k += b
chksum = shasha(k).digest()[:4]
key = k + chksum
b58key = b58encode(key)
return b58key | Convert privkey bytes to Wallet Import Format (WIF). |
344,423 | def _tag_most_likely(examples):
tokenized_examples = [_tokenize_by_character_class(example) for example in examples]
token_lengths = [len(e) for e in tokenized_examples]
token_lengths_mode = _mode(token_lengths)
tokenized_examples = [example for example in tokenized_examples if len(examp... | Return a list of date elements by choosing the most likely element for a token within examples (context-free). |
344,424 | def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
if "remove_solution" not in resources:
raise KeyError("The resources dictionary must have a remove_solution key.")
if resources["remove_solution"]:
keep_cells_idx = []... | Preprocess the entire notebook. |
344,425 | def simple_expression(joiner=, **fields):
expression, params = [], {}
for field_name, value in sorted(fields.items(), key=lambda kv: kv[0]):
key = % field_name
expression.append( % (field_name, key))
params[key] = value
return joiner.join(expression), params | Build a simple expression ready to be added onto another query.
>>> simple_expression(joiner=' AND ', name='bob', role='admin')
"`name`=%(_QB_name)s AND `name`=%(_QB_role)s", { '_QB_name': 'bob', '_QB_role': 'admin' } |
344,426 | def diff(self, periods=1, axis=0):
axis = self._get_axis_number(axis)
return self.__constructor__(
query_compiler=self._query_compiler.diff(periods=periods, axis=axis)
) | Finds the difference between elements on the axis requested
Args:
periods: Periods to shift for forming difference
axis: Take difference over rows or columns
Returns:
DataFrame with the diff applied |
344,427 | def assembla_filter(func):
@wraps(func)
def wrapper(class_instance, **kwargs):
extra_params = kwargs.get(, None)
if extra_params:
del kwargs[]
results = func(class_instance, extra_params)
if kwargs:
results = filter(
... | Filters :data for the objects in it which possess attributes equal in
name/value to a key/value in kwargs.
Each key/value combination in kwargs is compared against the object, so
multiple keyword arguments can be passed in to constrain the filtering. |
344,428 | def _sort_by(key):
@staticmethod
def sort_by(p_list, reverse=False):
return sorted(
p_list,
key=lambda p: getattr(p, key),
reverse=reverse,
)
return sort_by | High order function for sort methods. |
344,429 | def getStr_to_pathlist(gs):
1uu1
def numize(w):
try:
int(w)
except:
try:
float(w)
except:
return(w)
else:
return(float(w))
else:
return(int(w))
def strip_quote(w):
if(ty... | gs = "[1]['1'][2]"
getStr_to_pathlist(gs)
gs = "['u']['u1']"
getStr_to_pathlist(gs) |
344,430 | def generate(variables, templates_path, main_template):
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(templates_path),
lstrip_blocks=True,
trim_blocks=True
)
def norm_alg_filename(alg_name):
if alg_name in variables[][]:
return variables[][][alg_... | :Parameters:
variables : dict
Template parameters, passed through.
templates_path : str
Root directory for transclusions.
main_template : str
Contents of the main template.
Returns the rendered output. |
344,431 | def find_files(self, root):
def is_ignored(path, ignore_patterns):
filename = os.path.basename(path)
ignore = lambda pattern: fnmatch.fnmatchcase(filename, pattern)
return any(ignore(pattern) for pattern in ignore_patterns)
dir_suffix = % os.s... | Helper method to get all files in the given root. |
344,432 | def drawSquiggle(self, p1, p2, breadth = 2):
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1
rad = abs(S)
cnt = 4 * int(round(rad / (4 * breadth), 0))
if cnt < 4:
raise ValueError("points too close")... | Draw a squiggly line from p1 to p2. |
344,433 | def limit(self, count):
return self.__class__(
self._parent,
projection=self._projection,
field_filters=self._field_filters,
orders=self._orders,
limit=count,
offset=self._offset,
start_at=self._start_at,
en... | Limit a query to return a fixed number of results.
If the current query already has a limit set, this will overwrite it.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
~.firestore_v1beta1.query.Query: A limited q... |
344,434 | def _getActions(self):
actions = _a11y.AXUIElement._getActions(self)
return [action[2:] for action in actions] | Retrieve a list of actions supported by the object. |
344,435 | def calculate_splits(sdf_file, split_size):
counts = _sdfstats(sdf_file)["counts"]
splits = []
cur = 0
for i in range(counts // split_size + (0 if counts % split_size == 0 else 1)):
splits.append("%s-%s" % (cur, min(counts, cur + split_size)))
cur += split_size
return splits | Retrieve |
344,436 | def n_frames_total(self, stride=1, skip=0):
r
if not IteratorState.is_uniform_stride(stride):
return len(stride)
return sum(self.trajectory_lengths(stride=stride, skip=skip)) | r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
skip the first initial n frames per trajectory.
... |
344,437 | def DOM_pushNodesByBackendIdsToFrontend(self, backendNodeIds):
assert isinstance(backendNodeIds, (list, tuple)
), "Argument must be of type listtuple. Received type: " % type(
backendNodeIds)
subdom_funcs = self.synchronous_command(
, backendNodeIds=backendNodeIds)
return subdom_funcs | Function path: DOM.pushNodesByBackendIdsToFrontend
Domain: DOM
Method name: pushNodesByBackendIdsToFrontend
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'backendNodeIds' (type: array) -> The array of backend node ids.
Returns:
'nodeIds' (type: array)... |
344,438 | def write(self, file_or_filename, prog=None, format=):
if prog is None:
file = super(DotWriter, self).write(file_or_filename)
else:
buf = StringIO.StringIO()
super(DotWriter, self).write(buf)
buf.seek(0)
data = self.create(buf.getvalue... | Writes the case data in Graphviz DOT language.
The format 'raw' is used to dump the Dot representation of the Case
object, without further processing. The output can be processed by any
of graphviz tools, defined in 'prog'. |
344,439 | def get_df_val_alt(lat: float, lon: float, da_alt_meas: xr.DataArray, ds_val: xr.Dataset):
da_alt = geopotential2geometric(ds_val.z, ds_val.latitude)
da_alt_x = da_alt.sel(
latitude=lat, longitude=lon, method=)
alt_meas_x = da_alt_meas.sel(
latitude=lat, longitude=lon, method=)[0]
... | interpolate atmospheric variables to a specified altitude
Parameters
----------
lat : float
latitude of specified site
lon : float
longitude of specified site
da_alt_x : xr.DataArray
desired altitude to interpolate variable at
da_alt : xr.DataArray
altitude assoc... |
344,440 | def check( state_engine, nameop, block_id, checked_ops ):
name = nameop[]
sender = nameop[]
namespace_id = get_namespace_from_name( name )
if not is_b40( name ) or "+" in name or name.count(".") > 1:
log.warning("Malformed name : non-base-38 characters" % name)
return False
... | Revoke a name--make it available for registration.
* it must be well-formed
* its namespace must be ready.
* the name must be registered
* it must be sent by the name owner
NAME_REVOKE isn't allowed during an import, so the name's namespace must be ready.
Return True if accepted
Return Fal... |
344,441 | def fitspoly(self, n, x, y, sd=None, wt=1.0, fid=0):
a = max(abs(max(x)), abs(min(x)))
if a == 0:
a = 1
a = 1.0 / a
b = NUM.power(a, range(n + 1))
if self.set(n=n + 1, fid=fid):
self.linear(poly(n), x * a, y, sd, wt, fid)
self._fitids[... | Create normal equations from the specified condition equations, and
solve the resulting normal equations. It is in essence a combination.
The method expects that the properties of the fitter to be used have
been initialized or set (like the number of simultaneous solutions m
the type; f... |
344,442 | def launched():
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool |
344,443 | def kill_conditional_comments(self, doc):
bad = []
self._kill_elements(
doc, lambda el: _conditional_comment_re.search(el.text),
etree.Comment) | IE conditional comments basically embed HTML that the parser
doesn't normally see. We can't allow anything like that, so
we'll kill any comments that could be conditional. |
344,444 | def extract_cosponsors(bill):
logger.debug("Extracting Cosponsors")
cosponsor_map = []
cosponsors = bill.get(, [])
bill_id = bill.get(, None)
for co in cosponsors:
co_list = []
co_list.append(co.get())
co_list.append(bill_id)
co_list.append(co.get())
co_... | Return a list of list relating cosponsors to legislation. |
344,445 | def get_ladder(session, ladder_id, user_id=None, user_ids=None, start=0, limit=LADDER_RESULT_LIMIT):
params = {
: start,
: limit
}
if isinstance(ladder_id, str):
ladder_id = lookup_ladder_id(ladder_id)
if limit > LADDER_RESULT_LIMIT:
raise VooblyError()
if user_i... | Get ladder. |
344,446 | def last_n_results(self, n):
return list(
itertools.islice(
self.results, len(self.results) - n, len(self.results)
)
) | Helper method for returning a set number of the previous check results. |
344,447 | def single_lf_summary(Y_p, Y=None):
L = sparse.csr_matrix(arraylike_to_numpy(Y_p).reshape(-1, 1))
return lf_summary(L, Y) | Calculates coverage, overlap, conflicts, and accuracy for a single LF
Args:
Y_p: a np.array or torch.Tensor of predicted labels
Y: a np.array or torch.Tensor of true labels (if known) |
344,448 | def remove_one(self):
self.__bulk.add_delete(self.__selector, _DELETE_ONE,
collation=self.__collation) | Remove a single document matching the selector criteria. |
344,449 | def expressions(self):
for s in self.statements:
for expr_ in s.expressions:
yield expr_
yield self.next | Return an iterator of all expressions contained in the IRSB. |
344,450 | def __calculate_goodness(self, cluster1, cluster2):
number_links = self.__calculate_links(cluster1, cluster2);
devider = (len(cluster1) + len(cluster2)) ** self.__degree_normalization - len(cluster1) ** self.__degree_normalization - len(cluster2) ** self.__degree_normalization;
... | !
@brief Calculates coefficient 'goodness measurement' between two clusters. The coefficient defines level of suitability of clusters for merging.
@param[in] cluster1 (list): The first cluster.
@param[in] cluster2 (list): The second cluster.
@return Goodness measu... |
344,451 | def _get_next_parent_node(self, parent):
grandparent = parent.parent
if grandparent is None:
return None
parent_siblings = list(grandparent.children)
sorted_keys = sorted(parent_siblings)
index = sorted_keys.index(parent.timeperiod)
if i... | Used by _get_next_child_node, this method is called to find next possible parent.
For example if timeperiod 2011010200 has all children processed, but is not yet processed itself
then it makes sense to look in 2011010300 for hourly nodes |
344,452 | def spendables_for_address(self, address):
spendables = []
url_append = "?unspentOnly=true&token=%s&includeScript=true" % self.api_key
url = self.base_url("addrs/%s%s" % (address, url_append))
result = json.loads(urlopen(url).read().decode("utf8"))
for txn in result.get(... | Return a list of Spendable objects for the
given bitcoin address. |
344,453 | def logical_intf_helper(interface):
if interface is None:
return LogicalInterface.get_or_create(name=).href
elif isinstance(interface, LogicalInterface):
return interface.href
elif interface.startswith():
return interface
return LogicalInterface.get_or_create(name=interface)... | Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface |
344,454 | def write(self, msg):
if self.closed: raise ValueError
if [] == self.output:
self.output = [msg]
else:
self.output[-1] += msg
pass
return | This method the debugger uses to write. In contrast to
writeline, no newline is added to the end to `str'. |
344,455 | def _forget_page(self, page):
pid = id(page)
if pid in self._page_refs:
self._page_refs[pid] = None | Remove a page from document page dict. |
344,456 | def _tweepy_status_to_tweet(self, status):
tweet = Tweet()
tweet.published_at = status.created_at
tweet.content = status.text
return tweet | Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline |
344,457 | def find_version(*file_paths):
file_path = os.path.join(*file_paths)
with open(file_path, ) as version_file:
line = version_file.readline()
while line:
if line.startswith():
version_match = re.search(
r"^__version__ = [\"]*)[Unable to find ver... | read __init__.py |
344,458 | def one_of_tags(tags, canonical_tag, name=None):
element = oneOf(tags).setParseAction(replaceWith(canonical_tag))
if name is None:
return element
return element.setResultsName(name) | Define the tags usable in the :class:`BelParser`.
For example, statements like ``g(HGNC:SNCA)`` can be expressed also as ``geneAbundance(HGNC:SNCA)``. The language
must define multiple different tags that get normalized to the same thing.
:param list[str] tags: a list of strings that are the tags for a fu... |
344,459 | def close(self):
if self._cache:
if self._update_cache:
self._write_cache_to_file()
self._cache = None | Write the contents of the cache to disk (only if `update_cache`
parameter during the object initialization was not set to `False`) and
clear the in memory cache. |
344,460 | def to_excel(self, filepath: str, title: str):
try:
self.start("Saving data to Excell file: "+filepath + " ...")
writer = pytablewriter.ExcelXlsxTableWriter()
writer.from_dataframe(self.df)
writer.open(filepath)
writer.make_worksheet(title)
... | Write the main dataframe to an Excell file
:param filepath: path of the Excel file to write
:type filepath: str
:param title: Title of the stylesheet
:type title: str
:example: ``ds.to_excel_("./myfile.xlsx", "My data")`` |
344,461 | def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
(f,arg) = xxx_todo_changeme
return f(arg,msg,severity,xmlTextReaderLocator(locator)) | Intermediate callback to wrap the locator |
344,462 | def _prompt_changer(attr, val):
try:
sys.ps1 = conf.color_theme.prompt(conf.prompt)
except Exception:
pass
try:
apply_ipython_style(get_ipython())
except NameError:
pass | Change the current prompt theme |
344,463 | def discard(self, interval):
if interval not in self:
return
self.all_intervals.discard(interval)
self.top_node = self.top_node.discard(interval)
self._remove_boundaries(interval) | Removes an interval from the tree, if present. If not, does
nothing.
Completes in O(log n) time. |
344,464 | def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):
if isinstance(start_color, Color):
start_color = start_color.rgb
if isinstance(end_color, Color):
end_color = end_color.rgb
step = tuple((end_color[i] - start_color[i])/step_count for i in range(3))
... | Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
the start and end color.
:param start_color: The color starting the run
:param end_color: The color ending the run
:param step_count: The number of colors to have between the start and end ... |
344,465 | def qmed_all_methods(self):
result = {}
for method in self.methods:
try:
result[method] = getattr(self, + method)()
except:
result[method] = None
return result | Returns a dict of QMED methods using all available methods.
Available methods are defined in :attr:`qmed_methods`. The returned dict keys contain the method name, e.g.
`amax_record` with value representing the corresponding QMED estimate in m³/s.
:return: dict of QMED estimates
:rtype:... |
344,466 | def gene(store, hgnc_id):
res = {: {: None, : None}, : None, : None, : None, : None}
for build in res[]:
record = store.hgnc_gene(hgnc_id, build=build)
if record:
record[] = "{this[chromosome]}:{this[start]}-{this[end]}".format(this=record)
res[] = record[]
... | Parse information about a gene. |
344,467 | def pairwise_align_sequences_to_representative(self, gapopen=10, gapextend=0.5, outdir=None,
engine=, parse=True, force_rerun=False):
if not self.representative_sequence:
raise ValueError(.format(self.id))
if not outdir:
... | Pairwise all sequences in the sequences attribute to the representative sequence. Stores the alignments
in the ``sequence_alignments`` DictList attribute.
Args:
gapopen (int): Only for ``engine='needle'`` - Gap open penalty is the score taken away when a gap is created
gapextend... |
344,468 | def get_prefix(self):
prefix = self.bucket
if self.prefix:
prefix += self.delimiter + self.prefix
return prefix | Full prefix: bucket + optional prefix |
344,469 | def set_incoming(self, value):
if not isinstance(value, list):
raise TypeError("IncomingList new value must be a list")
for element in value:
if not isinstance(element, str):
raise TypeError("IncomingList elements in variable must be of String class")
... | Setter for 'incoming' field.
:param value - a new value of 'incoming' field. List of IDs (String type) of incoming flows. |
344,470 | def _atol(self, atol):
max_tol = self.__class__.MAX_TOL
if atol < 0:
raise QiskitError("Invalid atol: must be non-negative.")
if atol > max_tol:
raise QiskitError(
"Invalid atol: must be less than {}.".format(max_tol))
se... | Set the absolute tolerence parameter for float comparisons. |
344,471 | def _build_static_validator(exact_value):
def static_validator(data):
if data == exact_value:
return data
raise NotValid( % (data, exact_value))
return static_validator | Build a validator that checks if the data is equal to an exact value. |
344,472 | def _init_transforms(self, subjs, voxels, features, random_state):
np.random.seed(self.rand_seed)
W = [random_state.random_sample((voxels[i], features))
for i in range(subjs)]
for i in range(subjs):
W[i], _ = np.linalg.qr(W[i])
... | Initialize the mappings (Wi) with random orthogonal matrices.
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
features : int
The number of features in the model.
... |
344,473 | def validate(message, gpg_home=None, **config):
if gpg_home is None:
raise ValueError("You must set the gpg_home keyword argument.")
try:
_ctx.verify(
fedmsg.encoding.dumps(message[]),
b64decode(message[]),
homedir=gpg_home
)
return True
... | Return true or false if the message is signed appropriately.
Two things must be true:
1) The signature must be valid (obviously)
2) The signing key must be in the local keyring
as defined by the `gpg_home` config value. |
344,474 | def cli(ctx, *args, **kwargs):
backend = kwargs.get(, None)
model = kwargs.get(, None)
printer = kwargs.get(, None)
debug = kwargs.get()
ctx.meta[] = model
ctx.meta[] = backend
ctx.meta[] = printer
logging.basicConfig(level= if debug else ) | Command line interface for the brother_ql Python package. |
344,475 | def subtopics(store, folders, folder_id, subfolder_id, ann_id=None):
items = folders.grouped_items(folder_id, subfolder_id, ann_id=ann_id)
fcs = dict([(cid, fc) for cid, fc in store.get_many(items.keys())])
for cid, subids in items.iteritems():
fc = ... | Yields an unordered generator of subtopics in a subfolder.
Each item of the generator is a 4-tuple of ``content_id``,
``subtopic_id``, ``subtopic_type`` and ``data``. Subtopic type
is one of the following Unicode strings: ``text``, ``image``
or ``manual``. The type of ``data`` is dependent on the
s... |
344,476 | def update_gl_state(self, *args, **kwargs):
if len(args) == 1:
self._vshare.gl_state[] = args[0]
elif len(args) != 0:
raise TypeError("Only one positional argument allowed.")
self._vshare.gl_state.update(kwargs) | Modify the set of GL state parameters to use when drawing
Parameters
----------
*args : tuple
Arguments.
**kwargs : dict
Keyword argments. |
344,477 | def get_bundle(self, href=None, embed_tracks=False,
embed_metadata=False, embed_insights=False):
assert href is not None
data = None
fields = {}
embed = helper.process_embed(embed_items=False,
embed_tracks=embed_... | Get a bundle.
'href' the relative href to the bundle. May not be None.
'embed_tracks' determines whether or not to include track
information in the response.
'embed_metadata' determines whether or not to include metadata
information in the response.
'embed_insights' dete... |
344,478 | def camel_to_snake(s: str) -> str:
return CAMEL_CASE_RE.sub(r, s).strip().lower() | Convert string from camel case to snake case. |
344,479 | def perpendicular_distance(p3, p1, p2):
px = p2[]-p1[]
py = p2[]-p1[]
squared_distance = px*px + py*py
if squared_distance == 0:
line_point = Point(p1[], p1[])
point = Point(p3[], p3[])
return line_point.dist_to(point)
u = ((p3[] - p1[])*px +... | Calculate the distance from p3 to the stroke defined by p1 and p2.
The distance is the length of the perpendicular from p3 on p1.
Parameters
----------
p1 : dictionary with "x" and "y"
start of stroke
p2 : dictionary with "x" and "y"
end of stroke
p3 : dictionary with "x" and "y... |
344,480 | def flag_time_err(phase_err, time_thresh=0.02):
time_err = []
for stamp in phase_err:
if abs(stamp[1]) > time_thresh:
time_err.append(stamp[0])
return time_err | Find large time errors in list.
Scan through a list of tuples of time stamps and phase errors
and return a list of time stamps with timing errors above a threshold.
.. note::
This becomes important for networks cross-correlations, where
if timing information is uncertain at one site, the r... |
344,481 | def popen(self, cmd):
process = Popen(cmd, shell=True, stdout=PIPE, env=self.env)
stdoutdata, stderrdata = process.communicate()
return process.returncode, stdoutdata | Execute an external command and return (rc, output). |
344,482 | def pre_save(self, instance, add: bool):
slugs = LocalizedValue()
for lang_code, value in self._get_populate_values(instance):
if not value:
continue
if self.include_time:
value += % datetime.now().microsecond
def is_uniqu... | Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or an update. |
344,483 | def inflate_nd_checker(identifier, definition):
if isinstance(definition, bool):
return Checker(name=identifier, passes=definition)
elif isinstance(definition, dict):
return Checker(definition.pop(, identifier), **definition)
else:
raise ValueError(
... | Inflate a no-data checker from a basic definition.
Args:
identifier (str): the no-data checker identifier / name.
definition (bool/dict): a boolean acting as "passes" or a full
dict definition with "passes" and "allow_failure".
Returns:
Checker: a ch... |
344,484 | def validate_and_convert_nexson(nexson, output_version, allow_invalid, **kwargs):
try:
if TRACE_FILES:
_write_to_next_free(, nexson)
annotation, validation_log, nexson_adaptor = ot_validate(nexson, **kwargs)
if TRACE_FILES:
_write_to_next_free(, annotation)
e... | Runs the nexson validator and returns a converted 4 object:
nexson, annotation, validation_log, nexson_adaptor
`nexson` is the nexson dict.
`output_version` is the version of nexson syntax to be used after validation.
if `allow_invalid` is False, and the nexson validation has errors, then
a... |
344,485 | def get_conversations(
self, continuation_token=None, custom_headers=None, raw=False, **operation_config):
url = self.get_conversations.metadata[]
query_parameters = {}
if continuation_token is not None:
query_parameters[] = self._serialize.que... | GetConversations.
List the Conversations in which this bot has participated.
GET from this method with a skip token
The return value is a ConversationsResult, which contains an array of
ConversationMembers and a skip token. If the skip token is not empty,
then
there are... |
344,486 | def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):
body = {
"action": action,
"subjectIdentifier": subject_id,
"resourceIdentifier": resource_id,
}
if policy_sets:
body[] = policy_sets
uri = self.uri ... | Evaluate a policy-set against a subject and resource.
example/
is_allowed('/user/j12y', 'GET', '/asset/12') |
344,487 | def proto_01_12_steps025(abf=exampleABF):
swhlab.ap.detect(abf)
standard_groupingForInj(abf,200)
for feature in [,]:
swhlab.ap.plot_values(abf,feature,continuous=False)
swhlab.plot.save(abf,tag=+feature)
swhlab.plot.gain(abf)
swhlab.plot.save(abf,tag=) | IC steps. Use to determine gain function. |
344,488 | def list_rooms(api_key=None):
**
if not api_key:
api_key = _get_api_key()
return salt.utils.slack.query(function=,
api_key=api_key,
opts=__opts__) | List all Slack rooms.
:param api_key: The Slack admin api key.
:return: The room list.
CLI Example:
.. code-block:: bash
salt '*' slack.list_rooms
salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 |
344,489 | def save_callback(operation, graphdef):
if operation == :
for e in graphdef.expressions:
if expression_ok(e):
graphdef.expression = e
display_graph(graphdef)
return
mestate.console.writeln(, fg=)
return
if operation == :
... | callback from save thread |
344,490 | def to_mongo(qry):
rev = False
if qry == "" or qry == []:
return {}
unpar = lambda s: s.strip().strip()
if isinstance(qry, str):
groups = []
if _TOK_OR in qry:
groups = [unpar(g).split(_TOK_AND) for g in qry.split(_TOK_OR)]
else:
... | Transform a simple query with one or more filter expressions
into a MongoDB query expression.
:param qry: Filter expression(s), see function docstring for details.
:type qry: str or list
:return: MongoDB query
:rtype: dict
:raises: BadExpression, if one of the input expressions cannot be parsed... |
344,491 | def send(self):
senderrecipientsresultexception
res = dict(sender=self.__sender, recipients=self.__recipients)
try:
s = _SMTP()
s.connect()
res.update(dict(
result=s.sendmail(self.__sender, self.__recipients, self.text)
))
... | :returns:
A dictionary with the following:
* 'sender': The `sender`
* 'recipients': All recipients, compiled from `to`, `cc` and `bcc`
* 'result': The :py:meth:`smtplib.SMTP.sendmail`-result
* 'exception': The exception message (if any)
.. note::
... |
344,492 | def draw(self, surface, rect, surfaces=None):
if self._zoom_level == 1.0:
self._render_map(surface, rect, surfaces)
else:
self._render_map(self._zoom_buffer, self._zoom_buffer.get_rect(), surfaces)
self.scaling_function(self._zoom_buffer, rect.size, surface)
... | Draw the map onto a surface
pass a rect that defines the draw area for:
drawing to an area smaller that the whole window/screen
surfaces may optionally be passed that will be blitted onto the surface.
this must be a sequence of tuples containing a layer number, image, and
r... |
344,493 | def _project_single_observable(self, **kwargs: Dict[str, Any]) -> Hist:
assert isinstance(self.output_attribute_name, str)
output_hist, projection_name, projection_name_args, = self._project_observable(
input_key = "single_observable",
input_observable... | Driver function for projecting and storing a single observable.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable`... |
344,494 | def street_address(self, address):
address = self.street_addresses([address])
if not len(address):
return None
return Address(address[0]) | Geocode one and only address, get a single Address object back
>>> client.street_address("100 Main St, Anywhere, USA")
>>> client.street_address({"street": "100 Main St, anywhere USA"})
:param address: string or dictionary with street address information
:return: an Address object or N... |
344,495 | def run(self):
import numpy as np
query = self.session.query(models.NUTS2Region.key,
models.NUTS2Region.id)
region_ids = self.client.df_query(query).set_index()[].to_dict()
data = next(self.requires()).load()
nuts = ... | Load climate data and convert to indicator objects |
344,496 | def run_build(build_dir, params, verbose=True):
download_repo(repo_url=params[],
destination=build_dir)
os.chdir(build_dir)
if params[] != None:
bot.info( %params[])
os.system( %(params[]))
else:
params[] = "master"
Client.debug = param... | run_build takes a build directory and params dictionary, and does the following:
- downloads repo to a temporary directory
- changes branch or commit, if needed
- creates and bootstraps singularity image from Singularity file
- returns a dictionary with:
image (path), metadata (dict)
... |
344,497 | def generate_thumbnail(self, ratio=None, width=None, height=None,
filter=, store=current_store,
_preprocess_image=None, _postprocess_image=None):
params = ratio, width, height
param_count = sum(p is not None for p in params)
if not p... | Resizes the :attr:`original` (scales up or down) and
then store the resized thumbnail into the ``store``.
:param ratio: resize by its ratio. if it's greater than 1
it scales up, and if it's less than 1 it scales
down. exclusive for ``width`` and ``height``
... |
344,498 | def stats_from_fai(infile):
f = utils.open_file_read(infile)
try:
lengths = sorted([int(line.split()[1]) for line in f], reverse=True)
except:
raise Error( + infile)
utils.close(f)
stats = {}
if len(lengths) > 0:
stats[] = max(lengths)
stats[] = min(lengths)... | Returns dictionary of length stats from an fai file. Keys are: longest, shortest, mean, total_length, N50, number |
344,499 | def add_project_name_arg(arg_parser, required, help_text):
arg_parser.add_argument("-p", ,
metavar=,
type=to_unicode,
dest=,
help=help_text,
required=required) | Adds project_name parameter to a parser.
:param arg_parser: ArgumentParser parser to add this argument to.
:param help_text: str label displayed in usage |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.