Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
15,700 | def logic(self, data):
try:
msg = Message(data, self)
msg.validate(self.protocol_version)
except (ValueError, vol.Invalid) as exc:
_LOGGER.warning(, exc)
return None
message_type = self.const.MessageType(msg.type)
handler = messag... | Parse the data and respond to it appropriately.
Response is returned to the caller and has to be sent
data as a mysensors command string. |
15,701 | def detectBlackBerry10Phone(self):
return UAgentInfo.deviceBB10 in self.__userAgent \
and UAgentInfo.mobile in self.__userAgent | Return detection of a Blackberry 10 OS phone
Detects if the current browser is a BlackBerry 10 OS phone.
Excludes the PlayBook. |
15,702 | def scroll(clicks, x=None, y=None, pause=None, _pause=True):
_failSafeCheck()
if type(x) in (tuple, list):
x, y = x[0], x[1]
x, y = position(x, y)
platformModule._scroll(clicks, x, y)
_autoPause(pause, _pause) | Performs a scroll of the mouse scroll wheel.
Whether this is a vertical or horizontal scroll depends on the underlying
operating system.
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the bo... |
15,703 | def rename(self, name):
sql = .format(
s=self.schema, t=self.name, name=name
)
self.engine.execute(sql)
self.table = SQLATable(name, self.metadata, schema=self.schema, autoload=True) | Rename the table |
15,704 | def get_next_second(intersection, intersections, to_end=True):
along_edge = None
index_second = intersection.index_second
t = intersection.t
for other_int in intersections:
other_t = other_int.t
if other_int.index_second == index_second and other_t > t:
if along_edge is ... | Gets the next node along the current (second) edge.
.. note::
This is a helper used only by :func:`get_next`, which in
turn is only used by :func:`basic_interior_combine`, which itself
is only used by :func:`combine_intersections`.
Along with :func:`get_next_first`, this function does th... |
15,705 | def BatchLabelVocabulary(self):
bsc = getToolByName(self, )
ret = []
for p in bsc(portal_type=,
is_active=True,
sort_on=):
ret.append((p.UID, p.Title))
return DisplayList(ret) | Return all batch labels as a display list |
15,706 | def cross_fade(self, seg1, seg2, duration):
if seg1.comp_location + seg1.duration - seg2.comp_location < 2:
dur = int(duration * seg1.track.samplerate)
if dur % 2 == 1:
dur -= 1
if dur / 2 > seg1.duration:
dur = seg1.duration * 2
... | Add a linear crossfade to the composition between two
segments.
:param seg1: First segment (fading out)
:type seg1: :py:class:`radiotool.composer.Segment`
:param seg2: Second segment (fading in)
:type seg2: :py:class:`radiotool.composer.Segment`
:param duration: Duration... |
15,707 | async def findTask(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["findTask"], *args, **kwargs) | Find Indexed Task
Find a task by index path, returning the highest-rank task with that path. If no
task exists for the given path, this API end-point will respond with a 404 status.
This method gives output: ``v1/indexed-task-response.json#``
This method is ``stable`` |
15,708 | def new_clustered_sortind(x, k=10, row_key=None, cluster_key=None):
try:
from sklearn.cluster import MiniBatchKMeans
except ImportError:
raise ImportError(
)
def _cluster_key(i):
return cluster_key(x[labels == i, :])
... | Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index that will sort the rows of `x` and a list of "breaks".
`b... |
15,709 | def _type_single(self, value, _type):
if value is None or _type in (None, NoneType):
pass
elif isinstance(value, _type):
value = dt2ts(value) if _type in [datetime, date] else value
else:
if _type in (datetime,... | apply type to the single value |
15,710 | def from_df(cls, path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:Optional[DataFrame]=None,
tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, text_cols:IntsOrStrs=1,
label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=6... | Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation. |
15,711 | def pathsplit(pth, dropext=True):
if dropext:
pth = os.path.splitext(pth)[0]
parts = os.path.split(pth)
if parts[0] == :
return parts[1:]
elif len(parts[0]) == 1:
return parts
else:
return pathsplit(parts[0], dropext=False) + parts[1:] | Split a path into a tuple of all of its components. |
15,712 | def sitetree_breadcrumbs(parser, token):
tokens = token.split_contents()
use_template = detect_clause(parser, , tokens)
tokens_num = len(tokens)
if tokens_num == 3:
tree_alias = parser.compile_filter(tokens[2])
return sitetree_breadcrumbsNode(tree_alias, use_template)
else:
... | Parses sitetree_breadcrumbs tag parameters.
Two notation types are possible:
1. Two arguments:
{% sitetree_breadcrumbs from "mytree" %}
Used to render breadcrumb path for "mytree" site tree.
2. Four arguments:
{% sitetree_breadcrumbs from "mytree" template "sitetre... |
15,713 | def name(self, name):
self._data[] = name
request = self._base_request
request[] = name
return self._tc_requests.update(request, owner=self.owner) | Updates the security labels name.
Args:
name: |
15,714 | def scale_0to1(image_in,
exclude_outliers_below=False,
exclude_outliers_above=False):
min_value = image_in.min()
max_value = image_in.max()
image = image_in.copy()
if exclude_outliers_below:
perctl = float(exclude_outliers_below)
image[image < np.... | Scale the two images to [0, 1] based on min/max from both.
Parameters
-----------
image_in : ndarray
Input image
exclude_outliers_{below,above} : float
Lower/upper limit, a value between 0 and 100.
Returns
-------
scaled_image : ndarray
clipped and/or scaled image |
15,715 | def get_similar_entries(context, number=5,
template=):
entry = context.get()
if not entry:
return {: template, : []}
vectors = EntryPublishedVectorBuilder()
entries = vectors.get_related(entry, number)
return {: template,
: entries} | Return similar entries. |
15,716 | def main():
plugin = Register()
if plugin.args.option == :
plugin.sqlserverlocks_handle()
else:
plugin.unknown("Unknown actions.") | Register your own mode and handle method here. |
15,717 | def inbox(self):
if not self.isme:
raise PyPumpException("You cans inboxes")
if self._inbox is None:
self._inbox = Inbox(self.links[], pypump=self._pump)
return self._inbox | :class:`Inbox feed <pypump.models.feed.Inbox>` with all
:class:`activities <pypump.models.activity.Activity>`
received by the person, can only be read if logged in as the owner.
Example:
>>> for activity in pump.me.inbox[:2]:
... print(activity.id)
...
... |
15,718 | def calc_sasa(dssp_df):
infodict = {: dssp_df.exposure_asa.sum(),
: dssp_df.exposure_rsa.mean(),
: len(dssp_df)}
return infodict | Calculation of SASA utilizing the DSSP program.
DSSP must be installed for biopython to properly call it.
Install using apt-get on Ubuntu
or from: http://swift.cmbi.ru.nl/gv/dssp/
Input: PDB or CIF structure file
Output: SASA (integer) of structure |
15,719 | def select_parser(self, request, parsers):
if not request.content_type:
return parsers[0], parsers[0].mimetype
mimetype = MimeType.parse(request.content_type)
for parser in parsers:
if mimetype.match(parser.mimetype):
return parser, mimetype
... | Selects the appropriated parser which matches to the request's content type.
:param request: The HTTP request.
:param parsers: The lists of parsers.
:return: The parser selected or none. |
15,720 | def list_models(
self, dataset, max_results=None, page_token=None, retry=DEFAULT_RETRY
):
if isinstance(dataset, str):
dataset = DatasetReference.from_string(
dataset, default_project=self.project
)
if not isinstance(dataset, (Dataset, Datase... | [Beta] List models in the dataset.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/models/list
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetReference`, \
... |
15,721 | def flush(self, timeout=None, callback=None):
client, scope = self._stack[-1]
if client is not None:
return client.flush(timeout=timeout, callback=callback) | Alias for self.client.flush |
15,722 | def pin_direction(self, pin):
if type(pin) is list:
return [self.pin_direction(p) for p in pin]
pin_id = self._pin_mapping.get(pin, None)
if pin_id:
return self._pin_direction(pin_id)
else:
raise KeyError( % pin) | Gets the `ahio.Direction` this pin was set to.
If you're developing a driver, implement _pin_direction(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.Direction` the pin is set to
@throw KeyError if pin isn't mapped. |
15,723 | def script_dir_plus_file(filename, pyobject, follow_symlinks=True):
return join(script_dir(pyobject, follow_symlinks), filename) | Get current script's directory and then append a filename
Args:
filename (str): Filename to append to directory path
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's direct... |
15,724 | def _do_spelling_suggestion(database, query, spelling_query):
if spelling_query:
if in spelling_query:
return .join([database.get_spelling_suggestion(term).decode() for term in spelling_query.split()])
else:
return database.get_spelling_suggestio... | Private method that returns a single spelling suggestion based on
`spelling_query` or `query`.
Required arguments:
`database` -- The database to check spelling against
`query` -- The query to check
`spelling_query` -- If not None, this will be checked instead of `que... |
15,725 | def _to_eng_tuple(number):
split = lambda x, p: (x.ljust(3 + neg, "0")[:p], x[p:].rstrip("0"))
mant, exp = to_scientific_tuple(number)
mant, neg = mant.replace(".", ""), mant.startswith("-")
new_mant = ".".join(filter(None, split(mant, 1 + (exp % 3) + neg)))
n... | Return tuple with mantissa and exponent of number formatted in engineering notation.
:param number: Number
:type number: integer or float
:rtype: tuple |
15,726 | def get_mon_map(service):
try:
mon_status = check_output([, , service,
, ])
if six.PY3:
mon_status = mon_status.decode()
try:
return json.loads(mon_status)
except ValueError as v:
log("Unable to parse mon_sta... | Returns the current monitor map.
:param service: six.string_types. The Ceph user name to run the command under
:return: json string. :raise: ValueError if the monmap fails to parse.
Also raises CalledProcessError if our ceph command fails |
15,727 | def get_attachment_info(self, attachment):
attachment_uid = api.get_uid(attachment)
attachment_file = attachment.getAttachmentFile()
attachment_type = attachment.getAttachmentType()
attachment_icon = attachment_file.icon
if callable(attachment_icon):
attach... | Returns a dictionary of attachment information |
15,728 | def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]:
return [" " * num + l for l in elems] | Indent an iterable. |
15,729 | def describe_cache_parameter_groups(name=None, conn=None, region=None, key=None, keyid=None,
profile=None):
return _describe_resource(name=name, name_param=,
res_type=, info_node=,
conn=conn, region=region, key=key,... | Return details about all (or just one) Elasticache cache clusters.
Example:
.. code-block:: bash
salt myminion boto3_elasticache.describe_cache_parameter_groups
salt myminion boto3_elasticache.describe_cache_parameter_groups myParameterGroup |
15,730 | def run_show_val(obj, name):
val = obj.debugger.settings[obj.name]
obj.msg("%s is %s." % (obj.name, obj.cmd.proc._saferepr(val),))
return False | Generic subcommand value display |
15,731 | def get_bpf_pointer(tcpdump_lines):
if conf.use_pypy:
return _legacy_bpf_pointer(tcpdump_lines)
size = int(tcpdump_lines[0])
bpf_insn_a = bpf_insn * size
bip = bpf_insn_a()
tcpdump_lines = tcpdump_lines[1:]
i = 0
for line in tcpdump_lines:
values = [int(v) fo... | Create a BPF Pointer for TCPDump filter |
15,732 | def join_path_prefix(path, pre_path=None):
if not path:
return path
if pre_path and not os.path.isabs(path):
return os.path.join(pre_path, path)
return path | If path set and not absolute, append it to pre path (if used)
:param path: path to append
:type path: str | None
:param pre_path: Base path to append to (default: None)
:type pre_path: None | str
:return: Path or appended path
:rtype: str | None |
15,733 | def assembleimage(patches, pmasks, gridids):
r
for d in range(patches[0].ndim):
groups = {}
for patch, pmask, gridid in zip(patches, pmasks, gridids):
groupid = gridid[1:]
if not groupid in groups:
groups[groupid] = []
... | r"""
Assemble an image from a number of patches, patch masks and their grid ids.
Parameters
----------
patches : sequence
Sequence of patches.
pmasks : sequence
Sequence of associated patch masks.
gridids
Sequence of associated... |
15,734 | def __read_byte_size(decl, attrs):
size = attrs.get(XML_AN_SIZE, 0)
decl.byte_size = int(size) / 8 | Using duck typing to set the size instead of in constructor |
15,735 | def cdd(d, k):
if not isinstance(k, list):
k = [k]
for i in k:
if i in d:
d.pop(i) | Conditionally delete key (or list of keys) 'k' from dict 'd' |
15,736 | def setup_graph(self):
graph_default_context = None
if self.execution_type == "single":
self.graph = tf.Graph()
graph_default_context = self.graph.as_default()
graph_default_context.__enter__()
self.global_model = None
... | Creates our Graph and figures out, which shared/global model to hook up to.
If we are in a global-model's setup procedure, we do not create
a new graph (return None as the context). We will instead use the already existing local replica graph
of the model.
Returns: None or the graph's a... |
15,737 | def get_all_subdomains(offset=None, count=None, min_sequence=None, db_path=None, zonefiles_dir=None):
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts[]
if zonefiles_dir is None:
zonefiles_dir = opts[]
db = ... | Static method for getting the list of all subdomains |
15,738 | def check_serial_port(name):
try:
cdc = next(serial.tools.list_ports.grep(name))
return cdc[0]
except StopIteration:
msg = "device {} not found. ".format(name)
msg += "available devices are: "
ports = list(serial.tools.list_ports.comports())
for p in ports:
... | returns valid COM Port. |
15,739 | def load_glb(self):
with open(self.path, ) as fd:
magic = fd.read(4)
if magic != GLTF_MAGIC_HEADER:
raise ValueError("{} has incorrect header {} != {}".format(self.path, magic, GLTF_MAGIC_HEADER))
version = struct.unpack(, fd.read(4))[0]... | Loads a binary gltf file |
15,740 | def load(args):
from datetime import datetime as dt
from jcvi.formats.fasta import Seq, SeqRecord
valid_id_attributes = ["ID", "Name", "Parent", "Alias", "Target"]
p = OptionParser(load.__doc__)
p.add_option("--parents", dest="parents", default="mRNA",
help="list of features ... | %prog load gff_file fasta_file [--options]
Parses the selected features out of GFF, with subfeatures concatenated.
For example, to get the CDS sequences, do this:
$ %prog load athaliana.gff athaliana.fa --parents mRNA --children CDS
To get 500bp upstream of a genes Transcription Start Site (TSS), do t... |
15,741 | def call_somatic(tumor_name, normal_name):
tumor_thresh, normal_thresh = 3.5, 3.5
new_headers = [,
(
)
% (int(tumor_thresh * 10), int(normal_thresh * 10))]
def _output_filter_line(line, indexes):
parts = line.split("\t")
if ... | Call SOMATIC variants from tumor/normal calls, adding REJECT filters and SOMATIC flag.
Works from stdin and writes to stdout, finding positions of tumor and normal samples.
Uses MuTect like somatic filter based on implementation in speedseq:
https://github.com/cc2qe/speedseq/blob/e6729aa2589eca4e3a946f398... |
15,742 | def declare_alias(self, name):
def decorator(f):
self._auto_register_function(f, name)
return f
return decorator | Insert a Python function into this Namespace with an
explicitly-given name, but detect its argument count automatically. |
15,743 | def point_distance_ellipsode(point1,point2):
a = 6378137
f = 1/298.25722
b = a - a*f
e = math.sqrt((a*a-b*b)/(a*a))
lon1 = point1[][0]
lat1 = point1[][1]
lon2 = point1[][0]
lat2 = point2[][1]
M = a*(1-e*e)*math.pow(1-math.pow(e*math.sin(number2radius(lat1)),2),-1.5)
N = a/(m... | calculate the distance between two points on the ellipsode based on point1
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
return distance |
15,744 | def _get(self, node, key):
node_type = self._get_node_type(node)
if node_type == NODE_TYPE_BLANK:
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH:
if not key:
return node[-1]
sub_node = self._decode_to_node(node[key[0... | get value inside a node
:param node: node in form of list, or BLANK_NODE
:param key: nibble list without terminator
:return:
BLANK_NODE if does not exist, otherwise value or hash |
15,745 | def _handle_codeblock(self, match):
from pygments.lexers import get_lexer_by_name
yield match.start(1), String , match.group(1)
yield match.start(2), String , match.group(2)
yield match.start(3), Text , match.group(3)
lexer = No... | match args: 1:backticks, 2:lang_name, 3:newline, 4:code, 5:backticks |
15,746 | def build_props(self):
props = {}
if self.filters:
props["filters"] = {}
for grp in self.filters:
props["filters"][grp] = [f.params for f in self.filters[grp]]
if self.charts:
props["charts"] = [c.params for c in self.charts]
... | Build the props dictionary. |
15,747 | def update(self):
if self.hasproxy():
sonarD = SonarData()
range = 0
data = self.proxy.getSonarData()
sonarD.range = data.range
sonarD.maxAngle = data.maxAngle
sonarD.minAngle = data.minAngle
sonarD.maxRange = data.max... | Updates LaserData. |
15,748 | def _readXput(self, fileCards, directory, session, spatial=False, spatialReferenceID=4236, replaceParamFile=None):
for card in self.projectCards:
if (card.name in fileCards) and self._noneOrNumValue(card.value) and fileCards[card.name]:
fileIO = fileCards[c... | GSSHAPY Project Read Files from File Method |
15,749 | def flat(self, obj, mask=0):
s = self.base
if self.leng and self.item > 0:
s += self.leng(obj) * self.item
if _getsizeof:
s = _getsizeof(obj, s)
if mask:
s = (s + mask) & ~mask
return s | Return the aligned flat size. |
15,750 | def _query_helper(self, by=None):
if by is None:
primary_keys = self.table.primary_key.columns.keys()
if len(primary_keys) > 1:
warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. "
"USING THE FIRST KEY %s." %
... | Internal helper for preparing queries. |
15,751 | def copyto(self, other):
if isinstance(other, Context):
return super(RowSparseNDArray, self).copyto(other)
elif isinstance(other, NDArray):
stype = other.stype
if stype in (, ):
return super(RowSparseNDArray, self).copyto(other)
el... | Copies the value of this array to another array.
If ``other`` is a ``NDArray`` or ``RowSparseNDArray`` object, then ``other.shape``
and ``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a context, a new ``RowSparseNDArray`` wi... |
15,752 | def _log_graphql_error(self, query, data):
if isinstance(query, bytes):
query = query.decode()
elif not isinstance(query, str):
query = bytes(query).decode()
data = self._fixup_graphql_error(data)
errors = data[]
sel... | Log a ``{"errors": [...]}`` GraphQL return and return itself.
:param query: the GraphQL query that triggered the result.
:type query: str
:param data: the decoded JSON object.
:type data: dict
:return: the input ``data``
:rtype: dict |
15,753 | def t_binaryValue(t):
r
else:
t.value = int(t.value[0:-1], 2)
return t | r'[+-]?[0-9]+[bB] |
15,754 | def analyze(problem, Y, X, M=10, print_to_console=False, seed=None):
if seed:
np.random.seed(seed)
D = problem[]
N = Y.size
if print_to_console:
print("Parameter First")
Si = ResultDict((k, [None] * D) for k in [])
Si[] = problem[]
for i in range(D):... | Performs the Random Balanced Design - Fourier Amplitude Sensitivity Test
(RBD-FAST) on model outputs.
Returns a dictionary with keys 'S1', where each entry is a list of
size D (the number of parameters) containing the indices in the same order
as the parameter file.
Parameters
--------... |
15,755 | def exponentialRDD(sc, mean, size, numPartitions=None, seed=None):
return callMLlibFunc("exponentialRDD", sc._jsc, float(mean), size, numPartitions, seed) | Generates an RDD comprised of i.i.d. samples from the Exponential
distribution with the input mean.
:param sc: SparkContext used to create the RDD.
:param mean: Mean, or 1 / lambda, for the Exponential distribution.
:param size: Size of the RDD.
:param numPartitions: Number of p... |
15,756 | def get_android_resources(self):
try:
return self.arsc["resources.arsc"]
except KeyError:
self.arsc["resources.arsc"] = ARSCParser(self.zip.read(
"resources.arsc"))
return self.arsc["resources.arsc"] | Return the :class:`ARSCParser` object which corresponds to the resources.arsc file
:rtype: :class:`ARSCParser` |
15,757 | def transpose(a, axes=None):
if isinstance(a, np.ndarray):
return np.transpose(a, axes)
elif isinstance(a, RemoteArray):
return a.transpose(*axes)
elif isinstance(a, Remote):
return _remote_to_array(a).transpose(*axes)
elif isinstance(a, DistArray):
if axes is None:
... | Returns a view of the array with axes transposed.
For a 1-D array, this has no effect.
For a 2-D array, this is the usual matrix transpose.
For an n-D array, if axes are given, their order indicates how the
axes are permuted
Args:
a (array_like): Input array.
axes (list of int, optiona... |
15,758 | def _ignore_sql(self, query):
return any([
re.search(pattern, query.get()) for pattern in QC_SETTINGS[]
]) | Check to see if we should ignore the sql query. |
15,759 | def get_minutes_description(self):
return self.get_segment_description(
self._expression_parts[1],
_("every minute"),
lambda s: s,
lambda s: _("every {0} minutes").format(s),
lambda s: _("minutes {0} through {1} past the hour"),
l... | Generates a description for only the MINUTE portion of the expression
Returns:
The MINUTE description |
15,760 | def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_blade_swbd(self, **kwargs):
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
output = ET.SubElement(logical_chassis_... | Auto Generated Code |
15,761 | def _expand_colspan_rowspan(self, rows):
all_texts = []
remainder = []
for tr in rows:
texts = []
next_remainder = []
index = 0
tds = self._parse_td(tr)
for td in tds:
... | Given a list of <tr>s, return a list of text rows.
Parameters
----------
rows : list of node-like
List of <tr>s
Returns
-------
list of list
Each returned row is a list of str text.
Notes
-----
Any cell with ``rowspan`` o... |
15,762 | def learn(self, bottomUpInput, enableInference=None):
return self.compute(bottomUpInput, enableLearn=True,
enableInference=enableInference) | TODO: document
:param bottomUpInput:
:param enableInference:
:return: |
15,763 | def delete(self, folder_id):
self.folder_id = folder_id
return self._mc_client._delete(url=self._build_path(folder_id)) | Delete a specific campaign folder, and mark all the campaigns in the
folder as ‘unfiled’.
:param folder_id: The unique id for the campaign folder.
:type folder_id: :py:class:`str` |
15,764 | def flipFlopFsm(self, fsmTable, *varBinds, **context):
count = [0]
cbFun = context.get()
def _cbFun(varBind, **context):
idx = context.pop(, None)
err = context.pop(, None)
if err:
errors = context[]
... | Read, modify, create or remove Managed Objects Instances.
Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType`, recursively
transitions corresponding Managed Objects Instances through the Finite State
Machine (FSM) states till it reaches its final stop state.
Parameters
... |
15,765 | def get_arguments(self):
ApiCli.get_arguments(self)
if self.args.hostGroupId is not None:
self.hostGroupId = self.args.hostGroupId
if self.args.force is not None:
self.force = self.args.force
if self.force:
self.url_parameters = {"forceRemove... | Extracts the specific arguments of this CLI |
15,766 | def __msgc_step3_discontinuity_localization(self):
import scipy
start = self._start_time
seg = 1 - self.segmentation.astype(np.int8)
self.stats["low level object voxels"] = np.sum(seg)
self.stats["low level image voxels"] = np.prod(seg.shape)
... | Estimate discontinuity in basis of low resolution image segmentation.
:return: discontinuity in low resolution |
15,767 | def full_parent_name(self):
entries = []
command = self
while command.parent is not None:
command = command.parent
entries.append(command.name)
return .join(reversed(entries)) | Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``?one two three`` the parent name would be ``one two``. |
15,768 | def area(self):
area = abs(self.primitive.height *
self.primitive.polygon.length)
area += self.primitive.polygon.area * 2
return area | The surface area of the primitive extrusion.
Calculated from polygon and height to avoid mesh creation.
Returns
----------
area: float, surface area of 3D extrusion |
15,769 | def colorize(text, messageType=None):
formattedText = str(text)
if "ERROR" in messageType:
formattedText = colorama.Fore.RED + formattedText
elif "WARNING" in messageType:
formattedText = colorama.Fore.YELLOW + formattedText
elif "SUCCESS" in messageType:
formattedText ... | Function that colorizes a message.
Args:
-----
text: The string to be colorized.
messageType: Possible options include "ERROR", "WARNING", "SUCCESS",
"INFO" or "BOLD".
Returns:
--------
string: Colorized if the option is correct, including a tag at the end
... |
15,770 | def url_for(self, *args, **kwargs):
return yarl.URL(self.url(parts=kwargs)) | Construct url for route with additional params. |
15,771 | def format_cffi_externs(cls):
extern_decls = [
f.extern_signature.pretty_print()
for _, f in cls._extern_fields.items()
]
return (
+ .join(extern_decls)
+ ) | Generate stubs for the cffi bindings from @_extern_decl methods. |
15,772 | def undefine(vm_, **kwargs):
*
conn = __get_conn(**kwargs)
dom = _get_domain(conn, vm_)
if getattr(libvirt, , False):
ret = dom.undefineFlags(libvirt.VIR_DOMAIN_UNDEFINE_NVRAM) == 0
else:
ret = dom.undefine() == 0
conn.close()
return ret | Remove a defined vm, this does not purge the virtual machine image, and
this only works if the vm is powered down
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... |
15,773 | def std(a, axis=None, ddof=0):
axes = _normalise_axis(axis, a)
if axes is None or len(axes) != 1:
msg = "This operation is currently limited to a single axis"
raise AxisSupportError(msg)
dtype = (np.array([0], dtype=a.dtype) / 1.).dtype
return _Aggregation(a, axes[0],
... | Request the standard deviation of an Array over any number of axes.
.. note:: Currently limited to operating on a single axis.
:param axis: Axis or axes along which the operation is performed.
The default (axis=None) is to perform the operation
over all the dimensions of the ... |
15,774 | def lazy_connect(cls, pk):
instance = cls()
instance._pk = instance.pk.normalize(pk)
instance._connected = False
return instance | Create an object, setting its primary key without testing it. So the
instance is not connected |
15,775 | def __perform_request(self, url, type=GET, params=None):
if params is None:
params = {}
if not self.token:
raise TokenError("No token provided. Please use a valid token")
url = urlparse.urljoin(self.end_point, url)
identity = lambda x... | This method will perform the real request,
in this way we can customize only the "output" of the API call by
using self.__call_api method.
This method will return the request object. |
15,776 | def update_energy(self, bypass_check: bool = False):
if bypass_check or (not bypass_check and self.update_time_check):
self.get_weekly_energy()
if in self.energy:
self.get_monthly_energy()
self.get_yearly_energy()
if not bypass_check:... | Builds weekly, monthly and yearly dictionaries |
15,777 | def parse_comet(self):
import re
pat = ( +
+
( +
)
)
m = re.findall(pat, self.targetname.strip())
prefixnumber = None
desig = None
name = None
if len(m) > 0:
... | Parse `targetname` as if it were a comet.
:return: (string or None, int or None, string or None);
The designation, number and prefix, and name of the comet as derived
from `self.targetname` are extracted into a tuple; each element that
does not exist is set to `None`. Parenthesis ... |
15,778 | def _process_book(book_url):
data = DOWNER.download(book_url)
dom = dhtmlparser.parseString(data)
details_tags = dom.find("div", {"id": "contentDetail"})
assert details_tags, "Can't find details of the book."
details = details_tags[0]
title = _parse_title(dom, details)
authors ... | Parse available informations about book from the book details page.
Args:
book_url (str): Absolute URL of the book.
Returns:
obj: :class:`structures.Publication` instance with book details. |
15,779 | def _get_real_ip(self):
try:
real_ip = self.request.META[]
return real_ip.split()[0]
except KeyError:
return self.request.META[]
except Exception:
return None | Get IP from request.
:param request: A usual request object
:type request: HttpRequest
:return: ipv4 string or None |
15,780 | def cli(env, limit, closed=False, get_all=False):
manager = AccountManager(env.client)
invoices = manager.get_invoices(limit, closed, get_all)
table = formatting.Table([
"Id", "Created", "Type", "Status", "Starting Balance", "Ending Balance", "Invoice Amount", "Items"
])
table.align[]... | Invoices and all that mess |
15,781 | def delete(self, records, context):
DELETE = self.statement()
sql, data = DELETE(records, context)
if context.dryRun:
print sql % data
return 0
else:
return self.execute(sql, data, writeAccess=True) | Removes the inputted record from the database.
:param records | <orb.Collection>
context | <orb.Context>
:return <int> number of rows removed |
15,782 | def add_criterion(self, name, priority, and_or, search_type, value):
criterion = SearchCriteria(name, priority, and_or, search_type, value)
self.criteria.append(criterion) | Add a search criteria object to a smart group.
Args:
name: String Criteria type name (e.g. "Application Title")
priority: Int or Str number priority of criterion.
and_or: Str, either "and" or "or".
search_type: String Criteria search type. (e.g. "is", "is
... |
15,783 | def _set_pfiles(dry_run, **kwargs):
pfiles_orig = os.environ[]
pfiles = kwargs.get(, None)
if pfiles:
if dry_run:
print("mkdir %s" % pfiles)
else:
try:
os.makedirs(pfiles)
except OSError:
pass
pfiles = "%s:%s" %... | Set the PFILES env var
Parameters
----------
dry_run : bool
Don't actually run
Keyword arguments
-----------------
pfiles : str
Value to set PFILES
Returns
-------
pfiles_orig : str
Current value of PFILES envar |
15,784 | def ppf(q, df, loc=0.0, scale=1.0, gamma = 1.0):
result = np.zeros(q.shape[0])
probzero = Skewt.cdf(x=np.zeros(1),loc=np.zeros(1),df=df,gamma=gamma)
result[q<probzero] = 1.0/gamma*ss.t.ppf(((np.power(gamma,2) + 1.0) * q[q<probzero])/2.0,df)
result[q>=probzero] = gamma*ss.t.ppf((... | PPF function for Skew t distribution |
15,785 | def get_profiles(self):
out = set(x.profile for x in self.requires if x.profile)
out.update(x.profile for x in self.removes if x.profile)
return out | Returns set of profile names referenced in this Feature
:returns: set of profile names |
15,786 | def sign_transaction(self, signer: Account):
tx_hash = self.hash256()
sig_data = signer.generate_signature(tx_hash)
sig = [Sig([signer.get_public_key_bytes()], 1, [sig_data])]
self.sig_list = sig | This interface is used to sign the transaction.
:param signer: an Account object which will sign the transaction.
:return: a Transaction object which has been signed. |
15,787 | def set_state(self, state):
self.index_x.set(state[REG_X])
self.index_y.set(state[REG_Y])
self.user_stack_pointer.set(state[REG_U])
self.system_stack_pointer.set(state[REG_S])
self.program_counter.set(state[REG_PC])
self.accu_a.set(state[REG_A])
self.a... | used in unittests |
15,788 | def doNew(self, WHAT={}, **params):
if hasattr(WHAT, ):
for key in WHAT:
if key not in [,]:
if WHAT.__new2old__.has_key(key):
self._addDBParam(WHAT.__new2old__[key].encode(), WHAT[key])
else:
self._addDBParam(key, WHAT[key])
elif type(WHAT)==dict:
for key in WHAT:
self._addDB... | This function will perform the command -new. |
15,789 | def notify(self, subsystem, recipient, subject, body_html, body_text):
if not re.match(self.validation, recipient, re.I):
raise ValueError()
if recipient.startswith():
target_type =
elif recipient.find() != -1:
target_type =
else:
... | You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notification
recipient (`str`): Recipient
subject (`str`): Subjec... |
15,790 | def save(self, file, contents, name=None, overwrite=False):
if name is None:
name = self.format_from_extension(op.splitext(file)[1])
file_format = self.file_type(name)
if file_format == :
_write_text(file, contents)
elif file_format == :
_writ... | Save contents into a file. The format name can be specified
explicitly or inferred from the file extension. |
15,791 | def find_one(driver, locator_list, elem_type=CSS, timeout=TIMEOUT):
def _find_one(driver):
finders = {
CLASS_NAME: driver.find_elements_by_class_name,
CSS: driver.find_elements_by_css_selector,
ID: driver.find_elements_by_id,
LINK: driver.find_el... | Args:
driver (selenium webdriver): Selenium webdriver object
locator_list (:obj: `list` of :obj: `str`): List of CSS selector strings
elem_type (Selenium By types): Selenium By type (i.e. By.CSS_SELECTOR)
timeout (int): Number of seconds to wait before timing out
Returns:
Se... |
15,792 | def com_google_fonts_check_metadata_match_filename_postscript(font_metadata):
post_script_name = font_metadata.post_script_name
filename = os.path.splitext(font_metadata.filename)[0]
if filename != post_script_name:
yield FAIL, ("METADATA.pb font filename=\"{}\" does not match"
" post_scr... | METADATA.pb font.filename and font.post_script_name
fields have equivalent values? |
15,793 | def images(self, type):
images = []
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
images = res.json
try:
if type in ["qemu", "dynamips", "iou"]:
for local_image in list_images(type):
if local_im... | Return the list of images available for this type on controller
and on the compute node. |
15,794 | def read_header(filename):
header = {}
in_header = False
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split()]
for line in lines:
if line=="*** Header Start ***":
in_header=True
continue
if line=="*** Header End ***":
re... | returns a dictionary of values in the header of the given file |
15,795 | def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
secexp = self.privkey.secret_multiplier
k = rfc6979.generate_k(
self.curve.generator.order(), secexp, hashfunc, digest)
return self.sign_digest(digest, sigencode=sigencode, k=k) | Calculates 'k' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details. |
15,796 | def is_close_to(self, other, tolerance):
self._validate_close_to_args(self.val, other, tolerance)
if self.val < (other-tolerance) or self.val > (other+tolerance):
if type(self.val) is datetime.datetime:
tolerance_seconds = tolerance.days * 86400 + tolerance.seconds ... | Asserts that val is numeric and is close to other within tolerance. |
15,797 | def read_gtfs(path: Path, dist_units: str) -> "Feed":
path = Path(path)
if not path.exists():
raise ValueError(f"Path {path} does not exist")
if path.is_file():
zipped = True
tmp_dir = tempfile.TemporaryDirectory()
src_path = Path(tmp_dir.name)
shutil.unpac... | Create a Feed instance from the given path and given distance units.
The path should be a directory containing GTFS text files or a
zip file that unzips as a collection of GTFS text files
(and not as a directory containing GTFS text files).
The distance units given must lie in :const:`constants.dist_uni... |
15,798 | def AgregarDatoPDF(self, campo, valor, pagina=):
"Agrego un dato a la factura (internamente)"
if campo == and valor.startswith(self.InstallDir):
if not os.path.exists(valor):
valor = os.path.join(self.InstallDir, "plantillas", os.path.basename(valor))
if... | Agrego un dato a la factura (internamente) |
15,799 | def exclude_reference_link(self, exclude):
if not isinstance(exclude, bool):
raise InvalidUsage()
self._sysparms[] = exclude | Sets `sysparm_exclude_reference_link` to a bool value
:param exclude: bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.