Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,800 | def try_mongodb_opts(self, host="localhost", database_name=):
try:
mongo_client = MongoClient(host=host)
except Exception as e:
self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e)))
return None
try:
database =... | Try MongoDB configuration |
346,801 | def record(session_file, shell, prompt, alias, envvar):
if os.path.exists(session_file):
click.confirm(
.format(session_file),
abort=True,
default=False,
)
secho("We'll do it live!", fg="red", bold=True)
filename = click.format_filename(session_file)... | Record a session file. If no argument is passed, commands are written to
./session.sh.
When you are finished recording, run the "stop" command. |
346,802 | def compress(obj, level=6, return_type="bytes"):
if isinstance(obj, binary_type):
b = _compress_bytes(obj, level)
elif isinstance(obj, string_types):
b = _compress_str(obj, level)
else:
b = _compress_obj(obj, level)
if return_type == "bytes":
return b
elif retur... | Compress anything to bytes or string.
:param obj: could be any object, usually it could be binary, string, or
regular python objec.t
:param level:
:param return_type: if bytes, then return bytes; if str, then return
base64.b64encode bytes in utf-8 string. |
346,803 | def inputs_valid(self, outputs=None):
if self.operation == Transaction.CREATE:
return self._inputs_valid([
for _ in self.inputs])
elif self.operation == Transaction.TRANSFER:
return self._input... | Validates the Inputs in the Transaction against given
Outputs.
Note:
Given a `CREATE` Transaction is passed,
dummy values for Outputs are submitted for validation that
evaluate parts of the validation-checks to `True`.
Args:
... |
346,804 | def _get_key_for_index(self, indexedField, val):
t let it down.
@param indexedField - string of field name
@param val - Value of field
@return - Key name string, potentially hashed.
toIndex:idx::', val] ) | _get_key_for_index - Returns the key name that would hold the indexes on a value
Internal - does not validate that indexedFields is actually indexed. Trusts you. Don't let it down.
@param indexedField - string of field name
@param val - Value of field
@return - Key name string, potentially hashed. |
346,805 | def index_record(self, json_path):
self.logger.debug(, json_path)
json_path = os.path.abspath(json_path)
self.check_path(json_path, )
with open(json_path) as fp:
try:
dct = json.load(fp)
except ValueError:
warnings.warn(
... | Import `json_path` and remove it if :attr:`keep_json` is false. |
346,806 | def update_context(app, pagename, templatename, context, doctree):
context[] = feedback_form_url(app.config.project, pagename) | Update the page rendering context to include ``feedback_form_url``. |
346,807 | def init( self, lang=, css=None, metainfo=None, title=None, header=None,
footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None, base=None ):
self._full = True
if self.mode == or self.mode == :
if doctype is None:
doctype... | This method is used for complete documents with appropriate
doctype, encoding, title, etc information. For an HTML/XML snippet
omit this method.
lang -- language, usually a two character string, will appear
as <html lang='en'> in html mode (ignored in xml mode)
... |
346,808 | def plot(self, vertex_color=None, vertex_size=None, highlight=[],
edges=None, edge_color=None, edge_width=None,
indices=False, colorbar=True, limits=None, ax=None,
title=None, backend=None):
r
from pygsp.plotting import _plot_graph
return _plot_graph(self, ... | r"""Docstring overloaded at import time. |
346,809 | def create_qrcode(self, qrcode_data):
result = self._post(
,
data=qrcode_data,
result_processor=lambda x: x[]
)
return result | 创建卡券二维码
:param qrcode_data: 二维码信息
:return: 二维码 ticket,可使用 :func:show_qrcode 换取二维码文件 |
346,810 | def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5):
modFlags = 0
self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
dest_coord=dest_coord)
self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
... | Double-click and drag the left mouse button without modifiers
pressed.
Parameters: coordinates to double-click on screen (tuple (x, y))
dest coordinates to drag to (tuple (x, y))
interval to send event of btn down, drag and up
Returns: None |
346,811 | async def create_checkpoint_if_not_exists_async(self, partition_id):
checkpoint = await self.get_checkpoint_async(partition_id)
if not checkpoint:
await self.create_lease_if_not_exists_async(partition_id)
checkpoint = Checkpoint(partition_id)
return checkpoint | Create the given partition checkpoint if it doesn't exist.Do nothing if it does exist.
The offset/sequenceNumber for a freshly-created checkpoint should be set to StartOfStream/0.
:param partition_id: The partition ID.
:type partition_id: str
:return: The checkpoint for the given partit... |
346,812 | def size(self, key, resource_type):
with self._objects_queue_lock:
return len(self._objects_queue[key].get(resource_type, [])) | Return the size of the queue for a given key and resource type.
If the key is not in the cache, this will raise a KeyError. |
346,813 | def time_multi_coincidence(times, slide_step=0, slop=.003,
pivot=, fixed=):
def win(ifo1, ifo2):
d1 = Detector(ifo1)
d2 = Detector(ifo2)
return d1.light_travel_time_to_detector(d2) + slop
pivot_id, fix_id, slide = time_coincidence(times[piv... | Find multi detector concidences.
Parameters
----------
times: dict of numpy.ndarrays
Dictionary keyed by ifo of the times of each single detector trigger.
slide_step: float
The interval between time slides
slop: float
The amount of time to add to the TOF between detectors fo... |
346,814 | def distribution_files(self) -> Iterator[str]:
if self.distribution.packages:
package_dirs = self.distribution.package_dir or {}
for package in self.distribution.packages:
pkg_dir = package
if package in package_dirs:
... | Find distribution packages. |
346,815 | def perform_step(file_contents, step):
assert type(file_contents) is not bytes
xmldoc = parse(file_contents)
return step(xmldoc) | Performs a step of the transformation.
:param text file_contents: Contends of the cheetah template
:param function step: Function taking xmldoc and returning new contents
:returns: new contents of the file. |
346,816 | def get_path_attribute(obj, path):
path = path.replace(, ).replace(, )
attr_parts = path.split()
res = obj
try:
for part in attr_parts:
try:
res = getattr(res, part)
except AttributeError:
... | Given a path like `related_record.related_record2.id`, this method
will be able to pull the value of ID from that object, returning None
if it doesn't exist.
Args:
obj (fleaker.db.Model):
The object to attempt to pull the value from
path (str):
... |
346,817 | def _display_objects(obj_type, object_repo, namespace, cmt_begin, cmt_end,
dest=None, summary=None, output_format=None):
if namespace in object_repo:
if obj_type == :
_uprint(dest,
_format(u"{0}Namespace {1!A}: conta... | Display a set of objects of obj_type from the dictionary defined
by the parameter object_repo. obj_type is a string that defines the
type of object ('Classes', 'Instances', 'Qualifier Declarations',
'Methods'). |
346,818 | def main():
message_names = set()
packages = []
messages = []
extensions = []
constants = []
for info in extract_message_info():
message_names.add(info.title)
packages.append(
.format(
BASE_PACKAGE, info.module))
messages.append(
... | Script starts somewhere around here. |
346,819 | def setup_queue(self, queue_name):
logger.info(, name=queue_name)
self._channel.queue_declare(
self.on_queue_declareok, queue_name, durable=self._durable_queue
) | Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
command. When it is complete, the on_queue_declareok method will
be invoked by pika.
:param str|unicode queue_name: The name of the queue to declare. |
346,820 | def vm_state(vm_=None):
*
with _get_xapi_session() as xapi:
info = {}
if vm_:
info[vm_] = _get_record_by_label(xapi, , vm_)[]
return info
for vm_ in list_domains():
info[vm_] = _get_record_by_label(xapi, , vm_)[]
return info | Return list of all the vms and their state.
If you pass a VM name in as an argument then it will return info
for just the named VM, otherwise it will return all VMs.
CLI Example:
.. code-block:: bash
salt '*' virt.vm_state <vm name> |
346,821 | def _trigger(self, obj, old, value, hint=None, setter=None):
if hasattr(obj, ):
obj.trigger(self.name, old, value, hint, setter) | Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
new (obj) :
The new value of the property
... |
346,822 | def get_password(self, description=, confirm=False, clear=False):
if os.path.exists(self.password_file) and not clear:
logger.info("Read password from file {}".format(self.password_file))
password = self.load_password()
else:
... | Get the password from a Glances client or server.
For Glances server, get the password (confirm=True, clear=False):
1) from the password file (if it exists)
2) from the CLI
Optionally: save the password to a file (hashed with salt + SHA-256)
For Glances client, get the ... |
346,823 | def autoload_static(model, resources, script_path):
if isinstance(model, Model):
models = [model]
elif isinstance (model, Document):
models = model.roots
else:
raise ValueError("autoload_static expects a single Model or Document")
with OutputDocumentFor(models):
... | Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
Jav... |
346,824 | def retain_error(self, error, frame=None):
if frame is None:
stack = traceback.format_exc()
self.labels.add("@iopipe/error")
else:
stack = "\n".join(traceback.format_stack(frame))
self.labels.add("@iopipe/timeout")
details = {
... | Adds details of an error to the report.
:param error: The error exception to add to the report. |
346,825 | def synctree(src, dst, onexist=None):
src = pathlib.Path(src).resolve()
dst = pathlib.Path(dst).resolve()
if not src.is_dir():
raise ValueError
if dst.exists() and not dst.is_dir():
raise ValueError
if onexist is None:
def onexist(): pass
_synctree(src, dst, onex... | Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source di... |
346,826 | def archive(self, request, id):
gist = self.send(request, id).json()
with tarfile.open(.format(id), mode=) as archive:
for name, data in gist[].items():
with tempfile.NamedTemporaryFile() as fp:
fp.write(data[])
fp.flush()
... | Create an archive of a gist
The files in the gist are downloaded and added to a compressed archive
(tarball). If the ID of the gist was c78d925546e964b4b1df, the
resulting archive would be,
c78d925546e964b4b1df.tar.gz
The archive is created in the directory where the comma... |
346,827 | def isalive (self):
if self.child_fd == -1:
return False
try:
os.fstat(self.child_fd)
return True
except:
return False | This checks if the file descriptor is still valid. If :func:`os.fstat`
does not raise an exception then we assume it is alive. |
346,828 | def _expect(self, expected, times=50):
print % (self.port, expected)
retry_times = 10
while times > 0 and retry_times > 0:
line = self._readline()
print % (self.port, line)
if line == expected:
print % (self.port, expected)
... | Find the `expected` line within `times` trials.
Args:
expected str: the expected string
times int: number of trials |
346,829 | def is_vocalized(word):
if word.isalpha():
return False
for char in word:
if is_tashkeel(char):
return True
else:
return False | Checks if the arabic word is vocalized.
the word musn't have any spaces and pounctuations.
@param word: arabic unicode char
@type word: unicode
@return: if the word is vocalized
@rtype:Boolean |
346,830 | def from_tasks(cls, tasks):
endpoints = [
[
MarathonEndpoint(task.app_id, task.service_ports[
port_index], task.host, task.id, port)
for port_index, port in enumerate(task.ports)
]
for task in tasks
... | Construct a list of MarathonEndpoints from a list of tasks.
:param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse
:rtype: list[:class:`MarathonEndpoint`] |
346,831 | def get_template(self, name):
filename = path.join(self.search_path, *[p for p in name.split()
if p and p[0] != ])
if not path.exists(filename):
raise TemplateNotFound(name)
return Template.from_file(filename, self.encoding) | Get a template from a given name. |
346,832 | def _set_traffic_class_exp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("traffic_class_exp_map_name",traffic_class_exp.traffic_class_exp, yang_name="traffic-class-exp", rest_name="traffic-class-exp", parent=self, is_container=, user_or... | Setter method for traffic_class_exp, mapped from YANG variable /qos_mpls/map/traffic_class_exp (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_traffic_class_exp is considered as a private
method. Backends looking to populate this variable should
do so via calling ... |
346,833 | def genes_by_alias(hgnc_genes):
alias_genes = {}
for hgnc_id in hgnc_genes:
gene = hgnc_genes[hgnc_id]
hgnc_symbol = gene[]
for alias in gene[]:
true_id = None
if alias == hgnc_symbol:
true_id = hgnc_id
if alias in alias_... | Return a dictionary with hgnc symbols as keys
Value of the dictionaries are information about the hgnc ids for a symbol.
If the symbol is primary for a gene then 'true_id' will exist.
A list of hgnc ids that the symbol points to is in ids.
Args:
hgnc_genes(dict): a dictionary with hgnc_id as k... |
346,834 | def is_processing(self, taskid):
return taskid in self.processing and self.processing[taskid].taskid | return True if taskid is in processing |
346,835 | def _get_client(self):
client_kwargs = self._storage_parameters.get(, dict())
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs[] = False
return self._get_session().client("s3", **client_kwargs) | S3 Boto3 client
Returns:
boto3.session.Session.client: client |
346,836 | def match_files(files, pattern: Pattern):
for name in files:
if re.match(pattern, name):
yield name | Yields file name if matches a regular expression pattern. |
346,837 | def close(correlation_id, components):
if components == None:
return
for component in components:
Closer.close_one(correlation_id, component) | Closes multiple components.
To be closed components must implement [[ICloseable]] interface.
If they don't the call to this method has no effect.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param components: the list of components that are ... |
346,838 | def _GetDateValuesWithEpoch(self, number_of_days, date_time_epoch):
return self._GetDateValues(
number_of_days, date_time_epoch.year, date_time_epoch.month,
date_time_epoch.day_of_month) | Determines date values.
Args:
number_of_days (int): number of days since epoch.
date_time_epoch (DateTimeEpoch): date and time of the epoch.
Returns:
tuple[int, int, int]: year, month, day of month. |
346,839 | def _map_center(self, coord, val):
if self.ppd in [4, 8, 16, 32, 64]:
res = {: 0, : 360}
return res[coord] / 2.0
elif self.ppd in [128]:
res = {: 90, : 90}
return (val // res[coord] + 1) * res[coord] - res[coord] / 2.0
elif self.ppd in [2... | Identitify the center of the Image correspond to one coordinate. |
346,840 | def process_amendments(congress):
amend_dir = "{0}/{1}/amendments".format(congress[],
congress[])
logger.info("Processing Amendments for {0}".format(congress[]))
amendments = []
for root, dirs, files in os.walk(amend_dir):
if "data.json" in file... | Traverse amendments for a project |
346,841 | def findPreviousItem(self, item):
if not item:
return None
while item.parent():
index = item.parent().indexOfChild(item)
if index == 0:
return item.parent()
child = item.parent().child(index-1)
... | Returns the previous item in the tree.
:param item | <QtGui.QTreeWidgetItem>
:return <QtGui.QTreeWidgetItem> || None |
346,842 | def get_property(self, name):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
value = self._call("getProperty",
in_p=[name])
return value | Returns the value of the custom medium property with the given name.
The list of all properties supported by the given medium format can
be obtained with :py:func:`IMediumFormat.describe_properties` .
If this method returns an empty string in @a value, the requested
pro... |
346,843 | def activate_widget(self, package):
cmd, url = DEVICE_URLS["activate_widget"]
widget_id = self._get_widget_id(package)
url = url.format(, package, widget_id)
self.result = self._exec(cmd, url) | activate the widget of the given package
:param str package: name of the package |
346,844 | def normalize_url(url: str) -> str:
if url.startswith():
url = url[1:]
if url.endswith():
url = url[:-1]
return url | Remove leading and trailing slashes from a URL
:param url: URL
:return: URL with no leading and trailing slashes
:private: |
346,845 | def export(outfile):
if not nav:
sys.exit(1)
ecode = 0
savelist = list()
for imageId in imagelist:
try:
record = {}
record[] = {}
record[][] = imageId
record[][] = contexts[].load_image_new(imageId)
savelist.app... | Export image anchore data to a JSON file. |
346,846 | def coltype_as_typeengine(coltype: Union[VisitableType,
TypeEngine]) -> TypeEngine:
if isinstance(coltype, TypeEngine):
return coltype
return coltype() | Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as such instances, or as the
class type. This function ensures that such classes are converted to
instances.
To explain: you can specify columns like
.. code-block:: python
... |
346,847 | def load(cls, data):
if len(data) == 1:
for key, value in data.items():
if "__classname__" not in value:
raise ValueError
name = key
bases = (Constant,)
attrs = dict()
for k, v in value.ite... | Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2 |
346,848 | def render_to_string(self, template, context=None, def_name=None, subdir=):
template_adapter = self.get_template_loader(subdir).get_template(template)
return getattr(template_adapter, )(context=context, request=self.request, def_name=def_name) | App-specific render function that renders templates in the *current app*, attached to the request for convenience |
346,849 | def child_count(self, path):
stat = self.stat(path)
if not stat:
return 0
count = stat.numChildren
for _, _, stat in self.tree(path, 0, include_stat=True):
if stat:
count += stat.numChildren
return count | returns the child count under path (deals with znodes going away as it's
traversing the tree). |
346,850 | def _update_trial_queue(self, blocking=False, timeout=600):
trials = self._search_alg.next_trials()
if blocking and not trials:
start = time.time()
while (not trials and not self.is_finished()
and time.time() - st... | Adds next trials to queue if possible.
Note that the timeout is currently unexposed to the user.
Args:
blocking (bool): Blocks until either a trial is available
or is_finished (timeout or search algorithm finishes).
timeout (int): Seconds before blocking times o... |
346,851 | def make_ensemble_list(molecules, score_field, ensemble_size):
queryList = molecules[0].scores.keys()
ensemble_iterator = itertools.combinations(queryList, ensemble_size)
ensembleList = []
for ensemble in ensemble_iterator:
ensembleList.append(ensemble)
return ensemb... | Construct ensemble list |
346,852 | def eliminate_sequential_children(paths):
"helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path"
return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-1]))] | helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path |
346,853 | def main(arguments=None):
dev_flag = False
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="DEBUG",
options_first=False,
projectName="rockAtlas"
)
arguments, settings, log, dbConn = su.setup()
for arg, val in arguments.iteri... | *The main function used when ``cl_utils.py`` is run as a single script from the cl, or when installed as a cl command* |
346,854 | def pre_dissect(self, s):
length = len(s)
if length < _NTP_PACKET_MIN_SIZE:
err = " ({}".format(length) + " is < _NTP_PACKET_MIN_SIZE "
err += "({})).".format(_NTP_PACKET_MIN_SIZE)
raise _NTPInvalidDataException(err)
return s | Check that the payload is long enough to build a NTP packet. |
346,855 | def directives(self):
directive_sources = chain(hug.defaults.directives.items(), getattr(self, , {}).items())
return { + directive_name: directive for directive_name, directive in directive_sources} | Returns all directives applicable to this Hug API |
346,856 | def claim(self, file_readers):
unclaimed_readers = []
vcf_readers = []
for file_reader in file_readers:
if self._is_mutect_vcf(file_reader):
vcf_reader = vcf.VcfReader(file_reader)
vcf_readers.append(_MutectVcfReader(vcf_reader))
e... | Recognizes and claims MuTect VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.
Args:
file_readers: the collection of currently unclaimed files
Returns:
A tuple of... |
346,857 | def slice_config(config, key):
if key:
keys = key.split()
for k in keys:
config = config[k]
return config | Slice config for printing as defined in key.
:param ConfigManager config: configuration dictionary
:param str key: dotted key, by which config should be sliced for printing
:returns: sliced config
:rtype: dict |
346,858 | def destroy_ssh_key(self, ssh_key_id):
json = self.request( % ssh_key_id, method=)
status = json.get()
return status | This method will delete the SSH key from your account. |
346,859 | def zk_client(host, scheme, credential):
if not re.match(r".*:\d+$", host):
host = "%s:%d" % (host, DEFAULT_ZK_PORT)
client = KazooClient(hosts=host)
client.start()
if scheme != "":
client.add_auth(scheme, credential)
return client | returns a connected (and possibly authenticated) ZK client |
346,860 | def find_sink_variables(self):
is_sink = {name: True for name in self.variables.keys()}
for operator in self.operators.values():
for variable in operator.inputs:
is_sink[variable.onnx_name] = False
return [variable for name, variable in self... | Find sink variables in this scope |
346,861 | def compare(self, other, filter_fcn=None):
if not isinstance(other, type(self)):
return False
if filter_fcn is None:
def filter_unique(_, field):
return not field.unique
filter_fcn = filter_unique
return self.to_json_... | Returns True if properties can be compared in terms of eq.
Entity's Fields can be filtered accordingly to 'filter_fcn'.
This callable receives field's name as first parameter and field itself
as second parameter.
It must return True if field's value should be included on
comparis... |
346,862 | def tool_relation(self, pubid):
request = TOPRequest()
request[] = pubid
self.create(self.execute(request), fields=[])
return self.tools_user | taobao.taobaoke.tool.relation 工具联盟注册校验
判断用户pid是否是appkey关联的注册用户 |
346,863 | def cql_encode_map_collection(self, val):
return % .join( % (
self.mapping.get(type(k), self.cql_encode_object)(k),
self.mapping.get(type(v), self.cql_encode_object)(v)
) for k, v in six.iteritems(val)) | Converts a dict into a string of the form ``{key1: val1, key2: val2, ...}``.
This is suitable for ``map`` type columns. |
346,864 | def sample(self, fraction, seed=None, exact=False):
if (fraction > 1 or fraction < 0):
raise ValueError( + str(fraction))
if (len(self) == 0):
return SArray()
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_... | Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the ... |
346,865 | def delete(self):
def set_rw(operation, name, exc):
os.chmod(name, stat.S_IWRITE)
directory = self.project.node_working_directory(self)
if os.path.exists(directory):
try:
yield from wait_run_in_executor(shutil.rmtree, directory, onerror=set_rw)
... | Delete the node (including all its files). |
346,866 | def select(versions, optionsRequired=False):
if type(versions) == str:
versions = [versions]
global _selected
if _selected is not None:
for ver in versions:
if _selected.Score(_wxPackageInfo(ver), optionsRequired) > 0:
return
... | Search for a wxPython installation that matches version. If one
is found then sys.path is modified so that version will be
imported with a 'import wx', otherwise a VersionError exception is
raised. This function should only be called once at the beginning
of the application before wxPython is imported... |
346,867 | def netmiko_fun(fun, *args, **kwargs):
*show version
if not in fun:
fun = .format(fun=fun)
netmiko_kwargs = netmiko_args()
kwargs.update(netmiko_kwargs)
return __salt__[fun](*args, **kwargs) | .. versionadded:: 2019.2.0
Call an arbitrary function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
module, passing the authentication details from the existing NAPALM
connection.
fun
The name of the function from the :mod:`Netmiko<salt.modules.netmiko_mod>`
to invoke.
args
... |
346,868 | def search(self, term):
return self._result(
self._get(self._url("/images/search"), params={: term}),
True
) | Search for images on Docker Hub. Similar to the ``docker search``
command.
Args:
term (str): A term to search for.
Returns:
(list of dicts): The response of the search.
Raises:
:py:class:`docker.errors.APIError`
If the server returns... |
346,869 | def build_node_query(lat_min, lng_min, lat_max, lng_max, tags=None):
if tags is not None:
if isinstance(tags, str):
tags = [tags]
tags = .join(.format(t) for t in tags)
else:
tags =
query_fmt = (
)
... | Build the string for a node-based OSM query.
Parameters
----------
lat_min, lng_min, lat_max, lng_max : float
tags : str or list of str, optional
Node tags that will be used to filter the search.
See http://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide
for information ... |
346,870 | def webhook():
if request.method == "GET" and "challenge" in request.args:
print(" * Nylas connected to the webhook!")
return request.args["challenge"]
data = request.get_json()
for delta in data["deltas"]:
process_delta.delay... | When the Flask server gets a request at the `/webhook` URL, it will run
this function. Most of the time, that request will be a genuine webhook
notification from Nylas. However, it's possible that the request could
be a fake notification from someone else, trying to fool our app. This
function needs to ... |
346,871 | def _get_side2KerningGroups(self):
found = {}
for name, contents in self.items():
if name.startswith("public.kern2."):
found[name] = contents
return found | Subclasses may override this method. |
346,872 | def ut1_jd(self, jd):
ut1 = _to_array(jd)
tt_approx = ut1
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
tt_approx = ut1 + delta_t_approx / DAY_S
delta_t_approx = interpolate_delta_t(self.delta_t_table, tt_approx)
... | Build a `Time` from UT1 a Julian date.
Supply the Universal Time (UT1) as a Julian date:
>>> t = ts.ut1_jd(2456675.56640625)
>>> t.ut1
2456675.56640625 |
346,873 | def join(delim, items, quotes=False):
transform = lambda s: s
if quotes == True:
transform = lambda s: s if not in s else .format(s)
stripped = list([transform(i) for i in items if len(i) > 0])
if len(stripped) > 0:
return delim.join(stripped)
return | Joins the supplied list of strings after removing any empty strings from the list |
346,874 | def update_group_name(self, group_id, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.update_group_name_with_http_info(group_id, body, **kwargs)
else:
(data) = self.update_group_name_with_http_info(group_id, body, **kwargs)
return ... | Update the group name. # noqa: E501
An endpoint for updating a group name. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/policy-groups/{group-id} -d '{\"name\": \"TestGroup2\"}' -H 'content-type: application/json' -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method... |
346,875 | def DeletePermission(self, permission_link, options=None):
if options is None:
options = {}
path = base.GetPathFromLink(permission_link)
permission_id = base.GetResourceIdOrFullNameFromLink(permission_link)
return self.DeleteResource(path,
... | Deletes a permission.
:param str permission_link:
The link to the permission.
:param dict options:
The request options for the request.
:return:
The deleted Permission.
:rtype:
dict |
346,876 | def parse(self, args, ignore_help=False):
options = self._default_dict()
seen = set()
args = copy.copy(args)
while args:
opt = args.pop(0)
seen.add(opt)
if opt in ("--help","-h"):
if ignore_help:
... | Parse the (command-line) arguments. |
346,877 | def _consume_next(self):
response = six.next(self._response_iterator)
self._counter += 1
if self._metadata is None:
metadata = self._metadata = response.metadata
source = self._source
if source is not None and source._transaction_id is None:
... | Consume the next partial result set from the stream.
Parse the result set into new/existing rows in :attr:`_rows` |
346,878 | def have_cycle(graph:dict) -> frozenset:
walked = set()
nodes = frozenset(it.chain(it.chain.from_iterable(graph.values()), graph.keys()))
preds = reversed_graph(graph)
last_walked_len = -1
while last_walked_len != len(walked):
last_walked_len = len(walked)
for node in... | Perform a topologic sort to detect any cycle.
Return the set of unsortable nodes. If at least one item,
then there is cycle in given graph. |
346,879 | def issue(self, test, err):
self.step.setProgress(, len(self.failures) +
len(self.errors)) | An issue - failing, erroring etc test. |
346,880 | def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_port(self, **kwargs):
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_info
output = ET.SubElement(show_fabr... | Auto Generated Code |
346,881 | def get_argument_parser():
file_mv = cli.file_mv
desc =
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
, , type=str, required=True, metavar=file_mv,
help=
)
parser.add_argument(
, , type=str, required=True, metavar=file_mv,
help=
)
... | Function to obtain the argument parser.
Returns
-------
A fully configured `argparse.ArgumentParser` object.
Notes
-----
This function is used by the `sphinx-argparse` extension for sphinx. |
346,882 | def msg_err(message):
to_stdout(" !!! {message}".format(message=message), colorf=red, bold=True)
if _logger:
_logger.error(message) | Log an error message
:param message: the message to be logged |
346,883 | def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,
run_length=6, eig_update=True, collect_stats=False, rz_order=0,
run_type=2, **kwargs):
if rz_order > 0:
aug = AugmentedState(s, param_names, rz_order=rz_order)
lm = LMAugmentedState(aug, damping=damping, run_l... | Runs Levenberg-Marquardt optimization on a state.
Convenience wrapper for LMGlobals. Same keyword args, but the defaults
have been set to useful values for optimizing globals.
See LMGlobals and LMEngine for documentation.
See Also
--------
do_levmarq_particles : Levenberg-Marquardt optimiz... |
346,884 | def get_statements(self, reprocess=False):
if self._statements is None or reprocess:
if self.content is None:
self._statements = []
return []
if self.reader == ReachReader.name:
if self.format == formats.... | General method to create statements. |
346,885 | def add_library_path(path: str) -> bool:
if not os.path.exists(path):
return False
if path not in sys.path:
sys.path.append(path)
return True | Adds the path to the Python system path if not already added and the path
exists.
:param path:
The path to add to the system paths
:return:
Whether or not the path was added. Only returns False if the path was
not added because it doesn't exist |
346,886 | def _is_cached(self, ext=):
if not ext.startswith():
ext = % ext
cache_file = % (self.filename, ext)
return self.filename.endswith(ext) or os.path.exists(cache_file) | Determine if ``filename`` is cached using extension ``ex`` a string.
:param ext: extension used to cache ``filename``, default is '.json'
:type ext: str
:return: True if ``filename`` is cached using extensions ``ex``
:rtype: bool |
346,887 | def _merge_options(self, identifier, group_name, options):
if group_name not in self.groups:
raise KeyError("Group %s not defined on SettingTree" % group_name)
if identifier in self.children:
current_node = self[identifier]
group_options = current_node.group... | Computes a merged Options object for the given group
name from the existing Options on the node and the
new Options which are passed in. |
346,888 | def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True):
filenames = sorted(tf.gfile.Glob(filepattern))
lines_read = 0
for filename in filenames:
with tf.gfile.Open(filename) as f:
if split_on_newlines:
for line in f:
yield line.strip()
lines_read += 1
... | Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespa... |
346,889 | def get_metrics_data(self, query):
if self.es_url.startswith("http"):
url = self.es_url
else:
url = + self.es_url
es = Elasticsearch(url)
s = Search(using=es, index=self.es_index)
s = s.update_from_dict(query)
try:
response = ... | Get the metrics data from Elasticsearch given a DSL query
:param query: query to be sent to Elasticsearch
:return: a dict with the results of executing the query |
346,890 | def get_word_vector(self, word):
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getWordVector(b, word)
return np.array(b) | Get the vector representation of word. |
346,891 | def class_map_name(self, **kwargs):
config = ET.Element("config")
class_map = ET.SubElement(config, "class-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name = ET.SubElement(class_map, "name")
name.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
... | Auto Generated Code |
346,892 | def read_adjacency_matrix(file_path, separator, undirected):
file_row_generator = get_file_row_generator(file_path, separator)
row = list()
col = list()
data = list()
append_row = row.append
append_col = col.append
append_data = data.append
id_to_node = dict()
... | Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format.
Inputs: - file_path: The path where the adjacency matrix is stored.
- separator: The delimiter among values (e.g. ",", "\t", " ")
- undirected: If True, create the reciprocal edge for eac... |
346,893 | def db_chainstate_append(cls, cur, **fields):
missing = []
extra = []
for reqfield in CHAINSTATE_FIELDS:
if reqfield not in fields:
missing.append(reqfield)
for fieldname in fields:
if fieldname not in CHAINSTATE_FIELDS:
e... | Insert a row into the chain state.
Meant to be executed as part of a transaction.
Return True on success
Raise an exception if the fields are invalid
Abort on db error. |
346,894 | def _store_credentials(self, username, password, remember=False):
if username and password and remember:
CONF.set(, , username)
try:
keyring.set_password(, username, password)
except Exception:
if self._show_msgbox:
... | Store credentials for future use. |
346,895 | def list_engines(zap_helper):
engines = zap_helper.zap.script.list_engines
console.info(.format(.join(engines))) | List engines that can be used to run scripts. |
346,896 | def start_response_callback(start_response, origin):
def callback(status, headers, exc_info=None):
headers.append((, origin))
start_response(status, headers, exc_info)
return callback | Intercept upstream start_response and adds our headers. |
346,897 | def police_priority_map_exceed_map_pri4_exceed(self, **kwargs):
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, "name")
name_key.text = kw... | Auto Generated Code |
346,898 | def check_for_period_error(data, period):
period = int(period)
data_len = len(data)
if data_len < period:
raise Exception("Error: data_len < period") | Check for Period Error.
This method checks if the developer is trying to enter a period that is
larger than the data set being entered. If that is the case an exception is
raised with a custom message that informs the developer that their period
is greater than the data set. |
346,899 | def guess_input_handler(seqs, add_seq_names=False):
if isinstance(seqs, str):
if in seqs: | Returns the name of the input handler for seqs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.