content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_unii_other_code(tree):
"""Extract the codes for other ingredients"""
unii_other_xpath = \
'//generalizedMaterialKind/code[@codeSystem="%s"]/@code' % UNII_OTHER_OID
return tree.getroot().xpath(unii_other_xpath) | 5,350,800 |
def initfunc(f):
"""
Decorator for initialization functions that should
be run exactly once.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
if wrapper.initialized:
return
wrapper.initialized = True
return f(*args, **kwargs)
wrapper.initialized = F... | 5,350,801 |
def edit_frame(frame):
"""edit frame to analyzable frame
rgb 2 gray
thresh frame color
bitwise color
Args
frame (ndarray): original frame from movie
Returns
work_frame (ndarray): edited frame
"""
work_frame = frame
work_frame = cv2.cvtColor(work_frame, cv2.COLOR... | 5,350,802 |
def manchester(bin_string):
"""
Applies the Manchester technique to a string of bits.
:param bin_string:
:type bin_string: str
:return:
:rtype: str
"""
signal_manager = Signal()
for bin_digit in bin_string:
if bin_digit == '0': # Generate +-
if signal_manager... | 5,350,803 |
def load_admin_cells(identifier: str) -> List[MultiPolygon]:
"""Loads the administrative region cells
Data is loaded from :py:const:`ADMIN_GEOJSON_TEMPLATE` ``% identifier``.
This is a wrapper function for :py:func:`load_polygons_from_json`.
Returns:
A list of the administrative region cells.
... | 5,350,804 |
def register_writer(format, cls=None):
"""Return a decorator for a writer function.
A decorator factory for writer functions.
A writer function should have at least the following signature:
``<class_name_or_generator>_to_<format_name>(obj, fh)``. `fh` is **always**
an open filehandle. This decorat... | 5,350,805 |
def get_downloadpath(user_id):
"""
find the download path
"""
path = settings.DOCUMENT_PATH + str(user_id) + '/'
if not os.path.isdir(path):
os.mkdir(path)
return path | 5,350,806 |
def lerp(a: mat33, b: mat33, t: float32) -> mat33:
"""
Linearly interpolate two values a and b using factor t, computed as ``a*(1-t) + b*t``
"""
... | 5,350,807 |
def genetic_fit_call(fit_directory):
"""genetic_fit_call(fit_directory)
Run a casm genetic algorithm fit. Assumes that the fit settings file already exists.
Args:
fit_directory (str): absolute path to the current genetic fit directory.
Returns:
none.
"""
os.chdir(fit_directory)... | 5,350,808 |
def accuracy(output, target, topk=1,axis=1,ignore_index=-100, exclude_mask=False):
"""Computes the precision@k for the specified values of k
prec1, prec5 = accuracy(output.data, target, topk=(1, 5))
"""
input_tensor=output.copy().detach()
target_tensor=target.copy().detach()
num_classes = int_sh... | 5,350,809 |
def jitter_over_thresh(x: xr.DataArray, thresh: str, upper_bnd: str) -> xr.DataArray:
"""Replace values greater than threshold by a uniform random noise.
Do not confuse with R's jitter, which adds uniform noise instead of replacing values.
Parameters
----------
x : xr.DataArray
Values.
t... | 5,350,810 |
def index_set_names(index, names, level=None, inplace=False):
"""
Set Index or MultiIndex name.
Able to set new names partially and by level.
Parameters
----------
names : label or list of label
Name(s) to set.
level : int, label or list of int or label, optional
If the ind... | 5,350,811 |
def test_SingleScaler_combine_intensities():
"""test combine intensities method"""
p, e, r = (generated_param(), generated_exp(), generated_refl_for_comb())
exp = create_scaling_model(p, e, r)
p.reflection_selection.method = "use_all"
scaler = SingleScaler(p, exp[0], r)
scaler.combine_intensitie... | 5,350,812 |
def get_critic(obs_dim: int) -> tf.keras.Model:
"""Get a critic that returns the expect value for the current state"""
observation = tf.keras.Input(shape=(obs_dim,), name='observation')
x = layers.Dense(64, activation='tanh')(observation)
x = layers.Dense(64, activation='tanh')(x)
value = layers.Den... | 5,350,813 |
def register_and_login_test_user(c):
"""
Helper function that makes an HTTP request to register a test user
Parameters
----------
c : object
Test client object
Returns
-------
str
Access JWT in order to use in subsequent tests
"""
c.post(
"/api/auth/regi... | 5,350,814 |
def get_ssh_challenge_token(account, appid, ip=None, vo='def'):
"""
Get a challenge token for subsequent SSH public key authentication.
The challenge token lifetime is 5 seconds.
:param account: Account identifier as a string.
:param appid: The application identifier as a string.
:param ip: IP... | 5,350,815 |
def rootpath_capacity_exceeded(rootpath,newSize):
"""
Return True if rootpath is already allocated to the extent
it cannot accomadate newSize, otherwise return False
"""
vols_in_rootpath = Volume.objects.filter(root_path=rootpath)
rootpathallocsum = 0
if vols_in_rootpath.count() > 0:
... | 5,350,816 |
def user_token(user: str) -> str:
"""
Authorize this request with the GitHub app set by the 'app_id' and
'private_key' environment variables.
1. Get the installation ID for the user that has installed the app
2. Request a new token for that user
3. Return it so it can be used in future API reque... | 5,350,817 |
def file_exists(path):
"""
Return True if the file from the path exists.
:param path: A string containing the path to a file.
:return: a boolean - True if the file exists, otherwise False
"""
return isfile(path) | 5,350,818 |
def _static_to_href(pathto: Callable, favicon: Dict[str, str]) -> Dict[str, str]:
"""If a ``static-file`` is provided, returns a modified version of the icon
attributes replacing ``static-file`` with the correct ``href``.
If both ``static-file`` and ``href`` are provided, ``href`` will be ignored.
"""
... | 5,350,819 |
def test_IndentList_two():
"""Test indent with two spaces."""
assert fmt.IndentList(2, ["abc", "d"]) == [" abc", " d"] | 5,350,820 |
def concatenate(tensor1, tensor2, axis=0):
"""
Basically a wrapper for torch.dat, with the exception
that the array itself is returned if its None or evaluates to False.
:param tensor1: input array or None
:type tensor1: mixed
:param tensor2: input array
:type tensor2: numpy.ndarray
:pa... | 5,350,821 |
def setKey(key, keytype):
""" if keytype is valid, save a copy of key accordingly
and check if the key is valid """
global _key, _keytype, FREE_API_KEY, PREMIUM_API_KEY
keytype = keytype.lower()
if keytype in ("f", "fr", "free"):
keytype = "free"
FREE_API_KEY = key
elif keyt... | 5,350,822 |
def sum_(obj):
"""Sum the values in the given iterable.
Different from the built-in summation function, the summation is based on
the first item in the iterable. Or a SymPy integer zero is created
when the iterator is empty.
"""
i = iter(obj)
try:
init = next(i)
except StopIt... | 5,350,823 |
def setup_s3_client(job_data):
"""Creates an S3 client
Uses the credentials passed in the event by CodePipeline. These
credentials can be used to access the artifact bucket.
:param job_data: The job data structure
:return: An S3 client with the appropriate credentials
"""
try:
key... | 5,350,824 |
def collect_operations(opts):
"""
Produce a list of operations to take.
Each element in the operations list is in the format:
(function, (arguments,), 'logging message')
"""
operations = []
#######################
# Destination directory
if os.path.exists(opts.dest_dir):
... | 5,350,825 |
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.):
"""
FROM KERAS
Pads each sequence to the same length:
the length of the longest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen.
Truncation happens off... | 5,350,826 |
def basic_pyxll_function_22(x, y, z):
"""if z return x, else return y"""
if z:
# we're returning an integer, but the signature
# says we're returning a float.
# PyXLL will convert the integer to a float for us.
return x
return y | 5,350,827 |
def job_hotelling(prob_label, tr, te, r, ni, n):
"""Hotelling T-squared test"""
with util.ContextTimer() as t:
htest = tst.HotellingT2Test(alpha=alpha)
test_result = htest.perform_test(te)
return {
'test_method': htest,
'test_result': test_result,
'time_se... | 5,350,828 |
def get(id: str):
"""Get a notebook."""
try:
ep = f"{notebook_ep}/{id}"
r = request("GET", ep, True)
check_response(r)
d = r.json()
res = d.get("result")
if res is None:
raise Exception("Data not received.")
# Notebook data
_id = res... | 5,350,829 |
def return_circle_aperature(field, mask_r):
"""Filter the circle aperature of a light field.
Filter the circle aperature of a light field.
Parameters
----------
field : Field
Input square field.
mask_r : float, from 0 to 1
Radius of a circle mask.
Returns
... | 5,350,830 |
def train(flags=None):
"""Train a seq2seq model on human motion"""
if flags is None:
flags = create_flags()
train_dir, summaries_dir = get_dirs(flags)
train_set, test_set, data_mean, data_std = read_qpos_data(flags.seq_length_in, flags.seq_length_out, flags.data_dir,
... | 5,350,831 |
def user_get():
"""
Get information from the database about an user, given his id. If there are
field names received in the body, only those will be queried. If no field is
provided, every field will be selected. The body should be a JSON object
following the schema:
{
"user_id": id,
... | 5,350,832 |
def get_data_file_args(args, language):
"""
For a interface, return the language-specific set of data file arguments
Args:
args (dict): Dictionary of data file arguments for an interface
language (str): Language of the testbench
Returns:
dict: Language-specific data file argume... | 5,350,833 |
def mqtt_publish_temperature_val():
"""Publish system temperature value in centigrades to MQTT data topic."""
message = round_temp(dev_system.temperature)
if mqtt.connected:
cfg_section = mqtt.GROUP_TOPICS
cfg_option = 'system_data_temp_val'
try:
mqtt.publish(message, cfg... | 5,350,834 |
def branch_exists(branch):
"""Return True if the branch exists."""
try:
run_git("rev-parse --verify {}".format(branch), quiet=True)
return True
except ProcessExecutionError:
return False | 5,350,835 |
def spectrum_like_noise(signal: numpy.ndarray,
*,
sampling_rate=40000,
keep_signal_amp_envelope=False,
low_pass_cutoff=50, # Hz
low_pass_order=6,
seed: int = 42,
... | 5,350,836 |
def check_string_capitalised(string):
""" Check to see if a string is in all CAPITAL letters. Boolean. """
return bool(re.match('^[A-Z_]+$', string)) | 5,350,837 |
def sample_zero_entries(edge_index, seed, num_nodes, sample_mult=1.0):
"""Obtain zero entries from a sparse matrix.
Args:
edge_index (tensor): (2, N), N is the number of edges.
seed (int): to control randomness
num_nodes (int): number of nodes in the graph
sample_mult (float): t... | 5,350,838 |
def add_wsl_outputs(model, blob_in, dim, prefix=''):
"""Add RoI classification and bounding box regression output ops."""
if cfg.WSL.CONTEXT:
fc8c, fc8d = add_wsl_context_outputs(model, blob_in, dim, prefix=prefix)
else:
# Box classification layer
fc8c = model.FC(
blob_in... | 5,350,839 |
def ped_file_parent_missing(fake_fs):
"""Return fake file system with PED file"""
content = textwrap.dedent(
"""
# comment
FAM II-1\tI-1\t0\t1\t2
FAM I-1 0\t0\t1\t1
"""
).strip()
fake_fs.fs.create_file("/test.ped", create_missing_dirs=True, contents=content)
return fak... | 5,350,840 |
def symlink_sysmeta_to_usermeta(headers):
"""
Helper function to translate from cluster-facing
X-Object-Sysmeta-Symlink-* headers to client-facing X-Symlink-* headers.
:param headers: request headers dict. Note that the headers dict
will be updated directly.
"""
for user_hdr, sysmeta_hd... | 5,350,841 |
def GettingAyah():
"""The code used to get an Ayah from the Quran every fixed time"""
while True:
ayah = random.randint(1, 6237)
url = f'http://api.alquran.cloud/v1/ayah/{ayah}'
res = requests.get(url)
if len(res.json()['data']['text']) <= 280:
return res.json()['data... | 5,350,842 |
def iterdecode(value):
"""
Decode enumerable from string presentation as a tuple
"""
if not value:
return tuple()
result = []
accumulator = u''
escaped = False
for c in value:
if not escaped:
if c == CHAR_ESCAPE:
escaped = True
... | 5,350,843 |
def run_resolution_filter(image=None, image_path=None, height=600, width=1000):
"""
This will take the image which is correctly rotated yolo output. Initially, We
are doing for driving licenses only, Will return 1 if the height and width
are greater than 700 and 1100 pixels else it will return 10002
:return:... | 5,350,844 |
def text_to_emotion(text):
"""
テキストから感情を推測して返す
Parameters
----------
text : string
テキスト
Returns
-------
{'magnitude','score'}
"""
client = language.LanguageServiceClient()
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT,
... | 5,350,845 |
def process_actions(list_response_json, headers, url, force_reset):
"""
If a policy does not exist on a given cluster find the right values
defined in qos_dict and apply them
"""
qos_dict = {}
# This dictionary sets the tiers and min/max/burst settings
qos_dict['tiers'] = {"bronze": [500, 50... | 5,350,846 |
def list_bundles(maxResults=None, nextToken=None):
"""
List all available bundles.
See also: AWS API Documentation
Exceptions
:example: response = client.list_bundles(
maxResults=123,
nextToken='string'
)
:type maxResults: integer
:param maxResults: Ma... | 5,350,847 |
def calculate_statistics(stats_table, vocab, period):
"""Calculate statistics for the provided vocabulary and add them to stats table.
Parameters
----------
stats_table: dict, required
The dictionary containing statistics.
vocab: iterable of str, required
The vocabulary for which to... | 5,350,848 |
def validate_ac_power(observation, values):
"""
Run a number of validation checks on a daily timeseries of AC power.
Parameters
----------
observation : solarforecastarbiter.datamodel.Observation
Observation object that the data is associated with
values : pandas.Series
Series of ... | 5,350,849 |
def partition(predicate, iterable):
"""Use `predicate` to partition entries into falsy and truthy ones.
Recipe taken from the official documentation.
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
t1, t2 = itertools.tee(iterable)
return (
six.moves.filterfalse(pr... | 5,350,850 |
def _download(url: str) -> bytes:
"""Download something from osu!web at `url`, returning the file contents."""
with _login() as sess:
resp = sess.get(f"{url}/download", headers={"Referer": url})
if not resp.ok:
raise ReplyWith("Sorry, a download failed.")
return resp.content | 5,350,851 |
def get_node(obj, path):
"""Retrieve a deep object based on a path. Return either a Wrapped instance if the deep object is not a node, or another type of object."""
subobj = obj
indices = []
for item in path:
try:
subobj = subobj[item]
except Exception as e:
indic... | 5,350,852 |
def karto(data):
"""Karto node subscriber method.
Sends the recieved karto node information to treatment method.
:param data: OccupancyGrid Data, containing map information and metadata like height, width or resulution of the map.
:type data: OccupancyGrid struct.
"""
global countkarto
countkarto=countkar... | 5,350,853 |
def without_bond_orders(gra):
""" resonance graph with maximum spin (i.e. no pi bonds)
"""
bnd_keys = list(bond_keys(gra))
# don't set dummy bonds to one!
bnd_ord_dct = bond_orders(gra)
bnd_vals = [1 if v != 0 else 0
for v in map(bnd_ord_dct.__getitem__, bnd_keys)]
bnd_ord_dc... | 5,350,854 |
def check_struc(d1, d2,
errors=[], level='wf'):
"""Recursively check struct of dictionary 2 to that of dict 1
Arguments
---------
d1 : dict
Dictionary with desired structure
d2 : dict
Dictionary with structre to check
errors : list of str, optional
Missin... | 5,350,855 |
def indexoflines(LFtop):
""" Determining selected line index of Gromacs compatible topology files """
file1 = open(LFtop, "r")
readline = file1.readlines()
lineindex = ["x", "x", "x"]
n = 0
for line in readline:
linelist = line.split()
if "atomtypes" in linelist:
lineindex[0] = n
n += 1
elif "molecule... | 5,350,856 |
def checkout_program(connection, name, destdir=None):
"""Download program sources"""
adt_program = sap.adt.Program(connection, name)
adt_program.fetch()
download_abap_source(name, adt_program, '.prog', destdir=destdir)
progdir, tpool = build_program_abap_attributes(adt_program)
dump_attribute... | 5,350,857 |
def print_details(field):
"""Print the definition of one field, in readable text"""
print(u"Name: {}".format(apiname(field)))
print(u"Label: {}".format(field["text"]))
print(u"ID: {}".format(field["id"]))
print(u"Type: {}".format(field["input_type"]))
if "tooltip" in... | 5,350,858 |
def onTrainingButtonPress(sid, data):
"""
onTrainingButtonPress(({'identifier': "-",'id': "-"})
The html interface calls this function when the user clicks any of the buttons that the html interface
was sent with the function getTrainingButtons(). The identifier is the identifier that was sent with
... | 5,350,859 |
def create_mock_github(user='octo-cat', private=False):
"""Factory for mock GitHub objects.
Example: ::
>>> github = create_mock_github(user='octocat')
>>> github.branches(user='octocat', repo='hello-world')
>>> [{u'commit': {u'sha': u'e22d92d5d90bb8f9695e9a5e2e2311a5c1997230',
... | 5,350,860 |
def get_args_string(args: argparse.Namespace) -> str:
"""
Creates a string summarising the argparse arguments.
:param args: parser.parse_args()
:return: String of the arguments of the argparse namespace.
"""
string = ''
if hasattr(args, 'experiment_name'):
string += f'{args.experime... | 5,350,861 |
def top_9(limit=21):
"""Vrni dano število knjig (privzeto 9). Rezultat je seznam, katerega
elementi so oblike [knjiga_id, avtor,naslov,slika] """
cur.execute(
"""SELECT book_id, authors, title, original_publication_year, average_rating,image_url
FROM books
ORDER BY average_rating DE... | 5,350,862 |
async def startup():
"""
Startup event.
Makes a temp folder to store the uploaded files.
"""
p_information("Starting app...")
if not os.path.exists(project_root / "static" / "temp"):
os.mkdir(project_root / "static" / "temp") | 5,350,863 |
def spm_dot_torch(X, x, dims_to_omit=None):
""" Dot product of a multidimensional array with `x` -- Pytorch version, using Tensor instances
@TODO: Instead of a separate function, this should be integrated with spm_dot so that it can either take torch.Tensors or nd.arrays
The dimensions in `dims_to_omit` wi... | 5,350,864 |
def inverseTranslateTaps(lowerTaps, pos):
"""Method to translate tap integer in range
[-lower_taps, raise_taps] to range [0, lowerTaps + raiseTaps]
"""
# Hmmm... is it this simle?
posOut = pos + lowerTaps
return posOut | 5,350,865 |
def GMLstring2points(pointstring):
"""Convert list of points in string to a list of points. Works for 3D points."""
listPoints = []
#-- List of coordinates
coords = pointstring.split()
#-- Store the coordinate tuple
assert(len(coords) % 3 == 0)
for i in range(0, len(coords), 3):
list... | 5,350,866 |
def run(command, conf=None, tutorial=False, less_data=False, pdb=False,
**args):
"""Main entry point for a direct call from Python
Example usage:
>>> from yam import run
>>> run(conf='conf.json')
:param command: if ``'create'`` the example configuration is created,
optionally the t... | 5,350,867 |
def set_(key, value, service=None, profile=None): # pylint: disable=W0613
"""
Set a key/value pair in the etcd service
"""
client = _get_conn(profile)
client.set(key, value)
return get(key, service, profile) | 5,350,868 |
def compute_cw_score_normalized(p, q, edgedict, ndict, params = None):
"""
Computes the common weighted normalized score between p and q
@param p -> A node of the graph
@param q -> Another node in the graph
@param edgedict -> A dictionary with key `(p, q)` and value `w`.
@param ndi... | 5,350,869 |
def prompt_user_friendly_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'de... | 5,350,870 |
def get_elapsed(df, monitored_field, prefix='elapsed_'):
"""
Cumulative counting across a sorted dataframe.
Given a particular field to monitor, this function will start tracking time since the
last occurrence of that field. When the field is seen again, the counter is set to zero.
Args:
df ... | 5,350,871 |
def refresh_git_config_contexts(repository_record, job_result, delete=False):
"""Callback function for GitRepository updates - refresh all ConfigContext records managed by this repository."""
if "extras.configcontext" in repository_record.provided_contents and not delete:
update_git_config_contexts(repo... | 5,350,872 |
def fuse(search: typing.Dict, filepath: str):
"""Build a JSON doc of your pages"""
with open(filepath, "w") as jsonfile:
return json.dump(
[x for x in _build_index(search, id_field="id")],
fp=jsonfile,
) | 5,350,873 |
def aggregate_gradients_using_copy_with_device_selection(
tower_grads, avail_devices, use_mean=True, check_inf_nan=False):
"""Aggregate gradients, controlling device for the aggregation.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner li... | 5,350,874 |
def ToOrdinal(value):
"""
Convert a numerical value into an ordinal number.
@param value: the number to be converted
"""
if value % 100//10 != 1:
if value % 10 == 1:
ordval = '{}st'.format(value)
elif value % 10 == 2:
ordval = '{}nd'.format(value)
elif... | 5,350,875 |
def compute_partition(num_list: List[int]):
"""Compute paritions that add up."""
solutions = []
for bits in helper.bitprod(len(num_list)):
iset = []
oset = []
for idx, val in enumerate(bits):
(iset.append(num_list[idx]) if val == 0 else
oset.append(num_list[idx])... | 5,350,876 |
def renumber(conllusent):
"""Fix non-contiguous IDs because of multiword tokens or removed tokens"""
mapping = {line[ID]: n for n, line in enumerate(conllusent, 1)}
mapping[0] = 0
for line in conllusent:
line[ID] = mapping[line[ID]]
line[HEAD] = mapping[line[HEAD]]
return conllusent | 5,350,877 |
def assign_project_locale_group_permissions(sender, **kwargs):
"""
Assign permissions group to a given ProjectLocale.
"""
if kwargs["raw"] or not kwargs["created"]:
return
instance = kwargs["instance"]
try:
assign_group_permissions(
instance, "translators", ["can_tr... | 5,350,878 |
def test_human_gene_has_rgd_references_cross_reference():
"""Test Human Gene has RGD References Cross Reference"""
query = """MATCH (g:Gene)--(cr:CrossReference)
WHERE g.primaryKey = 'HGNC:11204'
AND cr.crossRefType = 'gene/references'
AND cr.globalCross... | 5,350,879 |
def recall_at(target, scores, k):
"""Calculation for recall at k."""
if target in scores[:k]:
return 1.0
else:
return 0.0 | 5,350,880 |
def supports_dynamic_state() -> bool:
"""Checks if the state can be displayed with widgets.
:return: True if widgets available. False otherwise.
"""
return widgets is not None | 5,350,881 |
def create_partial_image_rdd_decoder(key_type):
"""Creates a partial, tuple decoder function.
Args:
value_type (str): The type of the value in the tuple.
Returns:
A partial :meth:`~geopyspark.protobufregistry.ProtoBufRegistry.image_rdd_decoder`
function that requires ``proto_bytes`... | 5,350,882 |
def to_json(simple_object):
"""
Serializes the ``simple_object`` to JSON using the EnhancedJSONEncoder above.
"""
return json.dumps(simple_object, cls=EnhancedJSONEncoder) | 5,350,883 |
def bootstrap_metadata():
""" Provides cluster metadata which includes security modes
"""
return _metadata_helper('bootstrap-config.json') | 5,350,884 |
def unique_slug(*, title: str, new_slug: str = None) -> str:
"""Create unique slug.
Args:
title: The text where the slug will be generate.
new_slug: Custom slug to hard code.
Returns:
The created slug or hard code slug
"""
if new_slug is None:
slug = slugify(title)... | 5,350,885 |
def dcg(r, k=None):
"""The Burges et al. (2005) version of DCG.
This is what everyone uses (except trec_eval)
:param r: results
:param k: cut-off
:return: sum (2^ y_i - 1) / log (i +2)
"""
result = sum([(pow(2, rel) - 1) / math.log(rank + 2, 2) for rank, rel in enumerate(r[:k])])
return... | 5,350,886 |
async def detect_objects(computervision_client, image_url):
"""Detect objects from a remote image"""
detect_objects_results_local = \
computervision_client.detect_objects(image_url)
return detect_objects_results_local.objects | 5,350,887 |
def test_data_analyst_cannot_have_region(data_analyst, region):
"""Test that an error will be thrown if a region is set on a data analyst user."""
with pytest.raises(ValidationError):
data_analyst.region = region
data_analyst.save() | 5,350,888 |
def print_mystery (num = 10):
"""
Generates a set of suspects, their alibis and hair colours, and
outputs the result.
:``num``: The number of suspects. *Default 10*.
"""
rooms = get_rooms(num)
sl = SuspectList(num, rooms)
print "The victim: %s, %s" % (sl.get_victim().get_name(),
... | 5,350,889 |
def batch_metrics_logger(run_id):
"""
Context manager that yields a BatchMetricsLogger object, which metrics can be logged against.
The BatchMetricsLogger keeps metrics in a list until it decides they should be logged, at
which point the accumulated metrics will be batch logged. The BatchMetricsLogger e... | 5,350,890 |
def check_for_command(command):
"""
Ensure that the specified command is available on the PATH.
"""
try:
subprocess.check_call(['which', command])
except subprocess.CalledProcessError as err:
logging.error("Unable to find %s command", command)
raise err | 5,350,891 |
def split(endpoint_name, traffic_policy_dictionary):
"""Associate a service endpoint with traffic policy.
Example:
>>> serve.split("service-name", {
"backend:v1": 0.5,
"backend:v2": 0.5
})
Args:
endpoint_name (str): A registered service endpoint.
traffic_policy_dic... | 5,350,892 |
def rgb(r=None, g=None, b=None, smooth=True, force=True):
"""
Set RGB values with PWM signal
:param r: red value 0-1000
:param g: green value 0-1000
:param b: blue value 0-1000
:param smooth: runs colors change with smooth effect
:param force: clean fade generators and set color
:retu... | 5,350,893 |
def visualize_relative_weight_ranges_model():
"""
Code example for model visualization
"""
visualization_url, process = start_bokeh_server_session(8002)
model = models.resnet18(pretrained=True).to(torch.device('cpu'))
model = model.eval()
batch_norm_fold.fold_all_batch_norms(model, (1, 3, 2... | 5,350,894 |
def handle_config(args, configs):
"""Handle `view` subcommand
:param args: parsed arguments
:type args: `argparse.Namespace`
:param configs: configurations object
:type configs: ``sfftk.core.configs.Configs``
:return int status: status
"""
if args.config_subcommand == "get":
... | 5,350,895 |
def bottom_up_amons_of(mol, max_size, already_generated=set()):
"""
Generates all unique amons of mol by growing graphs up to a max_size around each atom
already_generated: A set of smiles strings of amons that have already been generated
"""
if mol.NumHvyAtoms() < 1:
return
obConversio... | 5,350,896 |
def dump_config(output=None, **kwargs):
"""
Dump current configuration to screen, useful for creating a new
``settings.cfg`` file
Arguments:
output (Optional[str]): output filename, stdout if None
"""
conf = arguments.read_config(**kwargs)
conf.write(output or sys.stdout) | 5,350,897 |
def filter_safe_actions(
action_shield: Dict[int, Dict[ActionData, int]], energy: int, bel_supp_state: int
) -> List[ActionData]:
"""Utility function to filter actions according to required energy for them with given action shield.
Parameters
----------
action_shield : List[Tuple[int, ActionData]]
... | 5,350,898 |
def handle_embedded_annot_2(data):
"""
socketio Handler to aggregate original page metadata with sparql endpoints.
emit the result of sparql requests
@param data dict Contains the data needed to aggregate (url, etc).
"""
# step = 0
print("handle annot_2")
sid = request.sid
print(sid... | 5,350,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.