content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pos_mask(row: int, col: int) -> int:
"""Return the bit mask for (row, col) on a bitboard."""
assert 0 <= row < 8
assert 0 <= col < 8
return 0x8000000000000000 >> col >> row * 8 | 11e374843026bb50a3d6ca0cd58c52d6ec1924b4 | 636,858 |
def find_vswitch_uri_for_id(k2_id, vswitch_map):
"""
Returns the vSwitch href URI for a given K2 id.
:param k2_id: The K2 vSwitch ID
:param vswitch_map: The vSwitch map from the HMC Topo
:returns: vSwitch URI
"""
k2_obj = vswitch_map.get(k2_id)
if not k2_obj:
return None
retu... | e8e9fbaa16061f207a0d9f49afe5ffb534cf409a | 636,859 |
def find(to_find, k):
"""Finds the Kth to last element in LinkedList.
uses two references to find the kth to last element
within a linked list
Args:
to_find: LinkedList containing kth element
k: the kth to last position
Returns:
the kth node's data.
"""
target = t... | ff5657190a2df26c6788caa14638ae8ec21679af | 636,860 |
def get_leftmost_end_point(linestring):
"""
extracts leftmost end point of linestring
:param linestring: shapely.geometry.LineString
:return: shapely.geometry.Point
"""
point_0_x = linestring.xy[0][0]
point_1_x = linestring.xy[0][-1]
if point_0_x <= point_1_x:
return point_0_x
... | e23014df16f09f6d60e3f3af66b5ef04ee5ca0bb | 636,861 |
def getKey(myDict, value):
""" Finds key associated with a value in dictionary """
for key, val in myDict.items():
if val == value:
return key
return -1 | ac0c1eaa8fec797ac1e4db9c1e0886cc5cffd99d | 636,862 |
def _worker_fn(url, dataset_fn, sampler_fn):
"""Function to generate the dataset and sampler for each worker."""
dataset = dataset_fn(url)
sampler = sampler_fn(dataset)
return (dataset, sampler) | 4ddafee02420eca6731ab75e60172c023c953eef | 636,863 |
def bin_to_str(x, digits=16):
"""
>>> bin_to_str(10, 6)
'001010'
"""
format = "{x:0%db}" % digits
return format.format(x=x) | 80c845c4072baad874a2cfcbdb3a04ea43c8dbe9 | 636,864 |
def summary_global_quantities(ods, update=True):
"""
Calculates global quantities for each time slice and stores them in the summary ods:
- Greenwald Fraction
- Energy confinement time estimated from the IPB98(y,2) scaling
- Integrate power densities to the totals
- Generate summary.global_q... | f70e9d233fc457e495e3ebb5ee46faaec38ad98a | 636,865 |
def get_resume_name(stage_name):
"""return a new name with resume and an increasing index"""
split_stage_name = stage_name.split("_")
if len(split_stage_name) > 2 and split_stage_name[-2] == "resume":
resume_index = int(split_stage_name[-1]) + 1
return "_".join(split_stage_name[:-2] + ["resu... | a1aea3021b33c1c39b5671979eaab13c91ecaf26 | 636,866 |
import os
def is_sm():
"""Check if running in a Sagemaker Training instance
"""
sm_framework_params = os.environ.get('SM_FRAMEWORK_PARAMS', None)
if sm_framework_params:
return True
return False | a9110570afe2b68cbf36d202378aaacd38bfd769 | 636,867 |
def create_empty_hierarchy():
"""Create an empty hierarchy structure (dict).
hierarchy = {
"lvl0": None,
"lvl1": None,
"lvl2": None,
"lvl3": None,
"lvl4": None,
"lvl5": None,
"lvl6": No... | 558d772820d028e8416f33cb594a2580ed422f5b | 636,869 |
def acknowledgements():
"""Returns acknowledgements for the specified ACE instrument
Returns
-------
ackn : string
Acknowledgements for the ACE instrument
"""
ackn = ''.join(['NOAA provided funds for the modification of ',
' the ACE transmitter to enable the broadc... | a29bd9dbe21b5ae5853cd25235d705da7f121044 | 636,870 |
def _merge_columns(grid, columns_to_merge):
"""A helper function that merges columns
in a grid.
grid: [[str]]
columns_to_merge: [(col1, col2)]
The columns must not overlap. Also, they must be
increasing. So if we had something like:
[(x,y), (w,z)], x<y<w<z must hold.
IMPORT... | a459628f2ca9ac8497112aa6c4b047bd838be049 | 636,871 |
import yaml
def extract(mdtext):
"""
Extract a yaml text blob from markdown text and parse the blob.
Returns a tuple (yaml_obj, markdown_text)
"""
lines = mdtext.split("\n")
n = 0
ylines = []
mlines = []
for line in lines:
if (line == "---"):
n = n + 1
else:
if n == 1:
y... | 7bfb9affa1b24af321f7558d01edbce86dfc80a9 | 636,872 |
import os
def _write_file(contents, path, owner_uid, group_gid, mode):
"""Try to write file to filesystem with specific UID, GID, and file mode"""
try:
with open(path, 'w') as f:
f.write(contents)
os.chmod(path, mode)
os.chown(path, owner_uid, group_gid)
return Tr... | 331f33b4bfb48d2da8db5beee1cb8df04ef043cb | 636,873 |
import torch
def binary_accuracy(prediction, target):
"""Calculates accuracy between two classes using probabilities
Parameters
----------
prediction : torch.Tensor or torch.autograd.Variable
Vector of probabilities of class 1
target : torch.Tensor
Vector containing the class indices 0 or 1
"""
... | 4f101992de444af744c06b361146feeee917b682 | 636,874 |
import inspect
def listens_to(name): # noqa: D401
"""Decorator to register a method of a :class:`Handler` as a listener.
The method must be a coroutine.
Arguments
---------
name: :class:`str`
The name of the event to listen to.
Raises
------
TypeError
The name was n... | e3c8f4bc365cfe4ee60a09297741335a4640272d | 636,875 |
def any_lowercase5(s):
""" incorrect - returns whether false if s contains any capital letters"""
for c in s:
if not c.islower():
return False
return True | 9c50afa415d2b0a74b2c4af7d7f3833dd4dae400 | 636,876 |
def remove_invalid_chars(string) -> str:
"""
Примимает строку и возвращает строку, удаляя из нее символы, указанные в invalid_chars
"""
invalid_chars = '\/:*?"<>|\r\n'
return string.rstrip().translate(dict.fromkeys(map(ord, invalid_chars))) | 1fd8b40f83096cf9c028c5a9aef0dca1633dcc12 | 636,878 |
def correlate_dicts(dicts, key):
"""Correlate several dicts under one superdict.
If you have several dicts each with a 'name' key, this
puts them in a container dict keyed by name.
Example::
>>> d1 = {"name": "Fred", "age": 41}
>>> d2 = {"name": "Barney", "age": 31}
>>> flint... | 2f4c03f5d976115ea14746a1acf243fff635bdb8 | 636,880 |
def parse_blosum_table(table, coeff_type=int, key_type='row'):
"""
Parse a table of pairwise amino acid coefficient (e.g. BLOSUM50)
"""
lines = table.split("\n")
# drop comments
lines = [line for line in lines if not line.startswith("#")]
# drop CR endline characters
lines = [line.repla... | 9ea91361c87fe0434b8f2c548d694afa04457cb2 | 636,882 |
import ipaddress
def anonymize_IP(ip):
"""
Anonymize IP before storing in the database.
Mask for IPv4: 16
Mask for IPv6: 32
"""
anonymized_ip = ""
try:
ip = ipaddress.ip_address("{}".format(ip.strip()))
if ip.version == 4:
mask = "/16"
else:
... | 5265ddf2e99e22c0c3b2a65b6ffa6d2cdae2d0b8 | 636,883 |
import functools
def as_list(f):
"""Decorator that changes a generator into a function that returns a list."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
return list(f(*args, **kwargs))
return wrapper | 28b0de884a06f4a0933ef7afe9940e449cfb2144 | 636,884 |
def is_overlapped(end1, start2):
"""Returns True if the two segments overlap
Arguments
---------
end1 : float
End time of the first segment.
start2 : float
Start time of the second segment.
"""
if start2 > end1:
return False
else:
return True | 421148cd3dfbb9ea5accaa6f5792c48beee09334 | 636,885 |
import requests
import json
import sys
def send(payload, webhook_url):
"""Sends notification to Slack"""
# Send message as a JSON string
try:
response = requests.post(
webhook_url,
data=json.dumps(payload),
headers={'Content-Type': 'application/json'})
excep... | 11921348d4267181f65b09502ce7eeee021a6990 | 636,886 |
def _flatten_state(state):
"""Reduce nested object to string."""
if isinstance(state, list):
return ",".join(map(_flatten_state, state))
elif isinstance(state, dict):
return ",".join(map(lambda x: ":".join(map(_flatten_state, x)), state.items()))
return str(state) | df82b0ab13cb14b9cf221309f87b1a2816d36ba9 | 636,887 |
def _delta(x,y):
"""
Returns 1 if x and y differ, 0 otherwise.
"""
return x != y | 69b3d1eca28678685d9d135b091affd1d6dcff00 | 636,888 |
def matrix_relative_rotation(r0, r1):
"""
Find the relative rotation to go from r0 to r1.
"""
return r1 @ r0.T | 83f675dda63a8120662b2b840b40e74f51580173 | 636,889 |
import tempfile
def makeTempDir() -> str:
"""Make a temporary directory.
:rtype: str
:return: The path to the temporary directory.
"""
return tempfile.mkdtemp() | cede067b0cc720ab37859d4ea590429778edbcf9 | 636,891 |
def role(value, arg):
"""Returns html div with the given user's group's role
Keyword arguments
value -- list of dictionaries, containing users, groups and roles
arg -- a user
"""
html = ''
for group in value.get(arg):
role = value.get(arg).get(group)
if role:
h... | cc28c504b2adead29c4ec3ee2dccbd67790f4b4f | 636,892 |
import os
def pkg_resouces_get_default_cache():
"""Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
"Application Data" directory. On all other systems, it's "~/.python-eggs".... | e3ce905b590f9a8c6420cf6a262237fa9a80946a | 636,893 |
import argparse
def get_args():
"""
Argument defnitions
"""
parser = argparse.ArgumentParser(description="Arguments for data exploration")
parser.add_argument("--pg",
dest="pg",
action="store_true",
help="tag the sentences wit... | 945661e1753a43ef9e7add98ed86ba53931a9f4c | 636,894 |
def firstPreparation(data):
"""
First preperation, drop the class and prepare data
"""
data_full = data.copy()
data = data.drop(["price"], axis = 1)
labels = data_full["price"]
return data_full, data, labels | e6bcfa281ac7b6aea6671e719b9b3d2a88a025b4 | 636,895 |
def parse_header(line):
"""Returns dict {'field': (start, length), ...}"""
fields = [f.strip() for f in line.split(' ') if f.strip()]
return {field: (line.index(field), len(field) + 1) for field in fields} | cb0f5bfec6540a573455ef6b4ee9de39a8809a74 | 636,896 |
import warnings
def deprecate_arg(old_arg, new_arg, old_value, new_value):
"""Helper to raise warnings when a deprecated arg is used.
Args:
old_arg (str): Name of old/deprecated argument.
new_arg (str): Name of new argument.
old_value (Any): Value the user passed in for the old argume... | 2d1a9a05ec65d364f26449423b540093c4c44167 | 636,897 |
def service_disconnect(connectionId): # noqa: E501
"""Disconnect from the service
Disconnects from the Azure IoTHub service. More specifically, closes all connections and cleans up all resources for the active connection # noqa: E501
:param connectionId: Id for the connection
:type connectionId: str... | 02145678f116b17391cae84ebcb1e05b03c639ac | 636,898 |
def readfile(filename):
"""
Reads and returns file contents
"""
with open(filename) as docfile:
return docfile.read() | ac17395b05e501673718b1110c3ebbedcee4e60c | 636,899 |
import math
def get_learning_rate(lr_schedule,
tot_epoch,
cur_epoch):
""" Compuate learning rate based on the initialized learning schedule,
e.g., cosine, 1.5e-4,90,6e-5,150,0 -> ('cosine', [1.5e-4,90,6e-5,150,0]).
Args:
lr_schedule: the learning schedu... | a6ee1d202d846094243baa120f1486e33016a174 | 636,900 |
def topic_ref_transform(ref_string, topic):
"""
Converts a topic string with forward-slashes into a JSON reference-friendly format
("/" becomes "~1"), then places the new string into the provided base reference path.
:param ref_string: The base reference path
:param topic: The DXL topic string to c... | b80071faed0e9bc3a4c8b06453e84c385012b532 | 636,901 |
def fall(vfz):
"""Compute the fall damage inflicted given final vertical speed on touch.
Return the untruncated damage corresponding to touch-ground vertical speed
*vfz*. Only positive *vfz* values are meaningful.
"""
return max(0.0, 25 * (vfz - 580) / 111) | 6536673f2e081a3929433dc79290e74c222904da | 636,902 |
def ang_sym_chek2(m1, m2):
"""
Calculate the ration of the doses stored in the 2D array m1
at coordinates row = i,column =j to the doses stored in the 2D array m2
at coordinates row = i,column = -j-1 .
"""
matrix = []
for row_index in range(len(m2)):
for value_index in range(len(m2... | c28a924fcbad24c8af42e207411c8f9e47f6ec32 | 636,904 |
import re
def check_date_format(date_str):
""" Check the date to ensure that it's in the proper format
"""
pattern = re.compile("^\d{4}-+\d{2}-+\d{2}T+\d{2}:+\d{2}:+\d{2}.+\d{1,}Z+$")
matched = pattern.match(date_str)
return matched | 4c82090bd463e71683ec8cc599e2f34515a6ce4f | 636,905 |
def compute_standard_walking_time(length_m: float, elevation_gain_m: float, elevation_loss_m: float) -> float:
"""Estimate the hiking time in seconds
Parameters
----------
:param: length_m: Length of the hike in meters
:param: elevation_gain_m: Elevation gain of the hike in meters
:... | c6c1c6896f1c9b5188d3b65bf32880f6071b92e1 | 636,906 |
def sort_dict(data: dict, key_type=None, reverse=False):
"""
Returns a sorted dictionary by keys
:param data: the input dictionary
:param key_type: type of key (if keys are not str for example)
:param reverse: sort in reverse order
:return: sorted dictionary
"""
res = {}
if len(data)... | b7cb416ebf6c572d09838ade105c5229a5be2e99 | 636,907 |
def _get_QListWidget(self):
"""
Get currently selected values in QListWidget via re-mapping filter.
Selected values are returned as a list.
"""
return [self._get_map(s.text()) for s in self.selectedItems()] | 5f4be2a7c03f7013a3bedd667f6954c761d6c962 | 636,908 |
def is_user_info_complete(user):
"""
Returns True if the user has provided all of the required registration info
Args:
user (django.contrib.auth.models.User):
Returns:
bool: True if the user has provided all of the required registration info
"""
return (
hasattr(user, "... | f8899908487ded83802313c5dd8f92ed360218b1 | 636,909 |
def poke_64(library, session, address, data):
"""Write an 64-bit value from the specified address.
Corresponds to viPoke64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to rea... | 37bb8355d2833f8810f66657ed20efa0f472b65e | 636,911 |
def bounds_to_geojson(bounds):
"""
Convert a rio BoundingBox to geojson with optional buffer
:param bounds: BoundingBox
:return: geojson with applied buffer
"""
return {
"type": "Polygon",
"coordinates": [
[
[bounds.left, bounds.top],
[... | 6aab2f3b44ff79eb30681b4f9d7aefc99679c0d6 | 636,912 |
def pre_compute(expr, data, scope=None, **kwargs):
""" Don't push slices into memory, they're about to come in anyway """
return data | 30e8b3ecc8f506d8d991280308fcdd32a2e980df | 636,913 |
def cors(environ):
"""Solove the cors problem."""
environ.headers['Access-Control-Allow-Origin'] = '*'
environ.headers['Access-Control-Allow-Method'] = '*'
environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
return environ | e0f17fd974a519da3a05e5122771640ef7c0c33a | 636,914 |
def _get_dataset_length(dset, default=1):
"""Return the dataset's training data length and in case the dataset is
uncountable return a defalt value."""
try:
return len(dset.train_data)
except RuntimeError:
return default | b2c46e652d425b920406a3a534d55886c555e0a5 | 636,915 |
import sys
def get_traceback_from_context(context):
"""
Get the traceback object from the context.
"""
exception = context.get('exception')
if exception:
if hasattr(exception, '__traceback__'):
return exception.__traceback__
else:
# call_exception_handler() ... | bc84dbd9fc160e8923baf40c5f27e7993f495534 | 636,916 |
def attribution() -> str:
"""Returns data attribution string"""
return '\u0026copy; <a href="https://usafacts.org">USAFacts</a>. ' | 556d0f74bc35a4e7cbc597d1a9190d8c8b936683 | 636,917 |
def _filter_core_state_space(df, options):
"""Applies filters to the core state space.
Sometimes, we want to apply filters to a group of choices. Thus, use the following
shortcuts.
- ``i`` is replaced with every choice with experience.
- ``j`` is replaced with every choice without experience.
... | 296c25879a2e30d8260efdf28ada02c6e5e69ff9 | 636,918 |
import torch
def _move_to_device(args, device):
"""Move args to given device
:param args: args to move to device
:param device: device to move to
"""
if isinstance(args, tuple):
return tuple([_move_to_device(x, device) for x in args])
if isinstance(args, list):
return [_move_t... | 11c22fcfcbc9e6f25a5c9e8e2a1c2234127cf79c | 636,919 |
def get_output_file(dataset, output_dir):
"""
Compute the output metadata file name for the given dataset.
"""
out_file_name = str(dataset.id) + '-metadata.yaml'
return output_dir / out_file_name | 34086bb664a5e1527391ad1d606196e0b63f3453 | 636,920 |
import subprocess
def _get_n_cpus(platform_name: str) -> str:
"""Get the number of logical CPUs.
Args:
platform_name: Assumed to the return value of `platform.system()`.
"""
command = [""]
if platform_name == "Linux":
command = ["nproc"]
elif platform_name == "Darwin":
... | a13c564ccc468eb9bb317802c31e13f40e177296 | 636,921 |
import warnings
def _split_sections(lines):
"""
Split rigaku file into sections
Returns a list of sections [(name, body, index)] where name is the section
type, body is the list of lines between *RAS_name_START and *RAS_name_END
and index is the 1-origin index of *RAS_name_START (or the 0-origin ... | b80678d654a91b6703dc490b930dff59f116ad29 | 636,922 |
def append_attr_to_dict(attrib, result):
"""append xml element attrib to dict
:param attrib: attributes
:param result: dict
:type result dict
:type attrib dict
:return: dict
"""
for attr in attrib:
result["@%s" % attr] = attrib[attr]
return result | 75e583ca6ad459eea9d20566d1d545154f322491 | 636,923 |
def sort_link(context, link_text, sort_field, visible_name=None):
"""Usage: {% sort_link "link text" "field_name" %}
Usage: {% sort_link "link text" "field_name" "Visible name" %}
"""
is_sorted = False
sort_order = None
orig_sort_field = sort_field
if context.get('current_sort_field') == ... | 8859a5fed692e1d9b8b520c1340cc21f9500bbf5 | 636,924 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Video cropping to images into separate but exact same dirs')
parser.add_argument('--video', dest='video', required=True, help='video root path',
default='')
parser.add_a... | dd78602b4b8936847c9b2107822947d4a57c8b96 | 636,925 |
import zipfile
def list_files_in_zip(filename, endswith=None):
""" List files in zip archive
:param filename: path of the zip
:param endswith: optional, end of filename to be matched
:return: list of the filepaths
"""
with zipfile.ZipFile(filename) as zip_file:
filelist = zip_file.name... | 51aeefd0c14223d65f84bbf95e7676fe27e46297 | 636,926 |
import os
def construct_name(id, fn, path):
"""Constructs a file name out of messages ID and packed file name."""
id = id.split(".")
id = id[0]+id[1]
result = path + os.path.basename(id+"."+fn)
return result | 39acb28f41811da1dffe978e3c2795aab98f6994 | 636,927 |
import os
def _get_number_of_cores_solaris():
"""
Return the number of cores for OpenSolaris 2008.05 and possibly other
editions of Solaris.
"""
f = os.popen("psrinfo -p")
try:
return int(f.read().strip())
finally:
f.close() | 11da6f150b8e7412597066e3c28af1e318053db9 | 636,928 |
def get_wet_info(wet_distro, name):
"""
Get information about wet packages or stacks
"""
repos = wet_distro['repositories']
for repo in repos:
info = repos[repo]
if repo == name or name in info.get('packages', []):
return (repo, info)
return None | 000e3719d490d310731eea2bc0b61231800045be | 636,929 |
def producer_config(config):
"""Filter the producer config"""
for field in ["group.id", "partition.assignment.strategy", "session.timeout.ms", "default.topic.config"]:
if field in config:
del config[field]
return config | 3245c62f26288ab58a992494a4d0e87b772fcc81 | 636,930 |
import argparse
def parse_all_args():
"""
Parses arguments
:return: the parsed arguments object
"""
# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("target",
help="The type of anomaly to identify")
parser.add_argument("fn",
... | bf3427641467746bea4983bf3b0611251cb95b64 | 636,931 |
def label_filter(label_key, label_value):
"""Return a valid label filter for operations.list()."""
return 'labels."{}" = "{}"'.format(label_key, label_value) | fe6efe0fdce70a1c36e3f070205c3b0d4279dd62 | 636,932 |
from datetime import datetime
def utc_folder(x):
"""
Convert a UTC timestamp to a folder string
"""
return datetime.utcfromtimestamp(x).strftime('%Y/%j/%H') | a153a06d07600420bbbcfa846eb144b0cceddf13 | 636,933 |
def is_allowed_coupling(coupling, flow, symmetries):
"""Return boolean if coupling is allowed.
"""
if len(coupling) != 3:
raise ValueError(f'len(coupling) [{len(coupling)}] != 3')
if len(flow) != 3:
raise ValueError(f'len(flow) [{len(flow)}] != 3')
def fermionic_constraint(irreps, ... | 21278fbba444a034cbb736016255fdb36a6f8263 | 636,934 |
import os
def sanitizedFilenameIncludeGuard(absFileName):
"""produce a string that matches the filename, but that's appropriate for use in a #include"""
# Use relative path to ensure files are identical across build directories
relFileName = os.path.relpath(absFileName)
return "__CPPML_TRANSFORMED_" +... | d2d1ec1ec8863b287c4111c063f6c5fe2c8cc2e0 | 636,935 |
def short_state(state: str) -> str:
"""Return a short version of query state.
>>> short_state("active")
'active'
>>> short_state("idle in transaction")
'idle in trans'
>>> short_state("idle in transaction (aborted)")
'idle in trans (a)'
"""
return {
"idle in transaction": "i... | 1559c3e97314607d96954793a9b253ef252dd04c | 636,936 |
import logging
def str2zipcode(value):
"""convert a str to int"""
try:
return int(value)
except ValueError as err:
logging.warn("str2zipcode: <%s | %s>" % (value, err))
return 0 | 8c93d24a80ba9c810693e0d37dd0d4046d94cfbf | 636,937 |
import codecs
import json
def read_load(json_path, encoding='utf-8'):
"""Load the data from the json file.
Args:
json_path (str): Json file path.
encoding (str): Encoding, default is ``utf-8``.
Returns:
dict: Data in the json file.
e.g.:
{
... | d8f1c2f80f5a9266bcd1558ed6a2588e9b1bfcb6 | 636,938 |
import re
def _extract_sentence_tags(tagged_sentence):
"""Given a tagged sentence, extracts a dictionary mapping tags to the words
or phrases that they tag.
Parameters
----------
tagged_sentence : str
The sentence with Medscan annotations and tags
Returns
-------
tags : dict
... | 2a913707d2f48736f70df2141779c00a0068ee54 | 636,939 |
def find_median(a: int, b: int, c: int) -> int:
"""Find median of three elements"""
x = a - b
y = b - c
z = a - c
if x * y > 0:
return b
if x * z > 0:
return c
return a | 97816d215c11fc158f800fe47d5b89941fd356fd | 636,940 |
def flatten(list):
"""Flatten a list of elements into a uniqu list
Author: Christophe Simonis (christophe@tinyerp.com)
Examples::
>>> flatten(['a'])
['a']
>>> flatten('b')
['b']
>>> flatten( [] )
[]
>>> flatten( [[], [[]]] )
[]
>>> flatten( [[['a','b'], 'c'], 'd', ['e', ... | 20d8ffef9ebd4a28fad98b866e257be4ac8ef46b | 636,941 |
def video_settings(settings):
"""Mock for django settings"""
settings.YOUTUBE_DEVELOPER_KEY = "key"
settings.YOUTUBE_FETCH_TRANSCRIPT_SLEEP_SECONDS = 0
return settings | bbb9d865552f97a6933c2f2f271b94a2fab1dec3 | 636,943 |
def get_updater(api, resource_type):
"""Returns the method to update a given resource type
"""
updaters = {
"source": api.update_source,
"dataset": api.update_dataset,
"model": api.update_model,
"ensemble": api.update_ensemble,
"batchprediction": api.update_batch_pre... | 3cbdad0376940724783134734b521e802da2ea60 | 636,944 |
import torch
def get_complete_dataset(dataloaders, key="train", region="region1"):
"""
Load complete dataset to memory.
Args:
dataloaders (OrderedDict): dictionary of dictionaries where the first level
keys are 'train', 'validation', and 'test', and second level keys are
r... | 8e952cd8458884160ee51f46a21feebc1af6c87c | 636,946 |
def converter_tuple(obj) -> tuple:
"""
Convert input to a tuple. ``None`` will be converted to an empty tuple.
Parameters
----------
obj: Any
Object to convert.
Returns
-------
obj: Tuple[Any]
Tuple.
"""
if obj is None:
return ()
elif hasattr(obj, "_... | 0e08563fc0f8253d1f81d1de90fdafd70cbe387b | 636,947 |
def tupilate(source, val):
"""Broadcasts val to be a tuple of same size as source"""
if isinstance(val, tuple):
assert(len(val) == len(source))
return val
else:
return (val,)*len(source) | 6047a14148aa22c32a2caa43f8ea2015ba69bd8c | 636,948 |
import pandas
def dataframe_to_html(
dataframe,
extra_classes=(),
index=False,
header=True,
use_default_classes=True,
escape_html=False,
):
"""Return a HTML version of a dataframe with Semantic UI CSS style classes.
By default it applies the following Semantic UI classes:
'ui', 'c... | 3ea71e2a6426f9929672272ab054186e82a75376 | 636,949 |
def convert_eq(list_of_eq):
"""
Convert equality constraints in the right format
to be used by unification library.
"""
lhs = []
rhs = []
for eq in list_of_eq:
lhs.append(eq.lhs)
rhs.append(eq.rhs)
return tuple(lhs), tuple(rhs) | 1366c0fa26b690cace85cb4feb2a646600850543 | 636,950 |
def split_filtStr(filtStr):
"""
...doctest:
>>> split_filtStr('a>b;c<=d; e == f; bc=[0,1]')
['a>b', 'c<=d', 'e == f', 'bc=[0,1]']
>>> split_filtStr('a>b AND c<=d AND e == f')
['a>b', 'c<=d', 'e == f']
>>> split_filtStr('bc=[0,1]')
['bc=[0,1]']
>>> split_f... | 2f2221afeb53ac4bfa626dfb4b7ad3082fc2c7c1 | 636,951 |
def coord2pix(cx, cy, cdim, imgdim, origin="upper"):
"""Converts coordinate x/y to image pixel locations.
Parameters
----------
cx : float or ndarray
Coordinate x.
cy : float or ndarray
Coordinate y.
cdim : list-like
Coordinate limits (x_min, x_max, y_min, y_max) of imag... | e750aaf8350826aa22af58e20622182a9a209b97 | 636,952 |
def fix_shape_intervals(intervals):
"""Fix issue for intervals of dims with shape
(https://github.com/Epistimio/orion/issues/800)
"""
for i, interval in enumerate(intervals):
intervals[i] = tuple(map(float, interval))
return intervals | dc2d7b0f7c12cebd12ef524708e5da21a826e16c | 636,953 |
def multiply(a,b):
""" multiply two numbers """
return a*b | 90580db394d6e6021e3fbf969d8de8e5e789fcff | 636,954 |
def get_public_key(remote, realm_url):
"""Get the realm's public key with the ID kid from Keycloak."""
certs_resp = remote.get(realm_url).data
return certs_resp["public_key"] | 2d4de952101901a862d14b8e13514f5f17c7d0dd | 636,955 |
def triple(n):
""" (number) -> number
Returns triple a given number.
>>> triple(9)
27
>>> triple(-5)
-15
>>> triple(1.1)
3.3
"""
one = n * 3
return (one) | 0f10a8026aba22ce9a1905c5d445984c7310763d | 636,956 |
import hashlib
def md5_bytes(data: bytes):
"""
generate md5 hash of binary.
"""
return hashlib.md5(data).hexdigest() | 9cfbea28556dae41e3eff3e9b480a48c39a47a3d | 636,957 |
import shlex
def expand_file_arguments(argv):
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
... | 70645b57b303092450cff60c7c4608633d48167f | 636,958 |
def hosts_loader(filename: str) -> dict:
""" Loads host mapping file
:param str filename: path to file
:return: mapping as dictionary
"""
return_dict = {}
with open(filename) as mapfile:
lines = [
line.strip() for line in mapfile
if not line.startswith('#') and l... | 2d271ce94f68eb36237d397678857b6654938f52 | 636,959 |
from zlib import crc32
def safe_crc(string):
"""64 bit safe crc computation.
See http://docs.python.org/library/zlib.html#zlib.crc32:
To generate the same numeric value across all Python versions
and platforms use crc32(data) & 0xffffffff.
"""
return crc32(string) & 0xffffffff | 43c6693c7d30ef19be7cda3d270f5c1225d70778 | 636,960 |
def iterator_strategy(cube, axis=None):
"""
Guess the most efficient iteration strategy
for iterating over a cube, given its size and layout
Parameters
----------
cube : SpectralCube instance
The cube to iterate over
axis : [0, 1, 2]
For reduction methods, the axis that is
... | a6769396d2fe2a0ca60419dcdc16cb0b454e4e38 | 636,961 |
def SetupSurfaceAndBuriedResiduesSelection(SurfaceResiduesNums, BuriedResiduesNums):
"""Setup PyMOL selection for surface and buried residues."""
SurfaceResiduesSelection, BuriedResiduesSelection = [None] * 2
UseSurfaceResidueNums, UseBuriedResidueNums = [False] * 2
SurfaceResiduesCount = len(Surf... | b4777b5a7b9961cef3a0888027046fe3e3fbff58 | 636,962 |
def __newobj__(cls, *args):
""" Unpickles new-style objects.
"""
return cls.__new__(cls, *args) | 2455cc106e3cb706c400184ccb24f861386b5830 | 636,963 |
def format_number(num):
"""Return a number representation with comma separators."""
snum = str(num)
parts = []
while snum:
snum, part = snum[:-3], snum[-3:]
parts.append(part)
parts.reverse()
return ",".join(parts) | 2de1b12c0703f1d5b1ed981f636b4db0cd00707b | 636,964 |
def invert_dict(dct: dict) -> dict:
"""Invert dictionary, i.e. reverse keys and values.
Args:
dct: Dictionary
Returns:
Dictionary with reversed keys and values.
Raises:
:class:`ValueError` if values are not unique.
"""
if not len(set(dct.values())) == len(dct.values())... | 380ed6b769526c08eecb4f33c58f350c54ccc18f | 636,965 |
def sort_list(coord_list):
"""
Return a sorted list of coordinates, by y, then x
"""
return sorted(coord_list, key=lambda k: [k[1], k[0]]) | 70d5c26e183c483adfe8013c6f60b4865e0f12d9 | 636,966 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.