text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _login(self, user, password, restrict_login=None):
"""
Backend login method for Bugzilla3
"""
payload = {'login': user, 'password': password}
if restrict_login:
payload['restrict_login'] = True
return self._proxy.User.login(payload) | 0.006734 |
def maskMatch(self, mask):
"""
Determine whether this sequence matches the given mask.
:param mask: string to match against. Ns in the mask are considered to
match anything in the sequence -- all other chars must
match exactly.
:return: True if the mask match... | 0.006557 |
def cmd_ip_geolocation(ip_address, verbose):
"""Get the geolocation of an IP adddress from https://ipapi.co/.
Example:
\b
$ habu.ip.geolocation 8.8.8.8
{
"ip": "8.8.8.8",
"city": "Mountain View",
...
"asn": "AS15169",
"org": "Google LLC"
}
"""
if... | 0.001527 |
def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... | 0.004167 |
def calc_max_flexural_wavelength(self):
"""
Returns the approximate maximum flexural wavelength
This is important when padding of the grid is required: in Flexure (this
code), grids are padded out to one maximum flexural wavelength, but in any
case, the flexural wavelength is a good character... | 0.010856 |
def parse_buffer(buffer, mode="exec", flags=[], version=None, engine=None):
"""
Like :meth:`parse`, but accepts a :class:`source.Buffer` instead of
source and filename, and returns comments as well.
:see: :meth:`parse`
:return: (:class:`ast.AST`, list of :class:`source.Comment`)
Abstract sy... | 0.001059 |
def update(kernel=False):
"""
Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``.
Exclude *kernel* upgrades by default.
"""
manager = MANAGER
cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}}
cmd = cmds[manager][kernel]
run_as_root... | 0.00565 |
def bash(command="bash"):
"""Start a bash shell and return a :class:`REPLWrapper` object."""
bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
encoding='utf-8')
# If the user runs 'env', the value of ... | 0.00325 |
def _nested_add(nested_a, nested_b):
"""Add two arbitrarily nested `Tensors`."""
return nest.map(lambda a, b: a + b, nested_a, nested_b) | 0.021429 |
def _tracing_information():
"""Gets B3 distributed tracing information, if available.
This is returned as a list, ready to be formatted into Spring Cloud Sleuth compatible format.
"""
# We'll collate trace information if the B3 headers have been collected:
values = b3.values()
if values[b3.b3... | 0.004994 |
def sync_via_get(self, owner, id, **kwargs):
"""
Sync files (via GET)
Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to us... | 0.002719 |
def _start_new_warc_file(self, meta=False):
'''Create and set as current WARC file.'''
if self._params.max_size and not meta and self._params.appending:
while True:
self._warc_filename = self._generate_warc_filename()
if os.path.exists(self._warc_filename):
... | 0.00227 |
def from_weight_map(cls, pixel_scale, weight_map):
"""Setup the noise-map from a weight map, which is a form of noise-map that comes via HST image-reduction and \
the software package MultiDrizzle.
The variance in each pixel is computed as:
Variance = 1.0 / sqrt(weight_map).
T... | 0.004525 |
def initialize(self, init_type = ema_init_type.KMEANS_INITIALIZATION):
"""!
@brief Calculates initial parameters for EM algorithm: means and covariances using
specified strategy.
@param[in] init_type (ema_init_type): Strategy for initialization.
@... | 0.015267 |
def on_palette_name_changed(self, combo):
"""Changes the value of palette in dconf
"""
palette_name = combo.get_active_text()
if palette_name not in PALETTES:
return
self.settings.styleFont.set_string('palette', PALETTES[palette_name])
self.settings.styleFont.... | 0.004228 |
def looks_like_gene(self):
'''Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons'''
return self.is_complete_orf() \
and len(self) >= 6 \
and len(self) %3 == 0 \
and self.seq[0:3].upper() in geneti... | 0.020115 |
def slice_mesh_plane(mesh,
plane_normal,
plane_origin,
**kwargs):
"""
Slice a mesh with a plane, returning a new mesh that is the
portion of the original mesh to the positive normal side of the plane
Parameters
---------
mesh : Trim... | 0.000433 |
def _street_addr_from_response(self, match):
"""Construct a street address (no city, region, etc.) from a geocoder response.
:param match: The match object returned by the geocoder.
"""
# Same caveat as above regarding the ordering of these fields; the
# documentation is not exp... | 0.003647 |
def run(self):
"""
Run the plugin.
"""
worker_builds = self.workflow.build_result.annotations['worker-builds']
has_v1_image_id = None
repo_tags = {}
for platform in worker_builds:
build_info = get_worker_build_info(self.workflow, platform)
... | 0.004955 |
def perform_permissions_check(self, user, obj, perms):
""" Performs the permission check. """
return self.request.forum_permission_handler.can_add_post(obj, user) | 0.011236 |
def get_us_midlatitude_cyclone_abi(base_dir='.', method=None, force=False):
"""Get GOES-16 ABI (CONUS sector) data from 2019-03-14 00:00Z.
Args:
base_dir (str): Base directory for downloaded files.
method (str): Force download method for the data if not already cached.
Allowed optio... | 0.002342 |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reaso... | 0.006764 |
def update_port_monitor(self, resource, timeout=-1):
"""
Updates the port monitor configuration of a logical interconnect.
Args:
resource: Port monitor configuration.
Returns:
dict: Port monitor configuration.
"""
data = resource.copy()
i... | 0.003839 |
def list_nodes_full(call=None):
''' Return a list of the BareMetal servers that are on the provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'list_nodes_full must be called with -f or --function'
)
items = query(method='servers')
# For each server, iterate o... | 0.001883 |
def tt(self, key, locale=None, locale2=None, default=I18n.DFT):
"""
|tt| means text transform.
key: tt key.
locale: main locale key into |self.tt_dd|. Default to |self.locale|
locale2: fallback locale key into |self.tt_dd|. Default to |self.locale2|
default: a de... | 0.019017 |
def setup_pod(build_file_path, manage_dir=None, local_requirements=None):
"""
This must be called by the project's build.py for pyntofdjango to function.
You can specify it directly with the optional manage_dir kwarg.
:param build_file_path: E.g. os.path.abspath(__file__)
:param manage_dir: Optio... | 0.005263 |
def _list_audio_files(self, sub_dir=""):
"""
Parameters
----------
sub_dir : one of `needed_directories`, optional
Default is "", which means it'll look through all of subdirs.
Returns
-------
audio_files : [str]
A list whose elements are ... | 0.002574 |
def _GetStructureValue(self, structure, key):
"""Retrieves a value from a parsed log line, removing empty results.
Args:
structure (pyparsing.ParseResults): parsed log line.
key (str): results key to retrieve from the parsed log line.
Returns:
type or None: the value of the named key in ... | 0.001961 |
def _parse_timestamp(tokens):
"""Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`."""
def parse():
precision = TimestampPrecision.YEAR
off_hour = tokens[_TimestampState.OFF_HOUR]
off_minutes = tokens[_TimestampState.OFF_MINUTE]
... | 0.001389 |
def _set_wait(self, request, validator_query):
"""Parses the `wait` query parameter, and sets the corresponding
`wait` and `timeout` properties in the validator query.
"""
wait = request.url.query.get('wait', 'false')
if wait.lower() != 'false':
validator_query.wait =... | 0.003509 |
def edit_task(self, task_name, **kwargs):
""" Change the name of a Task owned by this Job.
This will affect the historical data available for this
Task, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} editing task {1}'.format(self.name, task_name))
... | 0.001308 |
def libname_from_dir(dirname):
"""Reconstruct the library name without it's version"""
parts = []
for part in dirname.split('-'):
if part[0].isdigit():
break
parts.append(part)
return '-'.join(parts) | 0.004115 |
def construct_url(self):
"""Construct a full plex request URI, with `params`."""
path = [self.path]
path.extend([str(x) for x in self.params])
url = self.client.base_url + '/'.join(x for x in path if x)
query = self.kwargs.get('query')
if query:
# Dict -> Li... | 0.003035 |
def output(memory, ofile=None):
""" Filters the output removing useless preprocessor #directives
and writes it to the given file or to the screen if no file is passed
"""
for m in memory:
m = m.rstrip('\r\n\t ') # Ensures no trailing newlines (might with upon includes)
if m and m[0] == ... | 0.002574 |
def query_properties_with_values(self, query, include_defaults=True):
''' Query the properties values of |HasProps| instances with a
predicate.
Args:
query (callable) :
A callable that accepts property descriptors and returns True
or False
... | 0.00412 |
def read(self, *args, **kwargs):
""" read the buffer, passing named and non named arguments to the
io.BufferedReader function.
"""
buf = io.BufferedReader.read(self, *args, **kwargs)
self.increment(len(buf))
return buf | 0.007407 |
def find_tree_root(tree, key):
"""Find a root in a tree by it's key
:param dict tree: the pkg dependency tree obtained by calling
`construct_tree` function
:param str key: key of the root node to find
:returns: a root node if found else None
:rtype: mixed
"""
result = ... | 0.002252 |
def set(self, varname, value, idx=0, units=None):
'''set a variable value'''
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
if idx >= self.mapping.vars[varname].arraylength:
raise fgFDMError('index of %s beyond end of array idx=%u a... | 0.006766 |
def try_to_set_up_global_logging():
"""Try to set up global W&B debug log that gets re-written by every W&B process.
It may fail (and return False) eg. if the current directory isn't user-writable
"""
root = logging.getLogger()
root.setLevel(logging.DEBUG)
formatter = logging.Formatter(
... | 0.004111 |
def remove_option(self, mask):
"""Unset arbitrary query flags using a bitmask.
To unset the tailable flag:
cursor.remove_option(2)
"""
if not isinstance(mask, int):
raise TypeError("mask must be an int")
self.__check_okay_to_chain()
if mask & _QUERY_... | 0.00464 |
def NewFromLab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF):
'''Create a new instance based on the specifed CIE-LAB values.
Parameters:
:l:
The L component [0...100]
:a:
The a component [-1...1]
:b:
The a component [-1...1]
:alpha:
The color transparency [0...... | 0.00495 |
def input_from_history(a, n, bias=False):
"""
This is function for creation of input matrix.
**Args:**
* `a` : series (1 dimensional array)
* `n` : size of input matrix row (int). It means how many samples \
of previous history you want to use \
as the filter input. It also repres... | 0.002349 |
def remove(client, names):
"""Delete a dataset."""
from renku.models.refs import LinkReference
datasets = {name: client.dataset_path(name) for name in names}
if not datasets:
raise click.BadParameter(
'use dataset name or identifier', param_hint='names'
)
unknown = [
... | 0.00083 |
def switch_off(self):
"""Close the valve."""
success = self.set_status(CONST.STATUS_OFF_INT)
if success:
self._json_state['status'] = CONST.STATUS_CLOSED
return success | 0.009346 |
def iplot_bloch_multivector(rho, figsize=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size i... | 0.001664 |
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir):
""" Download script for google drive shared links
Thank you @turdus-merula and Andrew Hundt!
https://stackoverflow.com/a/39225039/623735
"""
if '&id=' in driveid:
# https://drive.google.com/uc?export=... | 0.006024 |
def _get(self, key, parser_result):
""" Given a type and a dict of parser results, return
the items as a list.
"""
try:
list_data = parser_result[key].asList()
if any(isinstance(obj, str) for obj in list_data):
txt_lines = [''.join(list_data)]
... | 0.004255 |
def show_node(self, node):
"""true if builtins and not show_builtins"""
if self.config.show_builtin:
return True
return node.root().name != BUILTINS_NAME | 0.010582 |
def function_options_help():
"""Help message for Function options Dialog.
.. versionadded:: 3.2.1
:returns: A message object containing helpful information.
:rtype: messaging.message.Message
"""
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(conten... | 0.002915 |
def handle_exception(self, e, status=500):
"""Handle the given exception. Log, sets the response code and
output the exception message as an error message.
:param e: Exception which is being handled.
:type e: :class:`Exception`
:param status: Status code to set.
:type st... | 0.003795 |
def isoformat(self):
"""Return the time formatted according to ISO.
This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if
self.microsecond == 0.
"""
s = _format_time(self._hour, self._minute, self._second,
self._microsecond)
tz = self._tzstr()
... | 0.005391 |
def update_create_front_page_courses(self, course_id, wiki_page_body=None, wiki_page_editing_roles=None, wiki_page_notify_of_update=None, wiki_page_published=None, wiki_page_title=None):
"""
Update/create front page.
Update the title or contents of the front page
"""
path ... | 0.003322 |
def michalewicz_function(config, reporter):
"""f(x) = -sum{sin(xi) * [sin(i*xi^2 / pi)]^(2m)}"""
import numpy as np
x = np.array(
[config["x1"], config["x2"], config["x3"], config["x4"], config["x5"]])
sin_x = np.sin(x)
z = (np.arange(1, 6) / np.pi * (x * x))
sin_z = np.power(np.sin(z), ... | 0.002146 |
async def process_lander_page(session, github_api_token, ltd_product_data,
mongo_collection=None):
"""Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session... | 0.000435 |
def css_one(self, path, default=NULL):
"""
Get first element which matches the given css path
or raise DataNotFound.
"""
try:
return self.css_list(path)[0]
except IndexError:
if default is NULL:
raise DataNotFound('CSS path not... | 0.005155 |
def _format_device(var):
"""Returns the device with an annotation specifying `ResourceVariable`.
"legacy" means a normal tf.Variable while "resource" means a ResourceVariable.
For example:
`(legacy)`
`(resource)`
`/job:learner/task:0/device:CPU:* (legacy)`
`/job:learner/task:0/device:CPU:* (resource)`
... | 0.011111 |
def commands(self):
"""
:rtype: twilio.rest.wireless.v1.command.CommandList
"""
if self._commands is None:
self._commands = CommandList(self)
return self._commands | 0.009302 |
def authenticate_server(self, response):
"""
Uses GSSAPI to authenticate the server.
Returns True on success, False on failure.
"""
log.debug("authenticate_server(): Authenticate header: {0}".format(
_negotiate_value(response)))
host = urlparse(response.url... | 0.002398 |
def video(video_type, video_mime, doc=None):
"""Dynamically creates a video type handler for the specified video type"""
@on_valid(video_mime)
def video_handler(data, **kwargs):
if hasattr(data, 'read'):
return data
elif hasattr(data, 'save'):
output = stream()
... | 0.001499 |
def clean_delete(self):
"""
Deletes this router & associated files (nvram, disks etc.)
"""
yield from self._hypervisor.send('vm clean_delete "{}"'.format(self._name))
self._hypervisor.devices.remove(self)
try:
yield from wait_run_in_executor(shutil.rmtree, se... | 0.008993 |
def send(self, chat_id, msg_type, **kwargs):
"""
应用推送消息
详情请参考:https://work.weixin.qq.com/api/doc#90000/90135/90248
:param chat_id: 群聊id
:param msg_type: 消息类型,可以为text/image/voice/video/file/textcard/news/mpnews/markdown
:param kwargs: 具体消息类型的扩展参数
:return:
... | 0.005515 |
def register(cls):
"""Register an :class:`~.Entity` as a attachmentable class.
Can be used as a class decorator:
.. code-block:: python
@attachment.register
class MyContent(Entity):
....
"""
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass o... | 0.00495 |
def _get_date(data, position, dummy, opts):
"""Decode a BSON datetime to python datetime.datetime."""
end = position + 8
millis = _UNPACK_LONG(data[position:end])[0]
diff = ((millis % 1000) + 1000) % 1000
seconds = (millis - diff) / 1000
micros = diff * 1000
if opts.tz_aware:
return ... | 0.001916 |
def update_package_versions(self, batch_request, feed_id):
"""UpdatePackageVersions.
[Preview API] Update several packages from a single feed in a single request. The updates to the packages do not happen atomically.
:param :class:`<NuGetPackagesBatchRequest> <azure.devops.v5_0.nuget.models.NuGe... | 0.006148 |
def add_dry_run(parser):
'''
:param parser:
:return:
'''
default_format = 'table'
resp_formats = ['raw', 'table', 'colored_table', 'json']
available_options = ', '.join(['%s' % opt for opt in resp_formats])
def dry_run_resp_format(value):
if value not in resp_formats:
raise argparse.ArgumentT... | 0.011483 |
def emptyTag(self, namespace, name, attrs, hasChildren=False):
"""Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to... | 0.003091 |
def get_version():
"""
Returns shorter version (digit parts only) as string.
"""
version = '.'.join((str(each) for each in VERSION[:3]))
if len(VERSION) > 3:
version += VERSION[3]
return version | 0.004425 |
def cast_to_subclass(self):
"""
Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return:
"""
self.import_lib()
self.load_requirements()
try:
self.commit() # To ensure the r... | 0.006863 |
def format_assistants_lines(cls, assistants):
'''Return formatted assistants from the given list in human readable form.'''
lines = cls._format_files(assistants, 'assistants')
# Assistant help
if assistants:
lines.append('')
assistant = strip_prefix(random.choice... | 0.008274 |
def _handleAuth(fn):
''' Decorator to re-try API calls after asking the user for authentication. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
# if yotta is being run noninteractively, then we never retry, but we
# do call auth.authorizeUser, so that a login URL can be displayed:
... | 0.001759 |
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
"""
Bootstrap plot on mean, median and mid-range statistics.
The bootstrap plot is used to estimate the uncertainty of a statistic
by relaying on random sampling with replacement [1]_. This function will
generate bootstrapping plot... | 0.000334 |
def reset(self, required=False):
"""
Perform a reset and check for presence pulse.
:param bool required: require presence pulse
"""
reset = self._ow.reset()
if required and reset:
raise OneWireError("No presence pulse found. Check devices and wiring.")
... | 0.008876 |
def prune_old(self):
"""
Removes the directories that are older than a certain date.
"""
path = self.pubdir
dirmask = self.dirmask
expire = self.expire
expire_limit = int(time.time()) - (86400 * expire)
logger.info('Pruning directories older than %d days'... | 0.003067 |
def star(component, **kwargs):
"""
Create parameters for a new star.
Generally, this will be used as an input to the kind argument in
:meth:`phoebe.frontend.bundle.Bundle.add_component`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.p... | 0.006173 |
def get_KE_constraints(self):
"""Get linear constraints on KE matrix.
"""
C2 = np.eye(self.m)
C2 = C2[:self.m - 2, :]
to_be_deleted = []
for idx_vij_1 in range(self.m - 2):
idx_vij_2 = idx_vij_1 + 1
C2[idx_vij_1, idx_vij_2] = -1
i1 = np... | 0.004205 |
def occurrence_halved_fingerprint(
word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG
):
"""Return the occurrence halved fingerprint.
This is a wrapper for :py:meth:`OccurrenceHalved.fingerprint`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number... | 0.000993 |
def compute_offset_ncc(dem1, dem2, pad=(9,9), prefilter=False, plot=False):
"""Compute horizontal offset between input rasters using normalized cross-correlation (NCC) method
"""
#Apply edge detection filter up front - improves results when input DEMs are same resolution
if prefilter:
print("A... | 0.01437 |
def get_cluster_name(self):
"""
Name identifying this RabbitMQ cluster.
"""
return self._get(
url=self.url + '/api/cluster-name',
headers=self.headers,
auth=self.auth
) | 0.008197 |
def cholesky(A, sparse=True, verbose=True):
"""
Choose the best possible cholesky factorizor.
if possible, import the Scikit-Sparse sparse Cholesky method.
Permutes the output L to ensure A = L.H . L
otherwise defaults to numpy's non-sparse version
Parameters
----------
A : array-like... | 0.001692 |
def animate(self, seq_name):
"""
Returns a generator which "executes" an animation sequence for the given
``seq_name``, inasmuch as the next frame for the given animation is
yielded when requested.
:param seq_name: The name of a previously defined animation sequence.
:ty... | 0.00265 |
def replace_line_magic(source, magic, template='{line}'):
"""
Given a cell's source, replace line magics using a formatting
template, where {line} is the string that follows the magic.
"""
filtered = []
for line in source.splitlines():
if line.strip().startswith(magic):
subst... | 0.002016 |
def t_INITIAL_NEWLINE(self, newline_token):
r'\n+'
newline_token.lexer.lineno += newline_token.value.count('\n')
dent_tokens = self._create_tokens_for_next_line_dent(newline_token)
if dent_tokens:
dent_tokens.tokens.insert(0, newline_token)
return dent_tokens
... | 0.005525 |
def _convert_name(self, name):
"""Convert ``name`` to int if it looks like an int.
Otherwise, return it as is.
"""
if re.search('^\d+$', name):
if len(name) > 1 and name[0] == '0':
# Don't treat strings beginning with "0" as ints
return name
... | 0.008152 |
def _run_gvcfgenotyper(data, region, vrn_files, out_file):
"""Run gvcfgenotyper on a single gVCF region in input file.
"""
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
input_file = "%s-inputs.txt" % utils.splitext_plus(tx_out_file)[0]
... | 0.004412 |
def init(self):
"""Init the connection to the ES server."""
if not self.export_enable:
return None
self.index='{}-{}'.format(self.index, datetime.utcnow().strftime("%Y.%m.%d"))
template_body = {
"mappings": {
"glances": {
"dynamic_templat... | 0.00494 |
def saveWeights(sim):
''' Save the weights for each plastic synapse '''
with open(sim.weightsfilename,'w') as fid:
for weightdata in sim.allWeights:
fid.write('%0.0f' % weightdata[0]) # Time
for i in range(1,len(weightdata)): fid.write('\t%0.8f' % weightdata[i])
fid.w... | 0.015504 |
def related_linkage_state(self, state_id):
""" TODO: document
"""
related_transitions = {'external': {'ingoing': [], 'outgoing': []},
'internal': {'enclosed': [], 'ingoing': [], 'outgoing': []}}
related_data_flows = {'external': {'ingoing': [], 'outgoing':... | 0.005447 |
def gfm(text):
"""Processes Markdown according to GitHub Flavored Markdown spec."""
extractions = {}
def extract_pre_block(matchobj):
match = matchobj.group(0)
hashed_match = hashlib.md5(match.encode('utf-8')).hexdigest()
extractions[hashed_match] = match
result = "{gfm-extr... | 0.00922 |
def query(song_name):
"""CLI:
$ iquery -l song_name
"""
r = requests_get(SONG_SEARCH_URL.format(song_name))
try:
# Get the first result.
song_url = re.search(r'(http://www.xiami.com/song/\d+)', r.text).group(0)
except AttributeError:
exit_after_echo(SONG_NOT_FOUND)
... | 0.00578 |
def head(self, msgid_article=None):
"""HEAD command.
"""
args = None
if msgid_article is not None:
args = utils.unparse_msgid_article(msgid_article)
code, message = self.command("HEAD", args)
if code != 221:
raise NNTPReplyError(code, message)
... | 0.005236 |
def get_release_revision(self, project, release_id, definition_snapshot_revision, **kwargs):
"""GetReleaseRevision.
Get release for a given revision number.
:param str project: Project ID or project name
:param int release_id: Id of the release.
:param int definition_snapshot_rev... | 0.005502 |
def import_data_object_to_graph(diagram_graph, process_id, process_attributes, data_object_element):
"""
Adds to graph the new element that represents BPMN data object.
Data object inherits attributes from FlowNode. In addition, an attribute 'isCollection' is added to the node.
:param d... | 0.009031 |
def _get_checksum():
"""
Get the checksum of the RPM Database.
Returns:
hexdigest
"""
digest = hashlib.sha256()
with open(RPM_PATH, "rb") as rpm_db_fh:
while True:
buff = rpm_db_fh.read(0x1000)
if not buff:
break
digest.update(... | 0.002817 |
def stop(self, **kwargs):
"""
Stops a container. Similar to the ``docker stop`` command.
Args:
timeout (int): Timeout in seconds to wait for the container to
stop before sending a ``SIGKILL``. Default: 10
Raises:
:py:class:`docker.errors.APIError... | 0.004587 |
def _invert_dictionary(self, d):
"""Invert a dictionary.
"""
inv_dict = {}
for k, v in d.items():
inv_dict[v] = inv_dict.get(v, [])
inv_dict[v] += [k]
return inv_dict | 0.008621 |
def _solve_location_param(self):
"""
We're lazy here and simply iterate to find the location parameter such that growth_curve(0.5)=1.
"""
params = copy.copy(self.params)
del params['loc']
f = lambda location: self.distr_f.ppf(0.5, loc=location, **params) - 1
retu... | 0.011429 |
def cart2pol(x, y):
"""Cartesian to Polar coordinates conversion."""
theta = np.arctan2(y, x)
rho = np.hypot(x, y)
return theta, rho | 0.006757 |
def line_input(*args, **kwargs):
'''
Get a single line of input as a string from a textfield
'''
line_input = wtforms.TextField(*args, **kwargs)
line_input.input_type = 'line'
return line_input | 0.004608 |
def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
ge... | 0.002048 |
def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
'loadavg': ['all'],
'cpustats': ['all'],
'meminfo': ['all'],
'vmstats': ['all']... | 0.001264 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.