content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Any
def copy_with_str_subst(x: Any, substitutions: Any) -> Any:
"""Deep-copy a structure, carrying out string substitutions on any strings
Args:
x (object): structure to be copied
substitutions (object): substitutions to be made - passed into the
string '%' oper... | 2aefd8902b2ca56d9c7a2e81dbd52c52a731a14e | 266,645 |
def channel_reshape(x, channel_shape):
""" (B, *, H, W) to (B, custom, H, W) """
return x.reshape((x.shape[0],) + channel_shape + x.shape[-2:]) | 7d08dc4fc20686f9797a1e36ddaedbf9ef990a0c | 45,369 |
import re
def strip_advanced(s: str) -> str:
"""Remove newlines and multiple whitespaces."""
return re.sub(r'\s{2,}', ' ', s.replace('\n', ' ')) | 66456fd4357e55ec7cba4b2bec69c572d242287e | 221,987 |
def set_conn_string(server, db_name, username, password):
"""
Sets connection string to SSAS database,
in this case designed for Azure Analysis Services
"""
conn_string = (
"Provider=MSOLAP;Data Source={};Initial Catalog={};User ID={};"
"Password={};Persist Security Info=True;Impers... | 9b7d63a0ef97eb4012163550ed0548c5e531fe39 | 670,833 |
def dominant_flip_flopping(W):
"""Determine if a unique walk matrix demonstrates dominant flip-flopping.
Dominant flip-flopping is defined as:
For every class C[i], there exists a walk length L[x], such that C[i] has
more closed walks of length L[x] than all other classes combined.
Dominant flip-f... | 40e4092e23af578008370ef55cc983a0c243f89d | 334,189 |
def export_to_pascal(ibs, *args, **kwargs):
"""Alias for export_to_xml"""
return ibs.export_to_xml(*args, **kwargs) | b7fd4d3c68e09f5665dd658c42fc297341fb0b1e | 665,522 |
def get_typecode(dtype):
"""Get the IDL typecode for a given dtype"""
if dtype.name[:5] == "bytes":
return "1"
if dtype.name == "int16":
return "2"
if dtype.name == "int32":
return "3"
if dtype.name == "float32":
return "4"
if dtype.name == "float64":
retu... | 29e13fd122d6983b9bbc196216cf29487544e1b8 | 240,959 |
import re
def parse_num(s):
"""Parse data size information into a float number.
Here are some examples of conversions:
199.2k means 203981 bytes
1GB means 1073741824 bytes
2.1 tb means 2199023255552 bytes
"""
g = re.match(r'([-+\d.e]+)\s*(\w*)', str(s))
if not g:
r... | 721cc52cdf543bcaf3ff77d8059a7bfe6cb6d892 | 36,433 |
import re
def extract_target_sdk_version_apk(badging):
"""Extract targetSdkVersion tags from the manifest of an APK."""
pattern = re.compile("^targetSdkVersion?:'(.*)'$", re.MULTILINE)
for match in re.finditer(pattern, badging):
return match.group(1)
raise RuntimeError('cannot find targetSdkVersion in ... | da1d8c9a1d5ee23c4dda9710b872784286072dde | 517,768 |
def _is_vowel(phone):
"""Check whether a phoneme from the CMU dictionary represents a vowel."""
return any(c.isdigit() for c in phone) | 17bc16b73ec45e37d255728c8ea1ad38f80dad1f | 346,361 |
def bucket_size(bucket):
"""
Returns the total number of bytes in a bucket.
"""
return sum(key.size for key in bucket.get_all_keys()) | 83701d79eb54ff01e21814d3d107c06a798e2ef4 | 110,876 |
from typing import Tuple
def find_element(atom_symbol: str) -> Tuple[int, int]:
"""Returns the indices of the element component of a SMILES atom symbol.
That is, if atom_symbol[i:j] is the element substring of the SMILES atom,
then (i, j) is returned. For example:
* _find_element('b') = (0, 1).... | 2694d5de2a9ac41f25f55139eb3169c68f2f2125 | 57,794 |
def calc_duration(audio, rate):
"""Calculates the length of the audio in seconds.
params:
audio: A numpy ndarray, which has 1 dimension and values within
-1.0 to 1.0 (inclusive)
rate: An integer, which is the rate at which samples are taken
return: A float
"""
return a... | 34384c04a4f49bc3730b96696fdbd78621be57b5 | 459,692 |
def get_tag_value(tags, key):
"""Get a specific Tag value from a list of Tags"""
for tag in tags:
if tag['Key'] == key:
return tag['Value']
else:
raise KeyError | bb7a0a6e7dc928575cda84ce8c41065cd89efd09 | 492,416 |
import math
def distance(p1, p2):
"""Return the euclidean distance between (x1,y1) and (x2, y2)"""
x1,y1 = p1
x2,y2 = p2
return math.hypot(x1-x2, y1-y2) | 945213446cb78d7e35466ea7e0caa91ad699f8c1 | 322,935 |
def split(windows, num):
"""Split an iterable of windows into `num` sublists of (roughly) equal
length. Return a list of these sublists."""
if num == 1:
return [windows]
windows = windows if isinstance(windows, list) else list(windows)
length = len(windows) // num
return [windows[i*lengt... | 66180dfe34e5a345754c19e9fc5afd3369bacc5c | 250,319 |
def observe_rate(rate, redshift):
"""Returns observable burst rate (per day) from given local rate
"""
return rate / redshift | 13be6db3b3db0763a73be2b8381acb98f6f0ad54 | 679,033 |
def _get_energy(simulation, positions):
"""Given an OpenMM simulation and position, return its energy"""
simulation.context.setPositions(positions)
state = simulation.context.getState(getEnergy=True, getPositions=True)
energy = state.getPotentialEnergy()
return energy | 5179d54a4271bc5033115088ede50db5a532092c | 484,192 |
def is_a_number(string):
"""Takes a string and returns a boolean indicating whether it can be
converted to a float.
"""
try:
float(string)
return True
except ValueError:
return False | 92c20a803c1608140ca21f16e1a05cf0503cf994 | 290,525 |
def query_df(data, col_name, col_value):
"""
Create a new subset of a given DataFrame() by querying it.
Parameters:
- data: The base DataFrame().
- col_name: The name of the column.
- col_vale: The values to match in that column.
Returns:
A DataFrame() object.
"""
... | f75290e09c887a312e07fa62015fcdf0c19d5803 | 598,419 |
def add_to_dict_key(prefix: str, dct: dict) -> dict:
""" add a prefix to every dict key """
return {'%s/%s' % (prefix, k): v for k, v in dct.items()} | 9be01ed608744c60963b3f0b29e4bf841776648f | 501,399 |
from typing import Callable
def filter_keys(d: dict, predicate: Callable) -> dict:
"""
Returns new subset dict of d where keys pass predicate fn
>>> filter_keys({'Lisa': 8, 'Marge': 36}, lambda x: len(x) > 4)
{'Marge': 36}
"""
return {k: v for k, v in d.items() if predicate(k)} | 1bb282effd08bd103d479b442f1cd24b8b368e6a | 483,208 |
def al_cuadrado(x):
"""Función que eleva un número al cuadrado."""
y = x ** 2
return y | cbc2707c63d4a7c76f55d1e8ab1312e94eca8eb1 | 283,781 |
def is_str(target: str) -> bool:
"""Check target is str."""
if not isinstance(target, str):
return False
return True | e7d4449a0aac92b6c6f40c8aeca708b756cf3d94 | 219,941 |
def format_authors(paper):
"""
format_authors formats list of author fields to strings
:param paper: dict of paper meta data
:type paper: dict
:return: string format of authors
:rtype: str
"""
authors = paper["authors"]
if len(authors) > 2:
author = authors[0]["name"].split(... | 31a32e3460fb11e348577caa2e32b3d9ee079cc0 | 430,508 |
def sbr(data, weights):
"""Stolen Base Runs (SBR)
SBR = runSB * SB + runCS * CS
:param data: DataFrame or Series of player, team, or league totals
:param weights: DataFrame or Series of linear weights
:returns: Series of SBR values
"""
return weights["lw_sb"] * data["sb"] + weights["lw_cs"]... | f577dfa2955802a7cb7177f06f508d7902cbc60d | 633,003 |
def objScale(obj,factor):
"""
Object scaling function, gets obj and scale factor, returns an array of the scaled size
"""
oldSize = obj.get_size()
newSize = []
for i in oldSize:
newSize.append(int(i/float(factor)))
return newSize | 3104fc4e126299400a5a119fff0d8bc9d3ea32f7 | 9,061 |
def text_ends(text, pattern, case_sensitive=True):
"""
Checks whether the text (also known as `text`) contains the text specified for `pattern` at the end.
The no-data value None is passed through and therefore gets propagated.
Parameters
----------
text : str
Text in which to find some... | e1b821f1c1769e0658d251c521680246884d728b | 574,305 |
def _transform_headers(httpx_reponse):
"""
Some headers can appear multiple times, like "Set-Cookie".
Therefore transform to every header key to list of values.
"""
out = {}
for key, var in httpx_reponse.headers.raw:
decoded_key = key.decode("utf-8")
out.setdefault(decoded_key, ... | 583f2cef73415317341e65325e1ff35647ae42b9 | 235,697 |
def suggest_parameters_DRE_NMNIST(trial,
list_lr, list_bs, list_opt,
list_wd, list_multLam, list_order):
""" Suggest hyperparameters.
Args:
trial: A trial object for optuna optimization.
list_lr: A list of floats. Candidates of learning rates.
list_bs: A list of ints. Candidate... | 627855f5fe8fd15d43cc7c8ca3da22b704b5907e | 704,119 |
import unicodedata
def deaccent(text):
"""
Remove accentuation from the given string. Input text is either a unicode string or utf8 encoded bytestring.
Return input string with accents removed, as unicode.
Kindly borrowed from https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/utils.py
... | 01b36ed9c6e618d442fd67f89aac0cdc30f6a6d2 | 336,326 |
import getpass
def _set_shells(options):
"""Set password, shell and extra prompts for the username.
Args:
options dictionary with username, jump_user and extra_prompts keys.
Returns:
options dictionary with shell_prompts and passwd_prompts keys
"""
shells = [
"mysql\\>",... | f839646d52e2b43656a049d22866fd6fd201222d | 355,614 |
def input_parameter_name(name, var_pos):
"""Generate parameter name for using as template input parameter names
in Argo YAML. For example, the parameter name "message" in the
container template print-message in
https://github.com/argoproj/argo/tree/master/examples#output-parameters.
"""
return ... | 40a3d29274b141294e4b9cae83ddb84ae8e44188 | 42,270 |
def format_timedelta(days: int = 0, hours: int = 0, minutes: int = 0,
seconds: int = 0) -> str:
"""Returns a simplified string representation of the given timedelta."""
s = '' if days == 0 else f'{days:d}d'
if hours > 0:
if len(s) > 0:
s += ' '
s += f'{hours:... | 6414e2be5a01f178d6515ab6f21ea7c5ab4d5004 | 703,402 |
def build_database_url(ensembl_database):
""" Build the correct URL based on the database required
GRCh37 databases are on port 3337, all other databases are on port 3306
"""
port = 3337 if str(ensembl_database).endswith('37') else 3306
return 'mysql+mysqldb://anonymous@ensembldb.ensembl.org:{}/{}'\... | f33b6c4c18b8bf5ab7c8320e6b38c6f4cc9c41ac | 270,899 |
import pathlib
import json
def get_json_fixture_file(filename):
"""
Return JSON fixture from local file
"""
path = pathlib.Path(__file__).parent.parent / f"fixtures/{filename}"
content = pathlib.Path(path).read_text('UTF-8')
return json.loads(content) | a0973b51dd752996c1c2e526ee79cceb234849fa | 379,462 |
def _reduce_xyfp(x, y):
"""
Rescale FP xy coordinates
"""
a = 420.0 #mm
return x/a, y/a | 018c1a7dbd25590fd8bbb61238870cd4c3a00b03 | 134,385 |
import hashlib
def md5_hash(string):
""" Calculates the MD5 sum of a string
"""
m = hashlib.md5()
m.update(string.encode('utf-8'))
return m.hexdigest() | cf89d1c83e3fa1382c2f883627a774bfc51475e1 | 39,996 |
def formolIndex (NaOH_volume, NaOH_molarity, NaOH_fc, grams_of_honey):
"""
Function to calculate the formol index in honey
"""
number_of_NaOH_mols = NaOH_volume * NaOH_molarity * NaOH_fc
volume = number_of_NaOH_mols / NaOH_molarity
formol_index = (volume * 1000) / grams_of_honey
return formo... | 5c6d72cd1500a61adef21f263010bee1cdec4914 | 410,125 |
def is_float(s):
"""
test if string parameter is valid float value
:param s: string to test
:return: boolean
"""
try:
float(s)
return True
except ValueError:
return False | 4d8074ffcfc0346d2d097ebbcf5b19c793632c28 | 516,467 |
def apply_aliases(seq_dict, aliases):
"""Aliases is a mapping from sequence to replacement sequence. We can use
an alias if the target is a key in the dictionary. Furthermore, if the
source is a key in the dictionary, we can delete it. This updates the
dictionary and returns the usable aliases."""
usable_a... | 54f7bf8e1af653427450cbdb8cee6314359b8db0 | 168,547 |
def get_lineup_number(players: list[dict], prompt: str) -> int:
"""Get the player by lineup number and confirm it is a valid lineup number."""
while True:
try:
number: int = int(input(prompt))
except ValueError:
print("Invalid integer. Please try again.")
cont... | 508aabde982d310f52fca8cf80892edb7586db17 | 119,655 |
def merge(h1, h2):
"""
Returns a new dictionary containing the key-value pairs of ``h1`` combined with the key-value pairs of ``h2``.
Duplicate keys from ``h2`` overwrite keys from ``h1``.
:param h1: A python dict
:param h2: A python dict
:return: A new python dict containing the merged key-va... | a7d55808d5ee4e9652779276daa061db993c3587 | 141,923 |
def get_in_shape(in_data):
"""Get shapes of input datas.
Parameters
----------
in_data: Tensor
input datas.
Returns
-------
list of shape
The shapes of input datas.
"""
return [d.shape for d in in_data] | ae54409d425189c33fe9fe1bdb0487cc854f9510 | 25,579 |
def extract_jasmine_summary(line):
"""
Example SUCCESS karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 SUCCESS (0.205 secs / 0.001 secs)
Exmaple FAIL karma summary line:
PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.21 secs / 0.001 secs)
"""
# get tota... | f795ff015555cc3a2bd2d27527ae505a6dde9231 | 396 |
def set_recomputation_options(opts,
allow_recompute=True,
allow_stateful_recompute=None): # pylint: disable=unused-argument
"""Set re-computation options.
Args:
allow_recompute: Whether or not to re-compute instructions during training.
If this... | d0e4a6fbaf23401f5e5bba2ec9759627880529fc | 668,146 |
def chk_keys(keys, src_list):
"""Check the keys are included in the src_list
:param keys: the keys need to check
:param src_list: the source list
"""
for key in keys:
if key not in src_list:
return False
return True | 48706a1f39c06cf79b107ca67eb0a5c5e202fe08 | 678,492 |
def _get_first_non_empty_item(items):
"""
:param items: anything that is iterable
:return: first non empty value
In this filter the following values are considered non empty:
- None
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}.
Note: to guarantee... | 7880bef2183fa70cd8a24d61d48b18a28499d368 | 566,790 |
import codecs
def _open_file_with_cache(filename):
"""
Reads the input file and returns the result as a string.
This caches opened files to ensure that the audit functionality
doesn't unnecessarily re-open the same file.
"""
try:
with codecs.open(filename, encoding='utf-8') as f:
... | 099f35fde7b7fd813734fb79e024638a394ac15e | 189,577 |
import re
def validate_account_to_dashed(account):
"""
Validates the the provided string is in valid AdWords account format and converts it to dashed format.
:param str account: AdWords Account
:rtype: str
:return: Dashed format
"""
account = str(account).strip()
... | 30eae40d2b205aeebc99cfc38864893d2fe6e7b8 | 40,815 |
from typing import Dict
def wrap_multiple_str(wrapping_string: str):
"""Wrap multiple values in a wrapping string by passing a dict where the keys are the parameters in the wrapping string and the values are the desired values.
>>> wrap_multiple_str("hello {first} {second}")({ "first": "happy", "second": "wo... | 87a5bb85a7ca7586f1c7fa4d66f3c29b0809debe | 268,321 |
def set_list_of_lists(list_of_lists):
"""
Removes duplicated nested lists of a given list of lists, i.e. the set() equivalent for lists of lists
:param list_of_lists: A list of lists to take the set() of
:return: A set() equivalent to the given list of lists
"""
return [list(item) for item in se... | bb297a9c99a84c4dd68a0e4a62d3d9cee50d535b | 273,790 |
def rev_comp(item):
"""
Retuns the base on the opposite strand
"""
if item == 'A':
return 'T'
elif item == 'G':
return 'C'
elif item == 'T':
return 'A'
elif item == 'C':
return 'T'
else:
return 'N' | e38e1482b5682c6147ee6db6cdd92276d695c985 | 489,754 |
def str_to_list(data):
"""
Converts a string delimited by \n and \t to a list of lists.
:param data:
:type data: str
:return:
:rtype: List[List[str]]
"""
if isinstance(data, list):
return data
data = data.replace("'", '')
try:
if data[-1] == '\n':
d... | 17b2fda7b45041c101110b2405d3001798c8b258 | 403,595 |
import math
def truncate_floor(number, decimals):
"""Truncates decimals to floor based on given parameter
Arguments:
number {float} -- number to truncate
decimals {int} -- number of decimals
Returns:
float -- truncated number
"""
return math.floor(number * 10 ** decimals)... | 3f172b9947635662b59f2c5f31abb2cc13e31882 | 669,921 |
def b2i_le(value: bytes) -> int:
"""Converts a sequence of bytes (in little-endian order) to a single integer."""
value_int = sum(b * 2 ** (i * 8) for i, b in enumerate(value))
return value_int | 282dc9ef38681572c287f447cf4026b1b97c5c31 | 275,115 |
def create_lookup_tables(unique_words):
""" Create lookup tables for word_to_id and id_to_word
Args:
unique_words: dictionary of words in training set
Return:
word_to_id: dict with words as keys and corresponding ids as values
id_to_word: dict with ids as keys and corr... | 44a99e615c5be147039a2c030e8a45a8c01080b2 | 647,636 |
def _remap(station: dict, i: int):
"""Remaps a channel number to one based on the DVR index
"""
if station['channel'].isdigit():
new_channel = str(int(station['channel']) + 100 * i)
else:
new_channel = str(float(station['channel']) + 100 * i)
return (new_channel, station['callSign']... | 418160cd190299d11944d0fc0d9e74015fd339f2 | 555,689 |
def rotate(pattern, k):
""" Return a left circular rotation of the given pattern by k."""
if not type(k) == int:
raise TypeError("Second argument must be an integer")
n = len(pattern)
k = k % n
return pattern[k:n] + pattern[0:k] | 65ab067a02067ef26e300bd620407e71e63b2f95 | 525,652 |
def human_time(s):
"""Convert floating-point seconds into human-readable time"""
if s < 60.0: return "%.3f" % s
m = int(s) / 60
if m < 60: return "%d:%06.3f" % (m, s % 60)
return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60) | 5ab95271223ab65d44fce3c09e4f77e51e9be342 | 638,729 |
def get_motion_type(motion_detection_config):
"""Set default type if it is missing."""
if not motion_detection_config.get("type"):
motion_detection_config["type"] = "background_subtractor"
return motion_detection_config | b87f46f10f49a93f10aa0a7efcf530420ff1cef6 | 474,441 |
def get_system_columns(columns):
"""Filters leaderboard columns to get the system column names.
Args:
columns(iterable): Iterable of leaderboard column names.
Returns:
list: A list of channel system names.
"""
excluded_prefices = ['channel_', 'parameter_', 'property_']
return [... | 024dcdcd9c6327d3ac28a3b1c67bf7daa4953b99 | 647,222 |
def get_embedded(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the embedded object for link_relation. The returned object can be
treated as a result object in its own right.
'result_object' a JSON object returned by a previous API call.
The ... | a41bb87a1c8a55c7e0be966032fbf959d69bda6e | 674,878 |
def clip(value_before_switch, value_after_switch, t_switch, t):
"""
logical function of time. Changes value at threshold time t_switch.
"""
if t <= t_switch:
return value_before_switch
else:
return value_after_switch | 103a5aede1c1d0589e0acfc9ef058e011813f789 | 34,835 |
def take(src, idx):
"""Generate a list containing the elements of src of which the index is contained in idx
Parameters
----------
src: list (size: n)
Source iterable from which elements must be taken
idx: iterable (subtype: int, range: [0, n[, size: m)
Indexes iterable
Returns... | 4cfa42f8d4d5ec605633014823b27d2bdc4dd5ff | 499,498 |
def n_interactions(nplayers, repetitions):
"""
The number of interactions between n players
Parameters
----------
nplayers : integer
The number of players in the tournament.
repetitions : integer
The number of repetitions in the tournament.
Returns
-------
integer
... | 639d4bd535adba4db9117905ba6da66dfea51df6 | 205,601 |
def format_single_query(query):
"""
Formats the query parameters from a single query.
Parameters
----------
query : str
MongoDB-stype query.
Returns
-------
str
Query parameters.
"""
return f'?where={query}' | b2b7a30fa34a9ac2a2f41a10d018e69567ab923a | 408,642 |
from datetime import datetime
def unix_epoch_to_datetime(ux_epoch):
"""Convert number of seconds since 1970-01-01 to `datetime.datetime`
object.
"""
return datetime.utcfromtimestamp(ux_epoch) | 13edceec1631a2a3db06dad215380f609693f441 | 698,133 |
from typing import Union
import logging
def _level_to_int(level: Union[str, int]) -> int:
"""Convert a log level in str or int into an int.
Args:
level: Can be a string or int
Returns:
level as int.
"""
if not isinstance(level, int):
level = logging.getLevelName(level.upp... | 296529cb2160d94310da8a83d993e1e85fd4c354 | 596,434 |
def format_component_descriptor(name, version):
"""
Return a properly formatted component 'descriptor' in the format
<name>-<version>
"""
return '{0}-{1}'.format(name, version) | 2edb92f20179ae587614cc3c9ca8198c9a4c240e | 707,804 |
def get_foot_trajectory(data, header, foot):
"""Get the trajectory of the foot translations."""
tx = header.index(foot + "_tx")
ty = header.index(foot + "_ty")
tz = header.index(foot + "_tz")
return data[:, [tx, ty, tz]] | 4da8b4e947f3e3af6d7e39a11bdac7ad91a1715b | 258,167 |
def parse_tree_to_sql_where(parse_tree):
"""
Walks a parse tree of a filter expression and generates a Postgres WHERE
clause from it
"""
def next_element():
if len(parse_tree) > 0:
return parse_tree.pop(0)
where_clause = '('
cur = next_element()
while cur:
i... | de1ded97a876c7174037965160eed21c8530a10b | 401,836 |
def clean_state(state: str) -> str:
"""
Republica Virtual API returns a different state value when searching
for a district address. (i.e. "RO - Distrito" for 76840-000).
So let's clean it!
"""
return state.split(" ")[0].strip() | 8f6987ade1ea4cedc3d33593cd8077268a84d00e | 541,763 |
def read_def_file(def_file):
"""Read variables defined in def file."""
ret = {}
f = open(def_file, 'r')
for line_ in f:
if line_.startswith("#"):
continue
line = line_.rstrip()
if len(line) == 0:
continue
if "=" not in line:
continue
... | 3999378bca9ad4cdccaa480a50635ad567473c66 | 693,905 |
def surfaceTension(T, sTP):
"""
surfaceTension(T, sTP)
surfaceTension (dyne/cm) = A*(1-T/critT)^n
Parameters
T, temperature in Kelvin
sTP, A=sTP[0], critT=sTP[1], n=sTP[2]
A and n are regression coefficients, critT: critical temperature
Returns
surface tension in d... | 24980f54d9bd4760da44d3c453ac422f916917cc | 472,539 |
def merge_histos ( h1 , h2 ) :
"""Simple ``merger'' for historgams"""
if not h1 : return h2
h1.Add ( h2 )
return h1 | a0196a91a275ceca8689b3f70c4197ab674ed37a | 509,771 |
def make_adjlist(vertices, edges):
"""
Args:
vertices (List(int)): vertices of the graph
edges (List(tuple(int, int))): edges of the graph
Returns:
dict(int, List(int)): Adjacency list of thr graph
"""
adjlist = dict(zip(vertices, [[] for vertex in vertices]))
for u, v i... | ceb461666e0a8084a80d81aeda08a5a154d2cc56 | 448,554 |
import unicodedata
def is_latin(text):
"""
Function to evaluate whether a piece of text is all Latin characters, numbers or punctuation.
Can be used to test whether a search phrase is suitable for parsing as a fulltext query, or whether it
should be treated as an "icontains" or similarly language ind... | e804ffd688a8713e1e4362ac7fbb868a6dbff45c | 131,759 |
def change_eigen_param(self, param_name, new_value):
"""
Used to change a param in eigen params area.
Parameters
----------
param_name : str
name of parameter to change
new_value : ?
the new value to the parameter
Returns
-------
True if successful
"""
if par... | 2dc9d97fe154ce6c3a6ccee9c93fe03e9c139d3b | 574,366 |
def _pixel_addr(x, y):
"""Translate an x,y coordinate to a pixel index."""
if x > 8:
x = x - 8
y = 6 - (y + 8)
else:
x = 8 - x
return x * 16 + y | 71a718943663cd1e7f3026f1b51ef6c112a3e59a | 204,029 |
def try_lower(string):
# Ask for, forgiveness seems faster, perhaps better :-)
"""Converts string to lower case
Args:
string(str): ascii string
Returns:
converted string
"""
try:
return string.lower()
except Exception:
return string | 7b48401d4aaf4ae5a99b3a2d9ee5869c07726156 | 630,906 |
def compareNoteGroupings(noteGroupingA, noteGroupingB):
"""
Takes in two note groupings, noteGroupingA and noteGroupingB. Returns True
if both groupings have identical contents. False otherwise.
"""
if len(noteGroupingA) == len(noteGroupingB):
for (elementA, elementB) in zip(noteGroupingA, n... | 3e48d0bab407e7327b7be20a327434dc1371f575 | 566,046 |
from typing import Dict
from typing import Any
def abi_input_signature(input_abi: Dict[str, Any]) -> str:
"""
Stringifies a function ABI input object according to the ABI specification:
https://docs.soliditylang.org/en/v0.5.3/abi-spec.html
"""
input_type = input_abi["type"]
if input_type.start... | e2ed8b9587066b1edcbd3563c8c45ceb64dc1442 | 645,699 |
import math
def get_current_pose(measurement):
"""Obtains current x,y,yaw pose from the client measurements
Obtains the current x,y, and yaw pose from the client measurements.
Args:
measurement: The CARLA client measurements (from read_data())
Returns: (x, y, yaw)
x: X position ... | 42c5ba8a79de5ee9e46a7b72e62e0b63a4ec4c66 | 242,123 |
import torch
def create_simple_image(size, batch=1):
"""
returns a simple target image with two and a seeds mask
"""
sizex, sizey = size
target = torch.zeros(batch, 1, sizex, sizey).long()
target[:, :, :, sizey//2:] = 1
seeds = torch.zeros(batch, sizex, sizey).long()
seeds[:, 3 * siz... | d05cf2febe9e7f4fbc94288521696f9c1cae5745 | 500,654 |
def dotget(root, path: str, default=None) -> object:
""" Access an item in the root field via a dot path.
Arguments:
- root: Object to access via dot path.
- path: Every dot path should be relative to the state property.
- default: Default value if path doesn't exist.
Returns: Value. If path do... | 2fa846bf0cc9c4da7927968d0b208f4381470e0c | 347,992 |
def beta_mean(alpha, beta):
"""Calculate the mean of a beta distribution.
https://en.wikipedia.org/wiki/Beta_distribution
:param alpha: first parameter of the beta distribution
:type alpha: float
:param beta: second parameter of the beta distribution
:type beta: float
:return: mean of the ... | 2d730b5693dba71b07347d7564fed26d0182af7b | 346,657 |
from pathlib import Path
import re
def matches_filepath_pattern(filepath: Path, pattern: str) -> bool:
"""
Check if filepath matches pattern
Parameters
----------
filepath
The filepath to check
pattern
The pattern to search
Returns
-------
rc
A boolean in... | dbec77f7302d3ad319a0220ef1f29c14ca093486 | 368,347 |
def get_all_names(obj):
"""
Should return all possible names for object, for example real name of user or food, nick...
:param obj: user or food
:return: list of strings
"""
res = list()
if "name" in dir(obj):
if obj.name is not None:
res.append(obj.name)
if "nick" ... | b6b0a879a3d15919813785e70157e1a8f209c654 | 510,233 |
def JtoBTU(eJ):
"""
Convertie l'energie en Joules vers Btu
Conversion: 1 Btu = 1055 Joules
:param eJ: Energie [J]
:return eBTU: Energie [btu]
"""
eBTU = eJ / 1055
return eBTU | c0720b9ed82715415b6233f09c17411e996be6ae | 184,865 |
import errno
def _maybe_read_file(path):
"""Read a file, or return `None` on ENOENT specifically."""
try:
with open(path) as infile:
return infile.read()
except OSError as e:
if e.errno == errno.ENOENT:
return None
raise | 40a6b89eeb4acb9ef3bb5244ba54a86d8ec64efc | 148,391 |
def validated_slot_value(slot):
"""return a value for a slot that's been validated."""
if slot is not None:
for resolution in slot['resolutions']['resolutionsPerAuthority']:
if 'values' in resolution:
return resolution['values'][0]['value']['name']
return None | edef74d5eedb5f15579992c8762114439f399577 | 425,867 |
def count_lines(fasta_file):
"""
Counts number of lines in a fasta file
:param (str) filename: FASTA file
:return (int): number of lines in file
"""
return sum(1 for line in open(fasta_file)) | db3eeff277cbd7291c265ad9a21bb07645b9a24d | 327,156 |
def get_org_name(organisation):
"""Get short name for organisation (--> org.)."""
if organisation.endswith("organisation") or organisation.endswith("organization"):
return organisation[:-9] + "."
else:
return organisation | 7471100d5eba7b12fda080a7c74440d1976baffa | 477,812 |
def get_years(ncfiles, sep='-'):
"""
Retrieve a list of years from a list of netCDF filenames.
Parameters
----------
ncfiles : list
List of filenames from which years will be extracted.
sep : TYPE, optional
Separator. The default is '-'.
Returns
-------
years : set
... | 101424ab4d0d6958097dae63c7afced1dc676b75 | 495,922 |
import glob
def get_image_paths(dataset='cars'):
"""
Loads image paths for selected dataset.
:param dataset: Dataset that should be loaded. ['cars', 'notcars']
:return: Path list
"""
path_list = []
if dataset == 'cars':
print('Loading data set for \'cars\'...')
# GTI
... | e644fa7a8d83b5bf27375b9558f317ff0ed9e2c8 | 92,089 |
def is_event_match_for_list(event, field, value_list):
"""Return if <field> in "event" match any one of the value
in "value_list" or not.
Args:
event: event to test. This event need to have <field>.
field: field to match.
value_list: a list of value to match.
Returns:
... | 3e6e14391d04a566933be829fcbd8d0fd089e98b | 174,465 |
def writeContactPoint(cp):
"""Writes a contact point to text 'x1 x2 x3 n1 n2 n3 kFriction'"""
return ' '.join([str(v) for v in cp.x+cp.n+[cp.kFriction]]) | 49f54e04c29d87acb662d81da385ca409e7bd959 | 519,320 |
def calculate_residuals(fit_function,a,xdata,ydata):
"""Given the fit function, a parameter vector, xdata, and ydata returns the residuals as [x_data,y_data]"""
output_x=xdata
output_y=[fit_function(a,x)-ydata[index] for index,x in enumerate(xdata)]
return [output_x,output_y] | 1996a0782baa3e95a97d34324b22584a852179a8 | 244,033 |
def string_to_int(value):
"""Converts a string to an integer
Args:
value(str): string to convert
Return:
The integer representation of the nummber. Fractions are truncated. Invalid values return None
"""
ival = None
try:
ival = float(value)
ival = int(ival)
e... | d9b251be776d721d25ec35bf7fa558e4e3b68f00 | 660,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.