content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import itertools
def drop(n, seq):
""" The sequence following the first n elements
>>> list(drop(2, [10, 20, 30, 40, 50]))
[30, 40, 50]
See Also:
take
tail
"""
return itertools.islice(seq, n, None) | 3017d7881de54f2d96f362f041b3202c27dcf6f4 | 619,218 |
def zodiac_compatibility(user_sign, friend_sign):
""" Using comparison operators and conditionals, returns a given compatibility message.
Parameters
----------
user_sign : str
The user's zodiac sign as determined by their birthday input.
friend_sign : str
... | 35b872117d2df5bd8737f5a7693f6553a5c241ca | 619,221 |
from typing import List
from typing import Callable
def delete(route: str, additional_methods: List[str]=[]) -> Callable:
"""
States that a function will be executed when a DELETE request
is sent to the server.
"""
return lambda func: (route, 'DELETE', func, additional_methods) | 2e6c27338ac9c4a874219c54d8f0a8d42fd1a329 | 619,228 |
def get_category_from_topchart_url(url: str) -> str:
"""Return the category from an url.
Throws an error if the url isn't recognized.
"""
category = url.split("/")[3]
# check category
if category not in [
"films",
"series",
"jeuxvideo",
"livres",
"bd",
... | f32296ef176e70df0abf39d8391df394db6bc9d2 | 619,229 |
def is_output_node(node):
"""
Determine whether a RedBaron node may be expected to generate output.
Parameters
----------
node : <Node>
a RedBaron Node.
Returns
-------
bool
True if node may be expected to generate output, otherwise False.
"""
if node.type == 'p... | 54c83aaf785b5c8d0ab3af7e708649d88d299cea | 619,231 |
def rk4_backward(f, x, h, **kwargs):
"""Implements a backwards classic Runge-Kutta integration RK4.
Parameters
----------
f : callable
function to reverse integrate, must take x as the first argument and
arbitrary kwargs after
x : numpy array, or float
state needed by functi... | f1a017131b41303d82392d7b9283a4ee2955064b | 619,232 |
def car_blueprint_filter(blueprint_library):
"""
Exclude the uncommon vehicles from the default CARLA blueprint library
(i.e., isetta, carlacola, cybertruck, t2).
Parameters
----------
blueprint_library : carla.blueprint_library
The blueprint library that contains all models.
Retur... | 4549da6923f4a50f81c3d55a504b3d3bc603c057 | 619,235 |
def multiply_vector(vector: list, number: float) -> list:
"""Multiply a vector."""
multiplied_vector = [value * number for value in vector]
return multiplied_vector | 30577d7f75bff6d4a27d60239011e1cec2beb5be | 619,239 |
def _format_deps(deps_list):
"""Maps a list of dependencies into a single string."""
stripped_deps = [l.strip() for l in sorted(deps_list)]
indented_quoted_deps = [' "{}",'.format(l) for l in stripped_deps]
return '\n'.join(indented_quoted_deps) | 1c0848dad84f506f1cc0b193eb3260d4d5e06791 | 619,241 |
def identity(x):
"""A function that does nothing (the default parse action)"""
return x | f38fcf90241788cf90c01cb44ac17b2879496b87 | 619,243 |
def is_letter_guessed_correctly(player_input, secret_word):
""" check whether the (guessed_letter/ player_input) is in the secret_word
Arguments:
player_input (string): the player_input
secret_word (string): the secret, random word that the player should guess
Returns:
boolean: True if the player_in... | 2fd0840300ae16aba4ba1d997c4cd98343778f74 | 619,247 |
def RCI_calc(mutual_information, reference_entropy):
"""
Calculate RCI (Relative classifier information).
:param mutual_information: mutual information
:type mutual_information : float
:param reference_entropy: reference entropy
:type reference_entropy : float
:return: RCI as float
"""... | 73f0b76d8162ecabeb052f73b93445f6c12275ac | 619,248 |
def solve_optimisation_investment(model):
"""
Parameters
----------
model : oemof.solph.Model
The oemof model, which is optimized.
Returns
-------
dict : Results of optimisation. Contains:
- 'oemof' : Complete "oemof" results of the energy system optimisation (.results['mai... | 9aeb23407654aa9b51e6c3877ae376691585b138 | 619,250 |
def d_file_query(query_utils):
""" Retrieve D1 or D2 data.
Args:
query_utils: object containing:
file_utils: fileD1 or fileD2 utils
sess: database session
agency_code: FREC or CGAC code for generation
start: beginning of period for... | 82030c598ac8aa363e1ce53008d5928a46923d0b | 619,254 |
def rgb2hex(rgb) -> str:
"""Convert an RGB sequence to a hexadecimal color.
The values of the sequence need to be in ``range(256)``.
>>> rgb2hex([0, 255, 255])
'#00ffff'
"""
return '#%02x%02x%02x' % tuple(rgb) | 7b7240bbd260d8c0d17484f24eb96fdee4223974 | 619,258 |
def time_diff(end, start):
"""Take two times formatted HHMM and return end-start, in hours."""
end = 60 * int(end[:2]) + int(end[2:])
start = 60 * int(start[:2]) + int(start[2:])
return float(end-start) / 60 | c0d624760e128d48c30268ec81ecd0ae572996a5 | 619,264 |
def filter_bad_ra_dec(table_data):
"""Remove targets with bad RA and/or Dec values from the input table.
Use the column masks to find which entries have bad RA or Dec values.
These will be excluded from the Mirage catalog.
Parameters
----------
table_data : astropy.table.Table
Input tab... | f0c8c4ca077abb83c43e7dfdedc0e858dbe0a97a | 619,266 |
def get_parent_key(key):
"""
Gets the key of the parent object. Assumes keys are formatted like
param1__param2__param__3__...
Parameters
----------
key: str
The key whose parent we want.
Output
------
parent_key: str
The parent key
"""
return '__'.join(key.... | b49f706271f50bc38f2a789dcc90b72db2fea731 | 619,268 |
def is_remote(url):
"""Checks whether the specified value is a remote url.
"""
prefixes = ["http", "file", "git"]
for prefix in prefixes:
if url.startswith(prefix):
return True
return False | 077956e905fee3f41758d3d237f09615678486f8 | 619,271 |
from bs4 import BeautifulSoup
def title_card_factory(title: str, sub_title: str, image_link: str = ""):
"""
For creating title card HTML.
Args:
title (str): Title on the title card.
sub_title (str): The subtitle below the title card.
image_link (str, optional): The image on the ti... | 7ea4466d9834f420b9cb6d1f91d92cc2d97de8fe | 619,272 |
import math
def G(x, sigma):
"""
Calculates a gaussian kernel"""
return ((1 / (2 * math.pi * pow(sigma, 2))) *
math.exp(-(pow(x, 2) / (2 * pow(sigma, 2))))) | 6a87ab5e7c668b091e85f41ebe5e8134de32c433 | 619,273 |
from typing import AbstractSet
import pathlib
def get_available_gpus() -> AbstractSet[int]:
"""Return available gpu index numbers.
Returns:
AbstractSet[int]: index numbers of available GPUs
"""
try:
p = pathlib.Path("/proc/driver/nvidia/gpus")
gpu_count = len(list(p.iterdir()... | 9969a944183654f7416d566567ffbd8b0b377277 | 619,274 |
def flip_bbox(bbox, size, y_flip=False, x_flip=False):
"""Flip bounding boxes accordingly.
The bounding boxes are expected to be packed into a two dimensional
tensor of shape :math:`(R, 4)`, where :math:`R` is the number of
bounding boxes in the image. The second axis represents attributes of
the bo... | 499794862dc6a6d10542edcbfb3f5b57b523f744 | 619,275 |
def pointToGridIndex(x, y, z, sx=1.0, sy=1.0, sz=1.0, ox=0.0, oy=0.0, oz=0.0):
"""
Convert real point coordinates to index grid:
:param x, y, z: (float) coordinates of a point
:param nx, ny, nz: (int) number of grid cells in each direction
:param sx, sy, sz: (float) cell size in each directio... | 8df63aa196ed3bec7bcc0ae6478b51308a2a0ab9 | 619,278 |
def round_robin(
num_tasks,
num_resources,
verbose=False):
"""Round-Robin scheduling algorithm.
Parameters
----------
num_tasks : int
Number of tasks
num_resources : int
Number of resources
verbose : bool [default=False]
True if messages should be... | 901bcde2fd7dc64df3b1bb748b412feade506b65 | 619,280 |
def normalize_prisma_url(url: str) -> str | None:
""" Correct common Prisma Cloud API URL misconfigurations """
if not url:
return None
return url.lower().replace('//app', '//api').replace('http:', 'https:').rstrip('/') | 01bed9098ea0a14a2c9379357fe1466676f5d734 | 619,285 |
import six
def find_dict(iterable, **rules):
"""Search for dict in iterable of dicts using specified key-value rules."""
for item in iterable:
# assert all key-value pairs from rules dict
ok = True
for k, v in six.iteritems(rules):
ok = ok and k in item and item[k] == v
... | 25b85b74c65ca452b54a708ffee4cfa7a07093aa | 619,286 |
def _get_field_by_name(model, field):
"""
Retrieve a field instance from a model by its name.
"""
field_dict = {x.name: x for x in model._meta.get_fields()} # noqa
return field_dict[field] | eecb9e47c4113c952c112ee9671182264649f283 | 619,288 |
import math
def get_distance(i, j):
"""
Calculates the number of rounds before two songs would meet in a match.
If the songs would meet in the first round, returns 0. To determine a more
human-readable (1-indexed) round number for when two songs would meet (or,
the maximum number of rounds), call... | a0d66642722cd8c7730494ca17230c0e418e8a79 | 619,289 |
def count_trees_in_path(matrix, start, slope):
"""Given a slice of a larger repeating matrix, and a slope for
a path through the matrix, count the number of trees in the path.
:param matrix: 2D array representing slice of larger matrix
:param start: tuple of starting position
:param slope: tuple of run/rise (rig... | 91aee4b9cb63c939bdd5e8e3b7ac0e9d0807516f | 619,293 |
def scatter2D(ax,x,y,colorList,ec='black'):
"""
This function is to be called by makeScatter2D, creates a 2D scatter plot on a given axis with
colors determined by the given colorHandler or an optional override
:Arguments:
:type ax: matplotlib Axis2D
:param ax: Axis on which scatter... | 6745904d6bf32262ed787d19293d5dd02e41dd98 | 619,298 |
def _get_urls(driver):
"""Returns the list of URLs in tabs."""
urls = []
for w in driver.window_handles:
driver.switch_to.window(w)
urls.append(driver.current_url)
list.sort(urls)
return urls | d946f36a442a38092e3bd54c4686430f40f7f7c3 | 619,300 |
def get_micro_secs(real_str: str) -> int:
"""
If there is a decimal point returns fractional part as an integer in units
based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional
part is returned as an integer representing microseconds. Zero returned if no factional part
... | 33f602bbfff3f18510609beaa7a2153b6ab35c9e | 619,303 |
def idx_to_string(val):
"""Convert index to base pair
"""
idx_to_string = {0: "A",
1: "C",
2: "G",
3: "T"}
return idx_to_string[val] | 04c5935c2a5af8ce303142b11d066fe1d07645d6 | 619,308 |
import re
def is_username_valid(username):
"""
Check if a username is valid.
:param username: The username to validate.
:return: True if the username is valid; False otherwise.
"""
valid_username_regex = re.compile('^[a-zA-Z0-9\-_]+$')
return bool(re.match(valid_username_regex, username)) | 669ce73a2aa945d8a8e355a881ea58621c5b0ffb | 619,310 |
def batch_all(dataset, batch_size):
"""Batches all splits in a dataset into batches of size `batch_size`."""
return {
key: dataset[key].batch(batch_size)
for key in dataset.keys()
} | e04a3b87d140dece20c90c38f8f2149ad721c292 | 619,317 |
def translate(rna_sequence):
"""
Compute the protein that will be produced by the given RNA sequence.
Parameters
----------
rna_sequence : string
The RNA strand we are evaluating.
Returns
-------
protein : string
The resulting protein from evaluating the codons in the R... | b7033d05f66357e20b0c73dc2819636407a5dd87 | 619,318 |
from typing import Callable
def build_schedule(lr: float, final_lr: float, n_epochs: int) -> Callable:
"""
Builds the schedule of which the learning rate decreases.
The schedule makes the learning rate decrease linearly.
:param lr: initial learning rate.
:param final_lr: final learning rate.
... | 04efe4b0fc0edb576e1359afdf9ee9272420b91e | 619,320 |
import json
def LoadNotebook(filename):
"""Read a IPython notebook (.ipynb).
Reads the file and parses it as JSON.
Args:
filename: The path to the .ipynb file.
Returns:
A parsed JSON object (dictionary).
"""
with open(filename) as f:
return json.load(f) | d8fbefd2b9891bfc8d6e5d2876c4c400b8219990 | 619,325 |
def df_drop_duplicated_index(df):
"""Drop all duplicated indices in a dataframe or series"""
df2 = df.copy()
return df2[~df2.index.duplicated(keep='first')] | aa9666d098d7f07687603cfafe4b9fd0a595e51e | 619,327 |
def meanSubNormalize(cyDf, cyVars=None, compCommVars=None, meanVar=None):
"""Normalize cytokine columns by the log-mean for each patient, within each compartment.
The point is that if cytokine concentrations are generally high for one sample or another,
this might dominate the covariation of cytokines acros... | b2467cf5c7efeb312b9891e50408e06070c973c6 | 619,332 |
def select(iterable, conditional):
"""
Looks through each value in the list, returning an array of all the values that pass a truth test (conditional).
params: conditional, iterable
iterable -> list, sequenece, set, dictionary, generator etc
conditional -> a lambda or function that takes ... | 1e3abc9abe47b1ba4c3800f359750487db138427 | 619,334 |
def pad(names):
"""
Make all strings in list *names* the same size for f2py's benefit.
"""
return [ "%-16s"%v for v in names ] | acf4e05b619b0d297cefb02877fc3858d09264bb | 619,336 |
from typing import Tuple
def hflip_bboxes_helper(bbox: Tuple, **kwargs) -> Tuple:
"""
When the src image is horizontally flipped, the bounding box also gets horizontally
flipped
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
return (1 - right_factor, upper_factor, 1 - left_fa... | 2a21d3f1526d53560a4640e4f0708b269417b815 | 619,340 |
def is_supported_english_translation(translation):
"""
A helper function to determine if the provided string is a supported English translation.
:param translation: Translation code
:type translation: str
:return: True = the translation is not supported, False = the translation is supported
:rt... | 862bc1f8d8eaaaede921ceabe530d78d1658b874 | 619,342 |
def load_haiku(filename):
"""Open and return training corpus of haiku as a set."""
with open(filename) as in_file:
haiku = set(in_file.read().replace('-', ' ').split())
return haiku | b7604218820faaa51161586801e585551cb396d1 | 619,344 |
def isType(val, types):
"""
Check if val is of a type in types.
"""
for a_type in types:
if isinstance(val, a_type):
return True
return False | d8e16a89802b3f1f6b4ad19efe91bf8c7c1ab08a | 619,345 |
def int_to_rgb(rgb_int):
"""
Given an integer, converts to to RGB value. Any integer outside
the range of (0, 16777215) will raise an invalid
>>> int_to_rgb(-1)
Traceback (most recent call last):
...
ValueError: Integer must be in range [0, 16777215], got -1.
>>> int_to_rgb(0)
(0, 0,... | c23eef48c564dcb18eec81c1890add55d77fd3a5 | 619,346 |
import configparser
from typing import Dict
from typing import Any
def ConfigParser_to_Dict(config: configparser.ConfigParser) -> Dict:
"""
Convert ConfigParser object to dictionary.
The resulting dictionary has sections as keys which point to a dict of the
section options as key => value pairs.
I... | b2b20aa39d08ae929288e875b4733d91e8a9fca7 | 619,347 |
def timestamp(date_object):
"""Generate a trakt formatted timestamp from the given date object"""
fmt = '%Y-%m-%d:T%H:%M:%S.000Z'
return date_object.strftime(fmt) | 9949d3fec6ca7df94a7db0b8f41186adc572bbe6 | 619,348 |
import re
def is_sale(this_line):
"""Determine whether a given line describes a sale of cattle."""
has_price = re.search(r'[0-9]+', this_line)
is_not_succinct = len(re.split(r'\s{3,}',this_line)) > 3
return bool(has_price and is_not_succinct) | 2e456b1a5c961ee0f9632d279de6ce1747e3c30c | 619,350 |
from typing import List
from typing import Dict
from typing import Any
def total_zones(endpoints: List[Dict[str, Dict[str, Any]]]) -> int:
"""
Returns the true unique number of zones, taking into account
that multiple endpoints can have the same zone name.
- us-west-1
- us-west-1 == 2 zones
... | 56a536b4582ef18586cf893e6029f8dc83d051a8 | 619,352 |
def get(isamAppliance, kdb_id, cert_id, check_mode=False, force=False):
"""
Retrieving a personal certificate from a certificate database
"""
return isamAppliance.invoke_get("Retrieving a personal certificate from a certificate database",
"/isam/ssl_certificates/{0}/p... | cb07dcba66d476b9fbb483d537e4a00cea9ca30f | 619,353 |
from typing import Union
from typing import Any
def cast2lowercase(input: Union[list, tuple, str]) -> Any:
"""Cast input into lowercase.
Example:
>>> cast2lowercase('Hello World')
'hello world'
>>> cast2lowercase(['Hello', 'World'])
['hello', 'world']
"""
inputs = []
... | 397d3887c67ce26613b87cfe0aa762cafe080e2f | 619,355 |
import random
import string
def get_random_string(n):
""" Create random string with len `n`
"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=n)) | b1d354d8a7f1a4c3520e865fd87e2f2ca048699e | 619,359 |
def c_string_to_str(array) -> str:
"""
Cast C-string byte array to ``str``.
"""
return bytes(array).partition(b'\0')[0].decode('utf-8') | dee909c1f57970ac97d19377fcde778b4e2fde6c | 619,360 |
import hashlib
def etag_checksum(filename: str, chunk_size: int = 8 * 1024 ** 2) -> str:
"""\
Compute the `ETag` digest (which is not the `MD5` digest) of an object.
:param filename:
Path to file target file
:param chunk_size:
Chunk size to hash
:return:
`ETag` `hexdigest... | 1689f1ad099c4224ea7c77d1fe4488f62cd3fb0b | 619,368 |
def get_itim(tree, hart):
"""Get the ITIM associated with the hart"""
itim_ref = hart.get_field("sifive,itim")
if itim_ref:
itim = tree.get_by_reference(itim_ref)
return itim
return None | 7ee45e0fa74e1aac20936699830c715c44053842 | 619,374 |
def get_sma(data, length):
""" Returns the simple moving average over a period of LENGTH """
if len(data) < length:
return "Not enough Data"
subset = data[-length:]
return sum(subset) / len(subset) | ea1e393124e656222edaa75bcde11adcfd52fc9c | 619,376 |
def filter_timeseries_by_columns(data, columns):
"""
Filters features in multi-variate time series data
input (data): 3D numpy array with time series format
input (cols): array with columns (integer encoded) to be chosen
return (data): 3D numpy array with no. of featues = len(columns)
"""
... | 4b2476010337ca420337b34d6438aef19c346949 | 619,385 |
def get_n_bits(report):
"""Gets the number of bits that have each line from the input report.
Args:
report (list): Input report that contains a binary number for each line.
Returns:
int: How many bits have each binary number.
"""
return len(report[0])-1 | 3ecc31046c3e6c1691ff4f8d77910ad025ad9373 | 619,390 |
def is_int(string):
"""
Check if `string` can be converted
into an int.
Parameters
----------
string : str
String to check.
Returns
-------
check : bool
True if `string` can be converted.
"""
try:
int(string)
return True
except ValueError:
return False | 13402e552874e1cc71ad963b1ca43394488428bc | 619,392 |
import re
def eval_expr(expr: str) -> str:
"""
Compute and return the result of *expr*.
>>> eval_expr("2 ^ 30")
'1073741824'
*expr* is sanitized and only a small range of characters are allowed:
>>> eval_expr("cat /etc/passwd") # doctest: +ELLIPSIS
Traceback (most recen... | 7be83d4439d64662ab4384da2cc145420f967cb2 | 619,393 |
def get_var_val(key, ii, varDict):
"""Gets an input in the likes of ${var} and returns the corresponding var value from the dict
Parameters
----------
key: string
unparsed key of var
ii: int
current iteration idx
varDict: dict
variable dictionary
Returns
-------... | 81df687051e4fa3bcf1d1e6f08bdfa430138ee29 | 619,399 |
import typing
from typing import Any
def repr_for_fp(fp: typing.IO[Any]) -> str:
"""
Helper to make a useful repr() for a file-like object.
"""
name = getattr(fp, "name", None)
if name is not None:
return repr(name)
else:
return repr(fp) | db91e14fa7d1b5f44d8e8a35901777ea6b095b08 | 619,401 |
import re
def ignore_timestamp(text):
"""
Remove a time stamp from a string to ease comparison.
This function removes timestamps generated using the following method::
time.strftime('%B %e, %Y at %H:%M')
This makes it easy to compare two strings for equality without even though
the embe... | 9018f2c9283addcb7c854010e973627c6a1a9941 | 619,403 |
import math
def _ceil_with_max(num, max_value):
"""
Ceil function that also takes a max value, to deal with possible rounding errors.
Rounding errors in floats can cause out of index errors when we index into an array.
"""
return min(math.ceil(num), max_value) | d362296a19fa0fcb3905aa936def15681f4b6c43 | 619,409 |
def _string_parser(strip_whitespace):
"""Returns a parser function for parsing string values"""
def _parse_string_value(element_text, _state):
if element_text is None:
value = ''
elif strip_whitespace:
value = element_text.strip()
else:
value = element... | b00c6cdefb900dfafc03da1d35195213220447e2 | 619,410 |
from typing import Tuple
import re
def do_substitution(content: str, pattern_sub: list[Tuple[re.Pattern, str]]) -> str:
"""Do the substitution using pattern and sub."""
for pattern, sub in pattern_sub:
content = pattern.sub(sub, content)
return content | f602415f111ceb4a127c6fe8aea431373eab236f | 619,412 |
def estimate_lm_score(sequence, ngrams):
"""
Compute the log score of a sequence according to given language model.
:param sequence: list of token ids
:param ngrams: list of dicts, as returned by `read_ngrams`
:return: log probability of `sequence`
P(w_3 | w_1, w_2) =
log_prob(w_1 w_2 w_... | 851f061255954aaedfa7e73eb84a630d3b658c4b | 619,418 |
def remap_range(
val: float,
old_min: float,
old_max: float,
new_min: float,
new_max: float,
) -> float:
"""
Remaps a value from one range to another range.
Args:
val: A number form the old range to be rescaled.
old_min: The inclusive 'lower' bound of the old range.
... | fabfbccba970be590354f6e9dcf955003c99641e | 619,420 |
def _read_statements(filename):
"""
reads sql statements from file, where statements are separated using a single
newline
:param filename: path to ascii file contaning sql statements
:return: list of sql statements
"""
with open(filename, 'r') as f:
lines = f.readlines()
# on uni... | 8e7140b5161778909d349cc996161440ab27a56f | 619,423 |
def hashToBinary(hashValue):
"""Convert hashed value of type bytes32 into an array of binary digits in a string"""
tmp = bin(int(hashValue, 16))[2:];
prefix = '0' * (256 - len(tmp))
return prefix + tmp; | 22e2e5663f1db545e1cfdb69583eeee94deb96d4 | 619,424 |
def trim(string):
"""Trim a multi-line string (the idea is taken from PEP 257)."""
lines = string.splitlines()
indent = 0
while lines[1][indent] == ' ':
indent += 1
return lines[0] + '\n' + '\n'.join(line[indent:] for line in lines[1:]) | 6e1c76209930b626fe5d00b40e2421063a4cc334 | 619,425 |
def insert_sil(phones):
"""
Insert silences.
Parameters
----------
phones : list
A list of phone sequence
Returns
-------
out : list
A list of new labels.
"""
out = []
for i,(s,e,p) in enumerate(phones):
if out:
if out[-1][... | 91a8207da28aa5777849d09b25a4ceabcf68b611 | 619,426 |
def get_file_source(filename):
# type: (str) -> str
"""Read the source of a file.
This convenience function is present to match the interface of get_module_source.
Args:
filename (str): the path of the file to read
Returns:
str: the contents of the file
"""
with open(filen... | 6f1396c97d231f74325705acbef6791d6adf5f47 | 619,427 |
def compute_log_zT(log_rho, log_seebeck, log_kappa, log_temperature):
"""Returns the log of the thermoelectric figure of merit."""
return 2 * log_seebeck + log_temperature - log_rho - log_kappa | bd0ca63fede373f5dd78ae2acd9a43f8190400ef | 619,429 |
def ret_normalized_vec(vec, length):
"""Normalize a vector in L2 (Euclidean unit norm).
Parameters
----------
vec : list of (int, number)
Input vector in BoW format.
length : float
Length of vector
Returns
-------
list of (int, number)
L2-normalized vector in Bo... | 9bbb1de11975fdc282e4ecc5e2a6d72f57cd30f9 | 619,432 |
def calculate_discrete_classifier_point(instances, threshold):
"""
From a list of instances, calculate the coordinates for a discrete classifier
that uses the given threshold.
"""
TP = 0 # True positives
FP = 0 # False positives
P = 0 # Total positives
N = 0 # Total negatives
fo... | 967f5106e3f591114e4c50becbb0cf6280f8e78b | 619,434 |
def remote_prd_mock(url, request):
"""
Mock for remote PRD info.
"""
thebody = b'{"PRD-63999-999":{"curef":"PRD-63999-999","variant":"Snek","last_ota":"AAZ888","last_full":"AAZ999"}}'
return {'status_code': 200, 'content': thebody} | ee42ce3f7872455222047df8d0970f6aec335b7c | 619,435 |
def add_columns_with_default(event, field_and_default_dict):
""" Adds a column with the default value to every event where it's not already present
:param event: A dictionary
:param field_and_default_dict: A dictionary with keys and default values {field_1: default_for_field_1, field_2: default_for_field_2... | 7911cdbefe04e717d780acf0e7e3970122d76f3c | 619,436 |
import re
def modify_flexlogger_paths(s: str) -> str:
"""Modify flexlogger.* paths in the given string to hide implementation modules.
Examples:
>>> # Basic usage
>>> modify_flexlogger_paths("flexlogger.foo._abc.Abc")
'flexlogger.foo.Abc'
>>> # Modify all paths in the string
... | 4042d49f2c4b43d0188627e6de5b17fe07724d2e | 619,437 |
import json
def get_feed_by_path(path):
"""
This fetches the feed from a given path
:param path: Full path to file
:return: DiscoFeed as python object
"""
try:
with open(path, 'r') as fin:
return json.load(fin)
except:
raise Exception("Could not read file or rec... | 9f1799da847467a3af9e67dd724a0b236de0bc0d | 619,440 |
import re
def _default_parse(raw_inp, choices, *args):
"""
Helper to parse default input to a node decorated with the node_list decorator on
the form l1, l 2, look 1, etc. Spaces are ignored, as is case.
Args:
raw_inp (str): Input from the user.
choices (list): List of available optio... | dc033c13728a41cfa9f896b17e0fcb044264ed42 | 619,441 |
def import_profile(database, species, loci_list):
"""Import all possible allele profiles with corresponding st's
for the species into a dict. The profiles are stored in a dict
of dicts, to easily look up what st types are accosiated with
a specific allele number of each loci.
"""
# Open allele p... | 552ba8d3190fd06c9e35c08f19784bf9b1e485df | 619,443 |
def sortedSeasons(m):
"""Return a sorted list of seasons of the given series."""
seasons = m.get('episodes', {}).keys()
seasons.sort()
return seasons | 111e7076528d1d86169a5a8e3a4ab36c6973597e | 619,447 |
from typing import ByteString
from typing import Optional
def hexdump_line(_bytes: ByteString, length: Optional[int] = None) -> str:
"""Create a hexdump formatted line for supplied bytes.
If length is greater than len(_bytes), the line will be padded with ASCII
space characters to indicate no byte data i... | 6c12c79c124916bbaca97b0e9b12665903f0758b | 619,448 |
def is_aware(dtime):
"""test if a datetime instance is timezone aware"""
if dtime.tzinfo is not None and dtime.tzinfo.utcoffset(dtime) is not None:
return True
else:
return False | 5f3826cc83221a452164d891715024092d0274ca | 619,450 |
def bad_words_getter(occurences, occurences_min=2):
"""From a dictionnary, returns in a list all keys with lower value than the minimum given in input """
"""In the context: returns all words that appears less than the minimum given"""
bad_words = []
for key,value in occurences.items():
if value... | bdb4132d06ac19497c39c1b5be994a31534a3ceb | 619,452 |
import hashlib
def dt_encode_topic(topic: str) -> str:
"""
Encode any string to be accepted by Digital Twin setSource. Use byte encoding and sha256-hashing.
:param topic: Topic name to be encoded.
:return: Hashed-encoded topic name
"""
return f"0x{hashlib.sha256(topic.encode('utf-8')).hexd... | 8813d152dbdcb24e6ab0319ddee54d7591de4197 | 619,454 |
def merge_list(wordlists):
"""
this function merges all the wordlist(dictionary) into one, and return it
:param wordlists: an array contain all the wordlist(dictionary type)
:return: the merged word list (dictionary type)
"""
mergelist = {}
for wordlist in wordlists:
for key in word... | 4fefa2db0e885a5a9466207cab427cce497fe5e2 | 619,457 |
def validate_float_value(float_value_input,
greater_than=None, less_than=None):
"""
The purpose of this function is to validate that a float value is valid.
The value, its range (either greater than or less than a number) may
also be tested. This function will bark if the valu... | fb108b2f9e4af37668a68bea1d0da67b4c53400e | 619,458 |
def repattr(obj, name, value):
"""Sets an attribute of a class/object. Returns the old value.
"""
old = getattr(obj, name)
setattr(obj, name, value)
return old | 89e5ae7e36e703e13f56ef3ae492ce66d56c7ae1 | 619,459 |
def median(iterable, sort=True):
""" Returns the value that separates the lower half from the higher half of values in the list.
"""
s = sorted(iterable) if sort is True else list(iterable)
n = len(s)
if n == 0:
raise ValueError("median() arg is an empty sequence")
if n % 2 == 0:
... | cd69048720098864acf0d84e7cd1ac45023afaff | 619,462 |
def possible_moves(state: list) -> list:
"""
Returns list of all possible moves
For the given board position 'state' returns
list of all possible moves for the next turn
Parameters
----------
state : list
The board position to be evaluated
"""
moves = []
for x, row in ... | c7191d6c803883744eee2eccb85969bc3aa79116 | 619,464 |
import secrets
def passphrase(w, n):
"""
Generate passphrase
:param w: word list
:type w: list
:param n: number of words
:type n: int
:return: passphrase
:rtype: str
"""
# Store the random string
rd = ""
# Get n random words
for _ in range(n):
rd += secrets... | 67acb6f2cbb3c444c72318376fbdec83cc254807 | 619,467 |
from functools import reduce
def predict_number_of_row_from_conf(conf):
"""
Precict the number of row of the fake data set generated by `fake_data_generator(conf)`
This is the product of number of values for each label
"""
num_uniques_by_label = [len(c.get('values', [])) for c in conf if c['type']... | 0b64dcb9f00e37245d76b834ecd6c656a977ab5a | 619,474 |
def inductive_split(g):
"""Split the graph into training graph, validation graph, and test graph by training
and validation masks. Suitable for inductive models."""
train_g = g.subgraph(g.ndata['train_mask'])
val_g = g.subgraph(g.ndata['train_mask'] | g.ndata['val_mask'])
test_g = g
return trai... | a4a68bece7def07ddc3d409cdaadb2cf3db03adf | 619,479 |
def swap(array, idx_x, idx_y):
"""
Swap two values within an array. Mutates array!
:param array: array
:type array: list[any]
:param idx_x: index of a value
:type idx_x: int
:param idx_y: index of another value
:type idx_y: int
:return: array with swapped elements
"""
temp =... | cbac5d30f104c7b217c54d8c8199f649bbbb42ac | 619,484 |
import time
def _get_expiration_time(expiry_seconds):
"""Return a timestamp |expiry_seconds| from now."""
return int(time.time() + expiry_seconds) | f76fd3854fdfaf571e4637a319c7bc6507ccd302 | 619,485 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.