text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def fa(a, b, alpha=2):
"""Returns the factor of 'alpha' (2 or 5 normally)
"""
return np.sum((a > b / alpha) & (a < b * alpha), dtype=float) / len(a) * 100 | 0.012048 |
def _trace_summary(self):
"""
Summarizes the trace of values used to update the DynamicArgs
and the arguments subsequently returned. May be used to
implement the summary method.
"""
for (i, (val, args)) in enumerate(self.trace):
if args is StopIteration:
... | 0.013514 |
def idle_task(self):
'''called in idle time'''
try:
data = self.port.recv(1024) # Attempt to read up to 1024 bytes.
except socket.error as e:
if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK ]:
return
raise
try:
self.send_rtc... | 0.012136 |
def new_from_files(self, basepath, basename, repo, \
bohrs=False, \
software=_E_SW.ORCA, \
repo_clobber=False, **kwargs):
""" Initialize with data from files.
"""
# Imports
import os
from os import path as osp
... | 0.016089 |
def render_formset_errors(formset, **kwargs):
"""
Render formset errors to a Bootstrap layout
"""
renderer_cls = get_formset_renderer(**kwargs)
return renderer_cls(formset, **kwargs).render_errors() | 0.004587 |
def get_checks(self, target_type, tags=None, skips=None):
"""
Get all checks for given type/tags.
:param skips: list of str
:param target_type: TargetType class
:param tags: list of str
:return: list of check instances
"""
skips = skips or []
resu... | 0.00511 |
def _connect(self):
"""Connect to the serial port."""
try:
while True:
_LOGGER.info('Trying to connect to %s', self.port)
try:
yield from serial_asyncio.create_serial_connection(
self.loop, lambda: self.protocol, sel... | 0.002323 |
def wait(self, method, *args):
"""
Call a method on the zombie.js Browser instance and wait on a callback.
:param method: the method to call, e.g., html()
:param args: one of more arguments for the method
"""
methodargs = encode_args(args, extra=True)
js = """
... | 0.004938 |
def items(self, view=None, prefetch=None, cache=True):
""" Get list of download items.
@param view: Name of the view.
@param prefetch: OPtional list of field names to fetch initially.
@param cache: Cache items for the given view?
"""
# TODO: Cache should be b... | 0.004286 |
def GetCachedPattern(self, patternId: int, cache: bool):
"""
Get a pattern by patternId.
patternId: int, a value in class `PatternId`.
Return a pattern if it supports the pattern else None.
cache: bool, if True, store the pattern for later use, if False, get a new pattern by `sel... | 0.003472 |
def unparse(self, dn, record):
"""Write an entry or change record to the output file.
:type dn: string
:param dn: distinguished name
:type record: Union[Dict[string, List[string]], List[Tuple]]
:param record: Either a dictionary holding an entry or a list of
additi... | 0.00266 |
def get_wxa_code(self,
path,
width=430,
auto_color=False,
line_color={"r": "0", "g": "0", "b": "0"},
is_hyaline=False):
"""
创建小程序码(接口A: 适用于需要的码数量较少的业务场景)
详情请参考
https://mp.weixin.qq.co... | 0.010703 |
def _ip_assigned(self):
"""Check if IP prefix is assigned to loopback interface.
Returns:
True if IP prefix found assigned otherwise False.
"""
output = []
cmd = [
'/sbin/ip',
'address',
'show',
'dev',
self... | 0.000699 |
def twosided_2_centerdc(data):
"""Convert a two-sided PSD to a center-dc PSD"""
N = len(data)
# could us int() or // in python 3
newpsd = np.concatenate((cshift(data[N//2:], 1), data[0:N//2]))
newpsd[0] = data[-1]
return newpsd | 0.003984 |
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the... | 0.006192 |
async def read(self, n=None):
"""Read all content
"""
if self._streamed:
return b''
buffer = []
async for body in self:
buffer.append(body)
return b''.join(buffer) | 0.008511 |
def balance_ss_model(F,L,Qc,H,Pinf,P0,dF=None,dQc=None,dPinf=None,dP0=None):
"""
Balances State-Space model for more numerical stability
This is based on the following:
dx/dt = F x + L w
y = H x
Let T z = x, which gives
dz/dt = inv(T) F T z + inv(T) L w
y = H T z
"""... | 0.021016 |
def recalculate_extents(self):
"""Adjust x, y, cx, and cy to incorporate all contained shapes.
This would typically be called when a contained shape is added,
removed, or its position or size updated.
This method is recursive "upwards" since a change in a group shape
can change... | 0.002967 |
def update_trigger(self, trigger):
"""
Updates on the Alert API the trigger record having the ID of the specified Trigger object: the remote record is
updated with data from the local Trigger object.
:param trigger: the Trigger with updated data
:type trigger: `pyowm.alertapi30.... | 0.003922 |
def call(self, identifier, *args, **kwargs):
""" Call the named function with provided arguments
You can pass a custom JSON encoder by passing it in the encoder
keyword only argument.
"""
encoder = kwargs.get('encoder', None)
timeout = kwargs.get('timeout', 0)
ma... | 0.005119 |
def quantity_spec_string(name, quantity_dict):
'''
Returns a quantity specification for docstrings.
Example
-------
>>> quantity_spec_string('Tv')
>>> 'Tv : float or ndarray\n Data for virtual temperature.'
'''
if name not in quantity_dict.keys():
raise ValueError('{0} not present in quantity_d... | 0.001988 |
def initial_state(self, batch_size, dtype=tf.float32, trainable=False,
trainable_initializers=None, trainable_regularizers=None,
name=None):
"""Builds the default start state tensor of zeros.
Args:
batch_size: An int, float or scalar Tensor representing the batch s... | 0.004477 |
def AgregarReceptor(self, cod_caracter, **kwargs):
"Agrego los datos del receptor a la liq."
d = {'codCaracter': cod_caracter}
self.solicitud['receptor'].update(d)
return True | 0.009662 |
def _handle_actiongeturl(self, _):
"""Handle the ActionGetURL action."""
obj = _make_object("ActionGetURL")
obj.UrlString = self._get_struct_string()
obj.TargetString = self._get_struct_string()
yield obj | 0.008197 |
def get_source(self, spec, row):
""" Sources can be specified as plain strings or as a reference to a column. """
value = self.get_value({'column': spec.get('source_url_column')}, row)
if value is not None:
return value
return spec.get('source_url') | 0.010239 |
def _combine_sets(self, sets, final_set):
"""
Given a list of set, combine them to create the final set that will be
used to make the final redis call.
If we have a least a sorted set, use zinterstore insted of sunionstore
"""
if self._has_sortedsets:
self.cls... | 0.005941 |
def _find_form_xobject_images(pdf, container, contentsinfo):
"""Find any images that are in Form XObjects in the container
The container may be a page, or a parent Form XObject.
"""
if '/Resources' not in container:
return
resources = container['/Resources']
if '/XObject' not in resour... | 0.0009 |
def _build_service_livestate(self, host_name, service_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for a service livestate
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
Create an... | 0.001674 |
def run(
command,
timeout=None,
debug=False,
stdin=None,
print_stdout=True,
print_stderr=True,
callback_stdout=None,
callback_stderr=None,
environment=None,
environment_override=None,
win32resolve=True,
working_directory=None,
):
"""
Run an external process.
... | 0.001354 |
def gf_lehmann(eig_e, eig_states, d_dag, beta, omega, d=None):
"""Outputs the lehmann representation of the greens function
omega has to be given, as matsubara or real frequencies"""
ew = np.exp(-beta*eig_e)
zet = ew.sum()
G = np.zeros_like(omega)
basis_create = np.dot(eig_states.T, d_dag.do... | 0.001486 |
def urlread(url, encoding='utf8'):
"""
Read the content of an URL.
Parameters
----------
url : str
Returns
-------
content : str
"""
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
response = urlopen(url)
conte... | 0.002513 |
def set_priority(self, priority):
""" Set Screen Priority Class """
if priority in ["hidden", "background", "info", "foreground", "alert", "input"]:
self.priority = priority
self.server.request("screen_set %s priority %s" % (self.ref, self.priority)) | 0.013746 |
def InitializeNoPrompt(config=None,
external_hostname = None,
admin_password = None,
mysql_hostname = None,
mysql_port = None,
mysql_username = None,
mysql_password = None,
... | 0.012003 |
def find_packages_requirements_dists(pkg_names, working_set=None):
"""
Return the entire list of dependency requirements, reversed from the
bottom.
"""
working_set = working_set or default_working_set
requirements = [
r for r in (Requirement.parse(req) for req in pkg_names)
if w... | 0.002469 |
def persist_database(metamodel, path, mode='w'):
'''
Persist all instances, class definitions and association definitions in a
*metamodel* by serializing them and saving to a *path* on disk.
'''
with open(path, mode) as f:
for kind in sorted(metamodel.metaclasses.keys()):
metacla... | 0.002742 |
def catch_end_signal(self, signum, frame):
"""
When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible.
"""
if self.end_signal_caught:
self.log('Previous signal caught, will end soon')
return
... | 0.006424 |
def make_redirect_url(self, path_info, query_args=None, domain_part=None):
"""Creates a redirect URL.
:internal:
"""
suffix = ''
if query_args:
suffix = '?' + self.encode_query_args(query_args)
return str('%s://%s/%s%s' % (
self.url_scheme,
... | 0.003478 |
def merge_split_alignments(data):
"""Merge split BAM inputs generated by common workflow language runs.
"""
data = utils.to_single_data(data)
data = _merge_align_bams(data)
data = _merge_hla_fastq_inputs(data)
return [[data]] | 0.004016 |
def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date | 0.007299 |
def td_waveform_to_fd_waveform(waveform, out=None, length=None,
buffer_length=100):
""" Convert a time domain into a frequency domain waveform by FFT.
As a waveform is assumed to "wrap" in the time domain one must be
careful to ensure the waveform goes to 0 at both "bo... | 0.001719 |
def hardware_info():
"""
Returns basic hardware information about the computer.
Gives actual number of CPU's in the machine, even when hyperthreading is
turned on.
Returns
-------
info : dict
Dictionary containing cpu and memory information.
"""
try:
if sys.platfor... | 0.00315 |
def _check_env_var(envvar: str) -> bool:
"""Check Environment Variable to verify that it is set and not empty.
:param envvar: Environment Variable to Check.
:returns: True if Environment Variable is set and not empty.
:raises: KeyError if Environment Variable is not set or is empty.
.. versionad... | 0.001618 |
def chunk(self, size="150", axis=None, padding=None):
"""
Chunks records of a distributed array.
Chunking breaks arrays into subarrays, using an specified
size of chunks along each value dimension. Can alternatively
specify an average chunk byte size (in kilobytes) and the size ... | 0.003484 |
def _make_interpolation_node(self, tag_type, tag_key, leading_whitespace):
"""
Create and return a non-section node for the parse tree.
"""
# TODO: switch to using a dictionary instead of a bunch of ifs and elifs.
if tag_type == '!':
return _CommentNode()
if... | 0.005109 |
def is_running(self, family: str) -> bool:
"""Check if an analysis is currently running/pending for a family."""
latest_analysis = self.analyses(family=family).first()
return latest_analysis and latest_analysis.status in TEMP_STATUSES | 0.007752 |
def _send_event_to_project(self, project_id, action, event):
"""
Send an event to all the client listening for notifications for
this project
:param project: Project where we need to send the event
:param action: Action name
:param event: Event to send
"""
... | 0.003802 |
def headerlist(self):
""" WSGI conform list of (header, value) tuples. """
if 'Content-Type' not in self.headers:
self.headers.add_header('Content-Type', self.default_content_type)
if self._cookies:
for c in self._cookies.values():
self.headers.add_header(... | 0.005168 |
def partition_loci(self,verbose=False):
""" break the locus up into unconnected loci
:return: list of loci
:rtype: TranscriptLoci[]
"""
self.g.merge_cycles()
#sys.stderr.write(self.g.get_report()+"\n")
gs = self.g.partition_graph(verbose=verbose)
tls = [] # makea list of transcript loci... | 0.019002 |
def traverse(self):
"""Traverse proposal kernel"""
if self.verbose > 1:
print_('\t' + self._id + ' Running Traverse proposal kernel')
# Mask for values to move
phi = self.phi
theta = self.traverse_theta
# Calculate beta
if (random() < (theta - 1) /... | 0.003219 |
def order_by(self, *field_names):
"""
Change translatable field names in an ``order_by`` argument
to translation fields for the current language.
"""
if not self._rewrite:
return super(MultilingualQuerySet, self).order_by(*field_names)
new_args = []
fo... | 0.004158 |
def get_ipv4_or_ipv6(self, ip):
"""
Get a Ipv4 or Ipv6 by IP
:param ip: IPv4 or Ipv6. 'xxx.xxx.xxx.xxx or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx'
:return: Dictionary with the following structure:
::
{'ips': [{'oct4': < oct4 >, 'oct2': < oct2 >, 'oct3': < oct3 >,
... | 0.005124 |
def set_energy(self, spins, target_energy):
"""Set the energy of Theta with spins fixed to target_energy.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
target_energy (float): The desired energy for Theta with spins fixed.
Notes:
Add... | 0.006198 |
def find_next_character(code, position, char):
"""Find next char and return its first and last positions"""
end = LineCol(code, *position)
while not end.eof and end.char() in WHITESPACE:
end.inc()
if not end.eof and end.char() == char:
return end.tuple(), inc_tuple(end.tuple())
retu... | 0.003003 |
def from_dict(config):
'''
Instantiate a new ProxyConfig from a dictionary that represents a
client configuration, as described in `the documentation`_.
.. _the documentation:
https://docs.docker.com/network/proxy/#configure-the-docker-client
'''
return Proxy... | 0.003945 |
def transform_request(self, orig_request, params, method_config):
"""Transforms orig_request to apiserving request.
This method uses orig_request to determine the currently-pending request
and returns a new transformed request ready to send to the backend. This
method accepts a rest-style or RPC-style... | 0.000962 |
def get_issues_by_resource(resource_id, table):
"""Get all issues for a specific job."""
v1_utils.verify_existence_and_get(resource_id, table)
# When retrieving the issues for a job, we actually retrieve
# the issues attach to the job itself + the issues attached to
# the components the job has be... | 0.000458 |
def _resolve_indirect_inner(maybe_idict):
"""Resolve the contents an indirect dictionary (containing promises) to produce
a dictionary actual values, including merging multiple sources into a
single input.
"""
if isinstance(maybe_idict, IndirectDict):
result = {}
for key, value in l... | 0.003478 |
async def execute_insert(
self, sql: str, parameters: Iterable[Any] = None
) -> Optional[sqlite3.Row]:
"""Helper to insert and get the last_insert_rowid."""
if parameters is None:
parameters = []
return await self._execute(self._execute_insert, sql, parameters) | 0.009709 |
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
if self.masked_median is None:
grand_mean_file = self.file.path
grand_mean_img = nib.load(grand_mean_file)
grand_mean_data = grand_mean_img.get_data()
... | 0.002139 |
def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str = 'git remote prune origin'
# Attempt to force all output to plain ascii english, which is what some parsing code
# may expect.
#... | 0.002525 |
def error_info():
"""Return information about failed tasks."""
worker = global_worker
worker.check_connected()
return (global_state.error_messages(driver_id=worker.task_driver_id) +
global_state.error_messages(driver_id=DriverID.nil())) | 0.003788 |
def default_security_rule_get(name, security_group, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a default security rule within a security group.
:param name: The name of the security rule to query.
:param security_group: The network security group containing the
... | 0.002333 |
def _parse_names_dict(feature_names):
"""Helping function of `_parse_feature_names` that parses a dictionary of feature names."""
feature_collection = OrderedDict()
for feature_name, new_feature_name in feature_names.items():
if isinstance(feature_name, str) and (isinstance(new_f... | 0.007229 |
def fit_shifts(xy, uv):
""" Performs a simple fit for the shift only between
matched lists of positions 'xy' and 'uv'.
Output: (same as for fit_arrays)
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough ob... | 0.008226 |
def index(self, value):
"""Return the 0-based position of integer `value` in
the sequence this range represents."""
try:
diff = value - self._start
except TypeError:
raise ValueError('%r is not in range' % value)
quotient, remainder = divmod(diff, self._st... | 0.004274 |
def state_push(self):
"""
Push the state of all generators
"""
super(Composite,self).state_push()
for gen in self.generators:
gen.state_push() | 0.015464 |
def nsname(self, uri: Union[str, URIRef]) -> str:
"""
Return the 'ns:name' format of URI
:param uri: URI to transform
:return: nsname format of URI or straight URI if no mapping
"""
uri = str(uri)
nsuri = ""
prefix = None
for pfx, ns in self:
... | 0.005474 |
def _get_instance(self):
"""Retrieve instance matching instance_id."""
try:
instance = self.compute_driver.ex_get_node(
self.running_instance_id,
zone=self.region
)
except ResourceNotFoundError as e:
raise GCECloudException(
... | 0.003968 |
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 256
return hparams | 0.027027 |
def parse_options(arguments=None):
""" Reads command-line arguments
>>> parse_options('--indent-comments')
"""
if arguments is None:
arguments = sys.argv[1:]
if isinstance(arguments, str):
arguments = arguments.split()
if isinstance(arguments, argparse.Namespace):
return... | 0.002266 |
def get_username(self):
"""Get a username formatted for a specific token version."""
_from = self.auth_context['from']
if self.token_version == 1:
return '{0}'.format(_from)
elif self.token_version == 2:
_user_type = self.auth_context['user_type']
retu... | 0.004505 |
def allocation_explain(self, body=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-allocation-explain.html>`_
:arg body: The index, shard, and primary flag to explain. Empty means
'explain the first unassigned shard'
:arg inclu... | 0.004601 |
def _reset(self):
"""
Initializes the :class:`Harvester` object. Once you reset the
:class:`Harvester` object, all allocated resources, including buffers
and remote device, will be released.
:return: None.
"""
#
for ia in self._ias:
ia._destro... | 0.003067 |
def main():
"Boots up the command line tool"
logging.captureWarnings(True)
args = build_parser().parse_args()
# Configure logging
args.setup_logging(args)
# Dispatch into the appropriate subcommand function.
try:
return args.func(args)
except SystemExit:
raise
except:... | 0.004926 |
def scopusParser(scopusFile):
"""Parses a scopus file, _scopusFile_, to extract the individual lines as [ScopusRecords](../classes/ScopusRecord.html#metaknowledge.scopus.ScopusRecord).
A Scopus file is a csv (Comma-separated values) with a complete header, see [`scopus.scopusHeader`](#metaknowledge.scopus) for... | 0.009932 |
def find(self, pattern):
"""
:param pattern: REGULAR EXPRESSION TO MATCH NAME (NOT INCLUDING PATH)
:return: LIST OF File OBJECTS THAT HAVE MATCHING NAME
"""
output = []
def _find(dir):
if re.match(pattern, dir._filename.split("/")[-1]):
output... | 0.004193 |
def find_or_build(self, constructor, props):
"""Looks for a model that matches the given dictionary constraints. If it is not found, a new
model of the given type is constructed and returned.
"""
model = self.find_model(constructor, props)
return model or constructor(**props) | 0.006757 |
def recruit(self, n=1):
"""Generate experiemnt URLs and print them to the console."""
logger.info("Recruiting {} CLI participants".format(n))
urls = []
template = "{}/ad?recruiter={}&assignmentId={}&hitId={}&workerId={}&mode={}"
for i in range(n):
ad_url = template.fo... | 0.004444 |
def cli(ctx, group_id, users=None):
"""Update the group's admins
Output:
dictionary of group information
"""
return ctx.gi.groups.update_group_admin(group_id, users=users) | 0.005291 |
def getPinProperties(cardConnection, featureList=None, controlCode=None):
""" return the PIN_PROPERTIES structure
@param cardConnection: L{CardConnection} object
@param featureList: feature list as returned by L{getFeatureRequest()}
@param controlCode: control code for L{FEATURE_IFD_PIN_PROPERTIES}
... | 0.00113 |
def restart(self):
"""Restart the debugger after source code changes."""
_module_finder.reset()
linecache.checkcache()
for module_bpts in self.breakpoints.values():
module_bpts.reset() | 0.008772 |
def json_numpy_obj_hook(dct):
"""Decodes a previously encoded numpy ndarray with proper shape and dtype.
And decompresses the data with blosc
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarray__' in dct:
... | 0.001145 |
def generate_megaman_data(sampling=2):
"""Generate 2D point data of the megaman image"""
data = get_megaman_image()
x = np.arange(sampling * data.shape[1]) / float(sampling)
y = np.arange(sampling * data.shape[0]) / float(sampling)
X, Y = map(np.ravel, np.meshgrid(x, y))
C = data[np.floor(Y.max(... | 0.002433 |
def reroute(self, body=None, params=None):
"""
Explicitly execute a cluster reroute allocation command including specific commands.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-reroute.html>`_
:arg body: The definition of `commands` to perform (`move`, `cance... | 0.006003 |
def render_archive(entries):
"""Creates the archive page"""
context = GLOBAL_TEMPLATE_CONTEXT.copy()
context['entries'] = entries
_render(context, 'archive_index.html',
os.path.join(CONFIG['output_to'], 'archive/index.html')), | 0.003937 |
def _respawn(self):
"""
Pick a random location for the star making sure it does
not overwrite an existing piece of text.
"""
self._cycle = randint(0, len(self._star_chars))
(height, width) = self._screen.dimensions
while True:
self._x = randint(0, widt... | 0.003899 |
def install_logger(logger=None, module=None):
"""
Installs given logger in given module or default logger in caller introspected module.
:param logger: Logger to install.
:type logger: Logger
:param module: Module.
:type module: ModuleType
:return: Logger.
:rtype: Logger
"""
lo... | 0.005517 |
def d2logpdf_dlink2(self, link_f, y, Y_metadata=None):
"""
Hessian at y, given link_f, w.r.t link_f.
i.e. second derivative logpdf at y given link(f_i) link(f_j) w.r.t link(f_i) and link(f_j)
The hessian will be 0 unless i == j
.. math::
\\frac{d^{2} \\ln p(y_{i}|\... | 0.006616 |
def _execute(self, endpoint, database, query, default_timeout, properties=None):
"""Executes given query against this client"""
request_payload = {"db": database, "csl": query}
if properties:
request_payload["properties"] = properties.to_json()
request_headers = {
... | 0.004052 |
def adjust_mod_previous(self, holidays_obj=None):
"""
ajusts to Business Day Convention "Modified Preceding" (not in 2006 ISDA Definitons).
"""
month = self.month
new = BusinessDate.adjust_previous(self, holidays_obj)
if month != new.month:
new = BusinessDate.... | 0.007653 |
def to_json(self):
"""Short cut for JSON response service data.
Returns:
Dict that implements JSON interface.
"""
web_resp = collections.OrderedDict()
web_resp['status_code'] = self.status_code
web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code... | 0.00432 |
def _setup(self, action, line):
''' replace the command name from the group, alert the user of content,
and clean up empty spaces
'''
bot.debug('[in] %s' % line)
# Replace ACTION at beginning
line = re.sub('^%s' % action, '', line)
# Handle continuation lin... | 0.006 |
def log_metric(self, name, value, unit=None, global_step=None, extras=None):
"""Log the benchmark metric information to local file.
Currently the logging is done in a synchronized way. This should be updated
to log asynchronously.
Args:
name: string, the name of the metric to log.
value: n... | 0.006588 |
def poisson(x,
layer_fn=tf.compat.v1.layers.dense,
log_rate_fn=lambda x: x,
name=None):
"""Constructs a trainable `tfd.Poisson` distribution.
This function creates a Poisson distribution parameterized by log rate.
Using default args, this function is mathematically equivalent ... | 0.000914 |
def _get_import_name(importnode, modname):
"""Get a prepared module name from the given import node
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
for debugging. Otherwise, the initial module name
is returned unchanged.
"""
if isi... | 0.001608 |
def _set_ignored_version(version):
"""
Private helper function that writes the most updated
API version that was ignored by a user in the app
:param version: Most recent ignored API update
"""
data = {'version': version}
with open(filepath, 'w') as data_file:
json.dump(data, data_fil... | 0.003106 |
def counts_to_dicts(df, column):
"""
convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster
"""
# index where there are counts and they aren't null
d = df[column].apply(lambda c: pd.notnull(c) and len(c[0]) > 0)
return df.loc[d, column].... | 0.00551 |
def get(key, **kwargs):
'''
Gets details for a single, interpreted occurrence
:param key: [int] A GBIF occurrence key
:return: A dictionary, of results
Usage::
from pygbif import occurrences
occurrences.get(key = 1258202889)
occurrences.get(key = 1227768771)
occur... | 0.002179 |
def output(self, result):
"""
Adapts the result of a function based on the returns definition.
"""
if self.returns:
errors = None
try:
return self._adapt_result(result)
except AdaptErrors as e:
errors = e.errors
... | 0.003344 |
def dump(file_name, predictions=None, algo=None, verbose=0):
"""A basic wrapper around Pickle to serialize a list of prediction and/or
an algorithm on drive.
What is dumped is a dictionary with keys ``'predictions'`` and ``'algo'``.
Args:
file_name(str): The name (with full path) specifying wh... | 0.000929 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.