text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def ip2asn(ipaddr):
"""Returns the ASN data associated with an IP (v4 or v6)
>>> from pprint import pprint
>>> pprint(ip2asn('8.8.8.8'))
{'asn': '15169',
'asname': 'GOOGLE - Google Inc., US',
'cc': 'US',
'net': '8.8.8.0/24',
'rir': 'ARIN'}
>>> pprint(ip2asn('2001:4860:4860::8888... | 0.001592 |
def cluster_node(self, node_id):
"""
A node resource contains information about a node in the cluster.
:param str node_id: The node id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/ws/v1/cluster/nodes/... | 0.005168 |
def on_menu_exit(self,new):
"""
Fake event handler, same as :py:meth:`WorldView.on_menu_exit()` but force-disables mouse exclusivity.
"""
super(WorldViewMouseRotatable,self).on_menu_exit(new)
self.world.peng.window.toggle_exclusivity(False) | 0.017857 |
def __cancel(self, subscription_id, **kwargs):
"""Call documentation: `/subscription/cancel
<https://www.wepay.com/developer/reference/subscription#cancel>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | 0.004598 |
def authenticate(self, auth_url=None, **kwargs):
"""Authenticates a user via the Keystone Identity API."""
LOG.debug('Beginning user authentication')
if not auth_url:
auth_url = settings.OPENSTACK_KEYSTONE_URL
auth_url, url_fixed = utils.fix_auth_url_version_prefix(auth_url... | 0.000315 |
def fasta(self, key='vdj_nt', append_chain=True):
'''
Returns the sequence pair as a fasta string. If the Pair object contains
both heavy and light chain sequences, both will be returned as a single string.
By default, the fasta string contains the 'vdj_nt' sequence for each chain. To c... | 0.007157 |
def _init_metadata(self):
"""stub"""
ItemTextsFormRecord._init_metadata(self)
ItemFilesFormRecord._init_metadata(self)
super(ItemTextsAndFilesMixin, self)._init_metadata() | 0.009852 |
def _get_subject_info(self, n_local_subj, data):
"""Calculate metadata for subjects allocated to this process
Parameters
----------
n_local_subj : int
Number of subjects allocated to this process.
data : list of 2D array. Each in shape [n_voxel, n_tr]
T... | 0.00188 |
def _erf(x):
"""
Port of cephes ``ndtr.c`` ``erf`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
T = [
9.60497373987051638749E0,
9.00260197203842689217E1,
2.23200534594684319226E3,
7.00332514112805075473E3,
5.55923013010394... | 0.001297 |
def _list_of_dicts_to_column_headers(list_of_dicts):
"""
Detects if all entries in an list of ``dict``'s have identical keys.
Returns the keys if all keys are the same and ``None`` otherwise.
Parameters
----------
list_of_dicts : list
List of dictionaries to ... | 0.005643 |
def add_pending_model_content(cursor, publication_id, model):
"""Updates the pending model's content.
This is a secondary step not in ``add_pending_model, because
content reference resolution requires the identifiers as they
will appear in the end publication.
"""
cursor.execute("""\
SEL... | 0.000201 |
def AddSymbolicLink(self, path, linked_path):
"""Adds a symbolic link to the fake file system.
Args:
path (str): path of the symbolic link within the fake file system.
linked_path (str): path that is linked.
Raises:
ValueError: if the path is already set.
"""
if self.file_system.... | 0.003448 |
def _same_day_ids(self):
"""
:return: ids of occurrences that finish on the same day that they
start, or midnight the next day.
"""
# we can pre-filter to return only occurrences that are <=24h long,
# but until at least the `__date` can be used in F() statements
... | 0.005669 |
def getnode():
"""Get the hardware address as a 48-bit positive integer.
The first time this runs, it may launch a separate program, which could
be quite slow. If all attempts to obtain the hardware address fail, we
choose a random 48-bit number with its eighth bit set to 1 as recommended
in RFC 4... | 0.002611 |
def get_resource(self, service_name, resource_name, base_class=None):
"""
Returns a ``Resource`` **class** for a given service.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
... | 0.001582 |
def _download_predicate_data(self, class_, controller):
"""Get raw predicate information for given request class, and cache for
subsequent calls.
"""
self.authenticate()
url = ('{0}{1}/modeldef/class/{2}'
.format(self.base_url, controller, class_))
logger... | 0.004246 |
def v1_highlights_post(request, response, kvlclient, tfidf,
min_delay=3, task_master=None):
'''Obtain highlights for a document POSTed inside a JSON object.
Get our Diffeo Highlighter browser extension here:
https://chrome.google.com/webstore/detail/jgfcplgdmjkdepnmbdkmgohaldaiplpo
... | 0.00319 |
def job(self):
"""REST binding for the job associated with the submitted build.
Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.
"""
if self._submitter and hasattr(self._submitter, '_job_access'):
... | 0.007792 |
def _update_cell_values(self, cell_ids, interior_edge_ids):
"""Updates all sorts of cell information for the given cell IDs.
"""
# update idx_hierarchy
nds = self.cells["nodes"][cell_ids].T
self.idx_hierarchy[..., cell_ids] = nds[self.local_idx]
# update self.half_edge_c... | 0.000526 |
def repair_mongo(name, dbpath):
"""repair mongodb after usafe shutdown"""
log_file = os.path.join(dbpath, 'mongod.log')
cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend",
"--repair"]
proc = subprocess.Popen(
cmd, universal_newlines=True,
stdout=subprocess.P... | 0.000974 |
def _make_sync_method(name):
"""Helper to synthesize a synchronous method from an async method name.
Used by the @add_sync_methods class decorator below.
Args:
name: The name of the synchronous method.
Returns:
A method (with first argument 'self') that retrieves and calls
self.<name>, passing it... | 0.006734 |
def classpath(cls, targets, classpath_products, confs=('default',)):
"""Return the classpath as a list of paths covering all the passed targets.
:param targets: Targets to build an aggregated classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements.
:param confs... | 0.005102 |
def refresh_listing():
"""Refreshes the list of programs attached to the perform module from
the path"""
for program in get_programs():
if re.match(r'^[a-zA-Z_][a-zA-Z_0-9]*$', program) is not None:
globals()[program] = partial(_run_program, program)
globals()["_"] = _underscore_run... | 0.003049 |
def upload_file_to_s3(awsclient, bucket, key, filename):
"""Upload a file to AWS S3 bucket.
:param awsclient:
:param bucket:
:param key:
:param filename:
:return:
"""
client_s3 = awsclient.get_client('s3')
transfer = S3Transfer(client_s3)
# Upload /tmp/myfile to s3://bucket/key ... | 0.001773 |
def addBarcodesToIdentifier(read, UMI, cell):
'''extract the identifier from a read and append the UMI and
cell barcode before the first space'''
read_id = read.identifier.split(" ")
if cell == "":
read_id[0] = read_id[0] + "_" + UMI
else:
read_id[0] = read_id[0] + "_" + cell + "_"... | 0.002597 |
def _format_subtree(self, subtree):
"""Recursively format all subtrees."""
subtree['children'] = list(subtree['children'].values())
for child in subtree['children']:
self._format_subtree(child)
return subtree | 0.007937 |
def enumerate_tokens(sid=None, session_id=None, privs=None):
'''
Enumerate tokens from any existing processes that can be accessed.
Optionally filter by sid.
'''
for p in psutil.process_iter():
if p.pid == 0:
continue
try:
ph = win32api.OpenProcess(win32con.PR... | 0.003277 |
def _abs32(ins):
""" Absolute value of top of the stack (32 bits in DEHL)
"""
output = _32bit_oper(ins.quad[2])
output.append('call __ABS32')
output.append('push de')
output.append('push hl')
REQUIRES.add('abs32.asm')
return output | 0.003802 |
def _request_toc_element(self, index):
"""Request information about a specific item in the TOC"""
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, i... | 0.002999 |
def Nu_plate_Kumar(Re, Pr, chevron_angle, mu=None, mu_wall=None):
r'''Calculates Nusselt number for single-phase flow in a
**well-designed** Chevron-style plate heat exchanger according to [1]_.
The data is believed to have been developed by APV International Limited,
since acquired by SPX Corporation.... | 0.006787 |
def _mouse_pointer_moved(self, x, y):
'''GUI callback for mouse moved'''
self._namespace['MOUSEX'] = x
self._namespace['MOUSEY'] = y | 0.012821 |
def overlaps(self, canvas, exclude=[]):
"""
Returns True if sprite is touching any other sprite.
"""
try:
exclude = list(exclude)
except TypeError:
exclude = [exclude]
exclude.append(self)
for selfY, row in enumerate(self.image.image()... | 0.003063 |
def log_stack(logger, level=logging.INFO, limit=None, frame=None):
"""
Display the current stack on ``logger``.
This function is designed to be used during emission of log messages, so it
won't call itself.
"""
if showing_stack.inside:
return
showing_stack.inside = True
try:
... | 0.003356 |
def get_parent_device(self):
"""Retreive parent device string id"""
if not self.parent_instance_id:
return ""
dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN
dev_buffer = dev_buffer_type()
try:
if winapi.CM_Get_Device_ID(self.parent_instance_id... | 0.011091 |
def get_configuration_set_by_id(self, id):
'''Finds a configuration set in the component by its ID.
@param id The ID of the configuration set to search for.
@return The ConfigurationSet object for the set, or None if it was not
found.
'''
for cs in self.configuration_se... | 0.005038 |
def get_or_create_permission(codename, name=camel_or_snake_to_title):
"""
Get a Permission object from a permission name.
@:param codename: permission code name
@:param name: human-readable permissions name (str) or callable that takes codename as
argument and returns str
"""
u... | 0.006993 |
def _validate(self, val):
"""
Checks that the value is numeric and that it is within the hard
bounds; if not, an exception is raised.
"""
if self.allow_None and val is None:
return
if not isinstance(val, dt_types) and not (self.allow_None and val is None):
... | 0.008532 |
def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
"""
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optio... | 0.000985 |
def to_mongo(self):
"""Translate projection to MongoDB query form.
:return: Dictionary to put into a MongoDB JSON query
:rtype: dict
"""
d = copy.copy(self._fields)
for k, v in self._slices.items():
d[k] = {'$slice': v}
return d | 0.006734 |
def apply_constraint(self,constraint,selectfrac_skip=False,
distribution_skip=False,overwrite=False):
"""Apply a constraint to the population
:param constraint:
Constraint to apply.
:type constraint:
:class:`Constraint`
:param selectfrac... | 0.007092 |
def _is_array_integer(arr):
"""Returns True if an array contains integers (integer type or near-int
float values) and False otherwise.
>>> _is_array_integer(np.arange(10))
True
>>> _is_array_integer(np.arange(7.0, 20.0, 1.0))
True
>>> _is_array_integer(np.arange(0, 1, 0.1))
False
""... | 0.004926 |
def update_option_by_id(cls, option_id, option, **kwargs):
"""Update Option
Update attributes of Option
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_by_id(option_id, option, a... | 0.004154 |
def get(name, fallback='ssh'):
"""
Retrieve the matching backend class from a string. If no backend can be
matched, it raises an error.
>>> get('ssh')
<class 'remoto.backends.BaseConnection'>
>>> get()
<class 'remoto.backends.BaseConnection'>
>>> get('non-existent')
<class 'remoto.b... | 0.000718 |
def get_supported_metrics_notification_hub(self, name, hub_name):
'''
Retrieves the list of supported metrics for this namespace and topic
name:
Name of the service bus namespace.
hub_name:
Name of the service bus notification hub in this namespace.
'''
... | 0.002915 |
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name... | 0.001928 |
def CMYK_to_CMY(cobj, *args, **kwargs):
"""
Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
cmy_c = cobj.cmyk_c * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_m = cobj.cmyk_m * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
cmy_y = cobj.cmyk_y * (1.0 - cobj.cmyk_k) + cobj.cmyk_k
... | 0.002809 |
def scopes_as(self, new_scopes):
"""Replace my :attr:`scopes` for the duration of the with block.
My global scope is not replaced.
Args:
new_scopes (list of dict-likes): The new :attr:`scopes` to use.
"""
old_scopes, self.scopes = self.scopes, new_scopes
yie... | 0.005634 |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = RelativeLayout(self.get_context(), None, d.style) | 0.011111 |
def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]:
"""
Utility method to return the set of all supported types that may be parsed from files with the given extension.
ext=JOKER is a joker that means all extensions
:param ext_to... | 0.009375 |
def compile_compiler_bridge(self, context):
"""Compile the compiler bridge to be used by zinc, using our scala bootstrapper.
It will compile and cache the jar, and materialize it if not already there.
:param context: The context of the task trying to compile the bridge.
This is mostly n... | 0.008985 |
def support_autoupload_param_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
autoupload_param = ET.SubElement(support, "autoupload-param")
password = ET... | 0.006012 |
def wrap_form_params(func):
"""
A middleware that parses the url-encoded body and attach
the result to the request `form_params` attribute.
This middleware also merges the parsed value with the existing
`params` attribute in same way as `wrap_query_params` is doing.
"""
@functools.wraps(fu... | 0.002144 |
def _copy_flaky_attributes(cls, test, test_class):
"""
Copy flaky attributes from the test callable or class to the test.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test`
"""
test_callable = cls._get_test_cal... | 0.002395 |
def download_signed_document(self, signature_id, document_id):
"""
Get the audit trail of concrete document
@signature_id: Id of signature
@document_id: Id of document
"""
connection = Connection(self.token)
connection.set_url(self.production, self.SIGNS_DOCUMENT... | 0.00566 |
def transform(self, fn, dtype=None, *args, **kwargs):
"""Equivalent to map, compatibility purpose only.
Column parameter ignored.
"""
rdd = self._rdd.map(fn)
if dtype is None:
return self.__class__(rdd, noblock=True, **self.get_params())
if dtype is np.ndarra... | 0.003448 |
def _read_optimized_geometry(self):
"""
Parses optimized XYZ coordinates. If not present, parses optimized Z-matrix.
"""
header_pattern = r"\*+\s+OPTIMIZATION\s+CONVERGED\s+\*+\s+\*+\s+Coordinates \(Angstroms\)\s+ATOM\s+X\s+Y\s+Z"
table_pattern = r"\s+\d+\s+\w+\s+([\d\-\.]+)\s+([... | 0.005158 |
def get_guardian_enrollments(self, user_id):
"""Retrieves all Guardian enrollments.
Args:
user_id (str): The user_id of the user to retrieve
See: https://auth0.com/docs/api/management/v2#!/Users/get_enrollments
"""
url = self._url('{}/enrollments'.format(user_id))
... | 0.005634 |
def search(self):
"redirect to bookmark search"
form = forms.HomeForm()
bbm_filter = bs_filters.BookmarkBukuFilter(
all_keywords=False, deep=form.deep.data, regex=form.regex.data)
op_text = bbm_filter.operation()
values_combi = sorted(itertools.product([True, False], ... | 0.004938 |
def set_bot(self, bot):
''' Bot must be set before running '''
self.bot = bot
self.sink.set_bot(bot) | 0.016129 |
def add(addon, dev, interactive):
"""Add a dependency.
Examples:
$ django add dynamic-rest==1.5.0
+ dynamic-rest == 1.5.0
"""
application = get_current_application()
application.add(
addon,
dev=dev,
interactive=interactive
) | 0.003534 |
def countNeighbours(self, cell):
"""
Return the number active neighbours within one positions away from cell
"""
count = 0
y, x = cell
y = y % self.y_grid
x = x % self.x_grid
y1 = (y - 1) % self.y_grid
y2 = (y + 1) % self.y_grid
x1 = (x - 1... | 0.003559 |
def replace_some(ol,value,*indexes,**kwargs):
'''
from elist.elist import *
ol = [1,'a',3,'a',5,'a',6,'a']
id(ol)
new = replace_some(ol,'AAA',1,3,7)
ol
new
id(ol)
id(new)
####
ol = [1,'a',3,'a',5,'a',6,'a']
id(ol)
rslt =... | 0.011725 |
def mccormick(theta):
"""McCormick function"""
x, y = theta
obj = np.sin(x + y) + (x - y)**2 - 1.5 * x + 2.5 * y + 1
grad = np.array([np.cos(x + y) + 2 * (x - y) - 1.5,
np.cos(x + y) - 2 * (x - y) + 2.5])
return obj, grad | 0.003817 |
def refresh(self, include_fields=None, exclude_fields=None,
extra_fields=None):
"""
Refresh the bug with the latest data from bugzilla
"""
# pylint: disable=protected-access
r = self.bugzilla._getbug(self.bug_id,
include_fields=include_fields, exclude_fields=e... | 0.010616 |
def is_file_consistent(local_path_file, md5_hash):
"""Check if file is there and if the md5_hash is correct."""
return os.path.isfile(local_path_file) and \
hashlib.md5(open(local_path_file, 'rb').read()).hexdigest() == md5_hash | 0.004098 |
def trace(self, *attributes):
"""
Function decorator that traces functions
NOTE: Must be placed after the @app.route decorator
@param attributes any number of flask.Request attributes
(strings) to be set as tags on the created span
"""
def decorator(f):
... | 0.002245 |
def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options):
"""Returns True if user agrees, False otherwise"""
return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message) | 0.016667 |
def class_types(self):
"""list of class/class declaration types, extracted from the
operator arguments"""
if None is self.__class_types:
self.__class_types = []
for type_ in self.argument_types:
decl = None
type_ = type_traits.remove_refer... | 0.002364 |
def get_requirement_from_url(url):
"""Get a requirement from the URL, if possible. This looks for #egg
in the URL"""
link = Link(url)
egg_info = link.egg_fragment
if not egg_info:
egg_info = splitext(link.filename)[0]
return package_to_requirement(egg_info) | 0.003448 |
def run(ident):
'''Launch or resume an harvesting for a given source if none is running'''
source = get_source(ident)
cls = backends.get(current_app, source.backend)
backend = cls(source)
backend.harvest() | 0.004444 |
def on_queue_declareok(self, method_frame):
"""Method invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, ... | 0.004815 |
def nmget(o, key_path, def_val=None, path_delimiter='.', null_as_default=True):
'''
A short-hand for retrieving a value from nested mappings
("nested-mapping-get"). At each level it checks if the given "path"
component in the given key exists and return the default value whenever
fails.
Exampl... | 0.001192 |
def get_words(data):
"""
Extracts the words from given string.
Usage::
>>> get_words("Users are: John Doe, Jane Doe, Z6PO.")
[u'Users', u'are', u'John', u'Doe', u'Jane', u'Doe', u'Z6PO']
:param data: Data to extract words from.
:type data: unicode
:return: Words.
:rtype: l... | 0.002242 |
def set_filters(self, filters=None):
"""Apply filtering to all messages received by this Bus.
All messages that match at least one filter are returned.
If `filters` is `None` or a zero length sequence, all
messages are matched.
Calling without passing any filters will reset the... | 0.002022 |
def get_last_value_from_timeseries(timeseries):
"""Gets the most recent non-zero value for a .last metric or zero
for empty data."""
if not timeseries:
return 0
for metric, points in timeseries.items():
return next((p['y'] for p in reversed(points) if p['y'] > 0), 0) | 0.003344 |
def load_device(self, serial=None):
"""Creates an AndroidDevice for the given serial number.
If no serial is given, it will read from the ANDROID_SERIAL
environmental variable. If the environmental variable is not set, then
it will read from 'adb devices' if there is only one.
"... | 0.001744 |
def plot_clock_diagrams(self, colormap="summer"):
"""
Ploting clock diagrams - one or more rings around residue name and id (and chain id).
The rings show the fraction of simulation time this residue has spent in the vicinity of the
ligand - characterised by distance.
"""
... | 0.018519 |
def debug_option(f):
"""
Configures --debug option for CLI
:param f: Callback Function to be passed to Click
"""
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.debug = value
return value
return click.option('--debug',
e... | 0.00354 |
def set_value(cls, group, key=None, value=None):
"""set|create/update"""
return cls.query.set_value(general_object_model_class=cls, group=group, key=key, value=value) | 0.016484 |
def get_unused_port(port=None):
"""Checks if port is already in use."""
if port is None or port < 1024 or port > 65535:
port = random.randint(1024, 65535)
assert(1024 <= port <= 65535)
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('', ... | 0.001776 |
def cancel_spot_requests(self, requests):
"""Cancel one or more EC2 spot instance requests.
:param requests: List of EC2 spot instance request IDs.
:type requests: list
"""
ec2_requests = self.retry_on_ec2_error(self.ec2.get_all_spot_instance_requests, request_ids=requests)
... | 0.008021 |
def examples():
''' Examples of how to use. Default are that some functions are commented out in order
to not cause harm to existing metadata within the database.
'''
sci = InterLexClient(
api_key = os.environ.get('INTERLEX_API_KEY'),
base_url = 'https://beta.scicrunch.org/api/1/', #... | 0.008939 |
def get_form_kwargs(self):
"""
Pass template pack argument
"""
kwargs = super(FormContainersMixin, self).get_form_kwargs()
kwargs.update({
'pack': "foundation-{}".format(self.kwargs.get('foundation_version'))
})
return kwargs | 0.010239 |
def rehash(path, algo='sha256', blocksize=1 << 20):
"""Return (hash, length) for path using hashlib.new(algo)"""
h = hashlib.new(algo)
length = 0
with open(path, 'rb') as f:
block = f.read(blocksize)
while block:
length += len(block)
h.update(block)
bl... | 0.002132 |
def create_record(self, rtype=None, name=None, content=None, **kwargs):
"""
Create record. If record already exists with the same content, do nothing.
"""
if not rtype and kwargs.get('type'):
warnings.warn('Parameter "type" is deprecated, use "rtype" instead.',
... | 0.008929 |
def get_token_from_authorization_code(self,
authorization_code, redirect_uri):
"""Like `get_token`, but using an OAuth 2 authorization code.
Use this method if you run a webserver that serves as an endpoint for
the redirect URI. The webserver can retrie... | 0.002187 |
def is_tensor_on_canonical_device(self, tensor_name):
"""Whether the tensor is on the first (canonical) device.
Tensors not assigned to a device are assumed to be on all devices, including
the canonical device.
Args:
tensor_name: a string, name of a tensor in the graph.
Returns:
a boo... | 0.004065 |
def generate(bits, progress_func=None):
"""
Generate a new private RSA key. This factory function can be used to
generate a new host key or authentication key.
:param int bits: number of bits the generated key should be.
:param progress_func: Unused
:return: new `.RSAKe... | 0.003976 |
def main(cls, args=None):
"""
Fill in command-line arguments from argv
"""
if args is None:
args = sys.argv[1:]
try:
o = cls()
o.parseOptions(args)
except usage.UsageError as e:
print(o.getSynopsis())
print(o.ge... | 0.004124 |
def ManualUpdateTables(self):
"""
Allow user to manually update the database tables.
User options from initial prompt are:
- 'ls' : print database contents
- 'a' : add an row to a database table
- 'd' : delete a single table row
- 'p' : delete an entire table (purge)
- 'f' : ... | 0.011311 |
def _iget(key, lookup_dict):
"""
Case-insensitive search for `key` within keys of `lookup_dict`.
"""
for k, v in lookup_dict.items():
if k.lower() == key.lower():
return v
return None | 0.004484 |
def encode_pin(self, pin, matrix=None):
"""Transform correct PIN according to the displayed matrix."""
if matrix is None:
_, matrix = self.read_pin()
return "".join([str(matrix.index(p) + 1) for p in pin]) | 0.008299 |
def report(self, linenumber, filename, severity, message, rulename, char):
"""Report a rule violation"""
if self._print_filename is not None:
# we print the filename only once. self._print_filename
# will get reset each time a new file is processed.
print("+ " + self... | 0.004 |
def rand_str(length, allowed=CHARSET_ALPHA_DIGITS):
"""Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnw... | 0.002262 |
def _set_overlay_service_policy(self, v, load=False):
"""
Setter method for overlay_service_policy, mapped from YANG variable /overlay_gateway/overlay_service_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_service_policy is considered as a pri... | 0.005969 |
def _is_dir(self, f):
'''Check if the given in-dap file is a directory'''
return self._tar.getmember(f).type == tarfile.DIRTYPE | 0.013986 |
def get_jsapi_ticket(self):
"""
获取微信 JS-SDK ticket
该方法会通过 session 对象自动缓存管理 ticket
:return: ticket
"""
ticket_key = '{0}_jsapi_ticket'.format(self.appid)
expires_at_key = '{0}_jsapi_ticket_expires_at'.format(self.appid)
ticket = self.session.get(ticket_ke... | 0.003937 |
def scanProcessForOpenFile(pid, searchPortion, isExactMatch=True, ignoreCase=False):
'''
scanProcessForOpenFile - Scans open FDs for a given pid to see if any are the provided searchPortion
@param searchPortion <str> - Filename to check
@param isExactMatch <bool> Default True - If m... | 0.012119 |
def _prune(dir_: str, epochs: int) -> None:
"""
Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned
... | 0.004717 |
def press_pwr_btn(self):
"""Simulates a physical press of the server power button.
:raises: IloError, on an error from iLO.
"""
sushy_system = self._get_sushy_system(PROLIANT_SYSTEM_ID)
try:
sushy_system.push_power_button(sys_cons.PUSH_POWER_BUTTON_PRESS)
exc... | 0.003317 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.