content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import re
def MatchNameComponent(key, name_list, case_sensitive=True):
"""Try to match a name against a list.
This function will try to match a name like test1 against a list
like C{['test1.example.com', 'test2.example.com', ...]}. Against
this list, I{'test1'} as well as I{'test1.example'} will match, but
... | ad522feba9cabb3407e3b8e1e8c221f3e9800e16 | 5,342 |
def sign(num):
"""Returns the sign of num as an integer;
if ```num < 0```, returns ```-1```, ```num = 0```, returns ```0```, ```num > 0```, returns ```1```."""
return int(num > 0) - int(num < 0) | 8f8cca093060f5c7ea3f62bc43577077136622b2 | 428,838 |
def kd(Cs, Cl):
"""
kd calculates a partition coefficient for a given set of measurements. For
igneous petrology, this is commonly the concentration of a trace element in
the mineral divided by the concentration of the same trace element in the
melt (e.g. Rollinson 1993 Eq. 4.3)
Inputs... | 9debcdf367007192ce2bc2ec2b40cf5a6ee2b3f1 | 358,849 |
def _is_tachychardic(age: int, heart_rate: int):
"""
Determines if user is tacahychardic based on age and heart rate. Based on: https://en.wikipedia.org/wiki/Tachycardia
Args:
age (int): Age of the user.
heart_rate (int): Heartrate of the user.
Returns:
bool: Whether or not the ... | c8c0a96b72d7dbcebc0ab8ea7394af7b5ca635e3 | 259,006 |
import csv
def load_review_data(path_data):
"""
Returns a list of dict with keys:
* sentiment: +1 or -1 if the review was positive or negative, respectively
* text: the text of the review
"""
basic_fields = {'sentiment', 'text'}
data = []
with open(path_data) as f_data:
for dat... | e19e51a37007ad308893c190a3629beef9e57f90 | 34,011 |
def _compute_mod(score: int) -> int:
"""Compute a mod given an ability score
Args:
score (int): Ability score
Returns:
(int) Modifier for that score
"""
return score // 2 - 5 | c427d5ac3a438bfb210066ebe759fb1dac1a677b | 367,386 |
def _DefaultAlternative(value, default):
"""Returns value or, if evaluating to False, a default value.
Returns the given value, unless it evaluates to False. In the latter case the
default value is returned.
@param value: Value to return if it doesn't evaluate to False
@param default: Default value
@retur... | 63bfffb71545ee845c7f175bb924d6d45c4a6e0e | 409,311 |
import shutil
def check_valid_shell_command(cmd):
"""
Determine if a shell command returns a 0 error code.
Args:
cmd (string or list): Shell command. String of one command or list with arguments.
Returns:
bool
"""
if isinstance(cmd, list):
return shutil.which(cmd[0])... | 97d2ac7a24d15217481454fdd0a2c2b7ef11fa70 | 35,373 |
def dbamp(db):
"""Convert db to amplitude"""
return 10 ** (db / 20.0) | b66d96cbab2137c0b2f0efeb8bb36ea1a8bd75dc | 245,166 |
import tempfile
def fill_directory_with_temp_files(directory, num_files, delete=False):
"""Fill up a directory with temporary files, that by default do not delete
themselves when they go out of scope.
Args:
directory (str): Path to the directory to fill.
num_files (int): Amount of files t... | 135307365194e8d88c764c1b65f8d4c2d6572ddf | 499,728 |
def echo(request, string):
"""Returns whatever you give it."""
return string | 25cdf4d43e8cdcb08c4e79daf8cd92c92263241e | 462,515 |
from typing import Tuple
import random
def randRGB() -> Tuple[int, int, int]:
"""Returns a tuple containing an random RGB value"""
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b) | 9a044974cbb704c3a932e4c4de07aede6ed0cef8 | 432,449 |
def calculate_catalog_coverage(y_test, y_train, y_predicted):
"""
Calculates the percentage of user-item pairs that were predicted by the algorithm.
The full data is passed in as y_test and y_train to determine the total number of potential user-item pairs
Then the predicted data is passed in to determi... | 8ccab81e9590d0ec5702a18d96ce95656ce9eb74 | 547,683 |
def _default_with_off_flag(current, default, off_flag):
"""Helper method for merging command line args and noxfile config.
Returns False if off_flag is set, otherwise, returns the default value if
set, otherwise, returns the current value.
"""
return (default or current) and not off_flag | 880d826d1c487005102fbacb9d4dcc94fb14f4db | 618,507 |
def standardise_efficiency(efficiency):
"""Standardise efficiency types; one of the five categories:
poor, very poor, average, good, very good
Parameters
----------
efficiency : str
Raw efficiency type.
Return
----------
standardised efficiency : str
Standardised effici... | 07a712fc3f941f1b82a834940e05e4e4164bdf61 | 325,033 |
import json
def save_run_settings(run_settings):
"""
Takes a run_settings dictionary and saves it back where it was loaded from,
using the path stored in its own dictionary. Return None.
"""
# don't act on original dictionary
run_settings = run_settings.copy()
# store the raw log loss resu... | 420f10bf961a89aed6426fbefca70097918236d0 | 283,615 |
import re
import string
def clean_text_round1(text):
"""Make text lowercase, remove text in square brackets, remove punctuation and remove words containing numbers."""
text = text.lower()
text = re.sub("\[.*?\]", "", text)
text = re.sub("[%s]" % re.escape(string.punctuation), "", text)
text = re.s... | 4b543a2036f5e48435100caec069f7d5b5541d51 | 164,696 |
from typing import Callable
import inspect
def local_kwargs(kwargs: dict, f: Callable) -> dict:
"""Return the kwargs from dict that are inputs to function f."""
s = inspect.signature(f)
p = s.parameters
if next(reversed(p.values())).kind == inspect.Parameter.VAR_KEYWORD:
return kwargs
if l... | ba1f9753df754fe09a3b64e73f907ce8fed94e64 | 166,513 |
def int_array_to_bit_string(int_array: list) -> int:
"""
Integer array such as [1, 0, 0, 0] to integer (8).
Returns 0 if non-binary values found in the list.
Parameters
----------
int_array : list of int
Integer array.
Returns
-------
value : int
"""
try:
r... | 272f53d9376b10e3009ca48a09c78226d527ae04 | 242,672 |
def copyStream(src, dest, length = None, bufferSize = 16384):
"""Copy from one stream to another, up to a specified length"""
amtread = 0
while amtread != length:
if length is None:
bsize = bufferSize
else:
bsize = min(bufferSize, length - amtread)
buf = src.r... | b7ed47100cb226532f6acafc6598d5f5e1fdbe3f | 124,460 |
def graph_list_to_features(graphs):
"""Get a TFRecord feature dictionary from a list of graphs.
The features from each graph is prepended with a prefix and all
added to the final dictionary at the same level.
Parameters
----------
graphs : [Graph]
Returns
-------
features : dict (... | 97728caa1e5aedbb9e404b39fb6174361dd2b0cd | 667,805 |
def get_function_name(fcn):
"""Returns the fully-qualified function name for the given function.
Args:
fcn: a function
Returns:
the fully-qualified function name string, such as
"eta.core.utils.function_name"
"""
return fcn.__module__ + "." + fcn.__name__ | ae186415225bd5420de7f7b3aef98480d30d59f8 | 708,012 |
import json
def remove_dojo_report(path):
"""
Remove the `DOJO_REPORT` section from the pseudopotential file.
Write new file. Return dict with old_report, None if error.
"""
# Read lines from file and insert jstring between the tags.
with open(path, "rt") as fh:
lines = fh.readlines()
... | f1b7cd76493e90f7334ca6f3d47625c5b3389dfa | 150,146 |
def merge(b, a):
"""
Merges two dicts. Precedence is given to the second dict. The first dict will be overwritten.
"""
for key in a:
if key in b and isinstance(a[key], dict) and isinstance(b[key], dict):
b[key] = merge(b[key], a[key])
elif a[key] is not None:
b[ke... | 18b8c3da7928809ede3b07033fd9a2516d31879f | 477,989 |
def _defaultHandler(packetNum, packet, glob):
"""default packet handler
Args:
packetNum (int): packet number
packet (obj): packet
glob (dict): global dict
Returns:
dict: glob
"""
print(packetNum, packet)
return glob | d4e92ce5d7b2943a6199db220f6fe80807219849 | 304,827 |
import random
def _generate_fwf_row(characterSet, offsets):
"""Generates a random fwf line
Args:
characterSet (str): valid to pick characters from
offsets (list[int]): lengths of each field
Returns:
line(str): line formatted in fwf
"""
return [
"".join(random.choi... | ac4c778335c173c0802ec8a225f7edc6465bd776 | 613,740 |
from typing import Callable
from typing import List
import inspect
def _get_fn_argnames(fn: Callable) -> List[str]:
"""Get argument names of a function.
:param fn: get argument names for this function.
:returns: list of argument names.
"""
arg_spec_args = inspect.getfullargspec(fn).args
if i... | a464f1fb21a454f4e6a854a64810ba48cdb6f9f8 | 24,381 |
def composeVideoMaskName(maskprefix, starttime, suffix):
"""
:param maskprefix:
:param starttime:
:param suffix:
:return: A mask file name using the provided components
"""
if maskprefix.endswith('_mask_' + str(starttime)):
return maskprefix + '.' + suffix
return maskprefix + '_m... | 0fe45da135f79086fa52ca2fdca55a6cc51b9a3d | 664,845 |
def neighbor_idcs(x, y):
"""
Input x,y coordinates and return all the neighbor indices.
"""
xidcs = [x-1, x, x+1, x-1, x+1, x-1, x, x+1]
yidcs = [y-1, y-1, y-1, y, y, y+1, y+1, y+1]
return xidcs, yidcs | 59f479014dddcb1d1de7558f870836bdfed121be | 310,901 |
def loadWords(filename):
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
inFile = open(filename, 'r')
line = inFile.readline()
wor... | 655af114f7a6cafda830c563e351c425d11ecbee | 445,332 |
def proportional(raw_value, factor, unit=None):
"""Applies a proportional factor."""
return (float(raw_value) * factor, unit) | 0cdc5c14348f0d99e1de58d6445df69f8a8a39e8 | 584,731 |
def to_singular(name):
"""Convert the name to singular if it is plural
This just trims a trailing 's', if found.
"""
return name[:-1] if name.endswith("s") else name | 5ae3c75b8bd43cb6c4e6eaa775d4a58712fd0121 | 352,526 |
def sampling(array, interval=1, offset=0):
"""
Down-sample the input signal with certain interval.
input:
array: numpy array. The input temporal signal. 1d or with multiple dimensions
interval: int. The interval to sample EEG signal. Default is 1, which means NO down-sampling is applied
... | 440df08b95619f446ee498022d509740e2d75637 | 689,278 |
import itertools
def champernowne_digit(n):
"""Get Champernowne constant's n-th digit (starting from 0)."""
# Implementation determines 3 pieces of info in that order:
# - the length of the number the digit belongs to : len_num
# - the index of the digit in the number : digit_index
# - the numb... | 021298a940de81729289c0bf0f9acb3ddd8d298a | 226,448 |
import configparser
def submit_kaggle(notebook_name, submission_path, message):
""" Generate submission string that can be used to submit an entry for scoring by
kaggle on test data. Use python magic commands to run
Args:
notebook_name (str): Name of jupyter notebook for kaggle entry
... | 5661e291ac75776d8a5fcbba5154655a0452d5ed | 563,982 |
def extent_to_wkt(extent):
"""Create a Polygon WKT geometry from extent: (xmin, ymin, xmax, ymax)"""
wkt = "POLYGON(("
for dx, dy in ((0, 0), (0, 1), (1, 1), (1, 0)):
wkt += "{0} {1},".format(str(extent[2 * dx]), str(extent[2 * dy + 1]))
wkt += "{0} {1}))".format(str(extent[0]), str(extent[1]))
... | dfb40c85fade27f33861666647be1afa42dc75d8 | 515,391 |
from typing import Sequence
def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool:
"""
Check if the 2 lane sequences are overlapping.
Overlapping is defined as::
s1------s2-----------------e1--------e2
Here lane2 starts somewhere on lane 1 and ends after it,... | 155e3a962f3f457a868585798e1ab8d92c9f115f | 701,826 |
def isacn(obj):
"""isacn(string or int) -> True|False
Validate an ACN (Australian Company Number).
http://www.asic.gov.au/asic/asic.nsf/byheadline/Australian+Company+Number+(ACN)+Check+Digit
Accepts an int, or a string of digits including any leading zeroes.
Digits may be optionally separated with... | cbabe4a84113cdc02f85922b0012e97c22b99e9e | 90,464 |
def create_curl_command(authorization, payload, command, url, curl_options, show_api_key,
content_type='application/json'):
"""
cURL command generator
:param authorization: Authorization part e.g Bearer API key
:param payload: Payload data
:param command: GET, PUT, etc
:p... | 422d11c3837844111a1ef10a537ef4a52d0a988d | 659,785 |
def area(circle):
"""Get area of a circle"""
return circle.get('radius') ** 2 * 3.14159 | 5d64b5fcfe8d82bc994e2e12aeab90c276943fa5 | 624,780 |
def get_intersection_area(box1, box2):
"""
compute intersection area of box1 and box2 (both are 4 dim box coordinates in [x1, y1, x2, y2] format)
"""
xmin1, ymin1, xmax1, ymax1 = box1
xmin2, ymin2, xmax2, ymax2 = box2
x_overlap = max(0, min(xmax1, xmax2) - max(xmin1, xmin2))
y_overlap =... | d3c420597533236a210640f9d4b37a754c6f5a33 | 692,104 |
import time
def get_and_sleep(symbols, fetcher, sleep_time, log_data):
"""
:param symbols: [] of *
List of data to fetch
:param fetcher: func
Perform operations with this function on each data
:param sleep_time: int
After operations, sleep this amount of seconds
:param log_... | ee7f93dc7e58f262053833480602451dd903afb8 | 541,276 |
import six
def binary_encode(text, encoding='utf-8'):
"""Converts a string of into a binary type using given encoding.
Does nothing if text not unicode string.
"""
if isinstance(text, six.binary_type):
return text
elif isinstance(text, six.text_type):
return text.encode(encoding)
... | 185132f36f10a78db4d7a935aa3010eb0c8f29bc | 574,613 |
def is_matrix(iterable):
"""
Check if a iterable is an matrix (iterable of iterables)
>>> is_recursive_iter([[1, 2, 3], [5, 6], [9, 10]])
True
>>> is_recursive_iter([1, 2, 3])
False
"""
if isinstance(iterable, (list, tuple)):
return all(
isinstance(i, (list, tuple))... | 3eb6731ad20f576933a52aed8acb80018d907554 | 302,617 |
def session(tmpdir_path):
"""A temp session file (pathlib.Path)
"""
return tmpdir_path / 'cr-session.sqlite' | ee8d0318e355c402ae5c4df24a20b1c6bcd9553c | 490,783 |
def is_prolog_functor(json_term):
"""
True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format.
"""
return (
isinstance(json_term, dict) and "functor" in json_term and "ar... | b3435672520b2be45e2194a016f73b987d3e1dc6 | 659,609 |
def branch(cuds_object, *args, rel=None):
"""
Like Cuds.add(), but returns the element you add to.
This makes it easier to create large CUDS structures.
:param cuds_object: the object to add to
:type cuds_object: Cuds
:param args: object(s) to add
:type args: Cuds
:param rel: class of t... | 56e18a2e7a8f6cc215cd75b2998142090c86ea79 | 224,080 |
def get_links_to_articles_of_appropriate_type(soup, article_type):
"""Get links to articles with given article type and return them as a list
Args:
soup (BeautifulSoup): BeautifulSoup object of the site
article_type (str): The type of article to look up for
Returns:
list: The list ... | dfa3c80e5f17f38a69d90808271a825d1a3334a1 | 229,113 |
from typing import Optional
from typing import Callable
import functools
import click
def group_create_and_update_params(
f: Optional[Callable] = None, *, create: bool = False
) -> Callable:
"""
Collection of options consumed by group create and update.
Passing create as True makes any values required... | e2afc339de284e93b3afc805674c55adc9777fc4 | 563,598 |
def new_import_error(space, w_msg, w_name, w_path):
"""Create a new instance of ImportError.
The result corresponds to ImportError(msg, name=name, path=path)
"""
return space.appexec(
[w_msg, w_name, w_path], """(msg, name, path):
return ImportError(msg, name=name, path=path)""") | acafe1deebe98cbd97f0582c151c75395ecae147 | 405,368 |
def xPrime(t,x,y):
"""
Returns xPrime at a specified time, for specified value of y
"""
return(y) | 02a4d357ab27e7ca232c66914a7bf16b6676da97 | 353,830 |
async def startlist() -> dict:
"""Create a startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 0,
"start_entries": [],
} | f66299795bfb674b7e97396200d381022c4413a2 | 38,379 |
def _quote(s: str) -> str:
"""Surround keyword in quotes if it contains whitespace"""
return f'"{s}"' if ' ' in s else s | 5e30de39e2a59574b5cb137bb7aa726904ce74ab | 439,636 |
def ABCDFrequencyList_to_HFrequencyList(ABCD_frequency_list):
""" Converts ABCD parameters into h-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,h11,h12,h21,h22],...]
"""
h_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A... | d4f54e6864a34b8b24b1afe599a9338be52f29fd | 31,250 |
def flatten_data(radiance):
"""Extracts radiance arrays for a whole month
from a dictionary into a list of arrays.
Meant for use with a single month of data.
Parameters
----------
radiance : dict
Dictionary containing one whole month of
radiance arrays, with days as keys and
... | a52cfb8ab6b6d520851c83c86425961c923b19ec | 411,379 |
def get_color_index(color,palette):
"""Returns the index of color in palette.
Parameters:
color: List with 3 int values (RGB)
palette: List with colors each represented by 3 int values (RGB)
Returns:
Index of color in palette.
-1 if not found.
"""
for x in rang... | 6131fdaa9fb0db7727a5e8ad6c30bd0b61e12031 | 603,555 |
def valid(snk, body, size, moves):
"""
Determines if a move is out of bound or in body
"""
# print("Snk is: ", snk)
x = snk['x']
y = snk['y']
# print("Body is: ", body)
b = []
for item in body:
b.append([item['x'], item['y']])
for move in moves:
if move == 'left':
x -= 1
elif move == 'right':
... | 29ab50aeb8abdb6e38355ce558153ee798203bff | 129,488 |
import asyncio
def create_task(coro, loop):
# pragma: no cover
"""Compatibility wrapper for the loop.create_task() call introduced in
3.4.2."""
if hasattr(loop, 'create_task'):
return loop.create_task(coro)
return asyncio.Task(coro, loop=loop) | 8f41d15f1d7a9394b5e9ad7bb31aca83f81999d3 | 114,192 |
def wrapper(field, wrap_txt):
"""
Wrap a field in html.
"""
answer = "<%s>" % wrap_txt
answer += field
answer += "</%s>" % wrap_txt
return answer | 7757531c3770c4d0c2994634741e693760fb21bd | 291,803 |
def dEdL(E, L, P, Q, R):
"""
we know: E^2*P + E*Q + P = 0
therefore:
dEdL = E' = -(E^2*P' + E*Q' + R')/(2*E*P + Q)
input
P, Q, R: three polynomials that depend on L
E: the energy
L: the independent (scaling) variable
"""
Pp = P.deriv(1)(L)
Qp = Q.deriv(1)(L)
Rp = R.deri... | ef2543df52e78fb59c4001d07b09578dada52f62 | 527,626 |
def color_plot(x, y, color_s, plot_fcn, **kwargs):
"""
Plot a line with an individual color for each point.
:param x: Data for x-axis
:param y: Data for y-axis
:param color_s: array of colors with the same length as x and y respectively. If now enough colors are given,
use just t... | 1daaf5af6aac26fb6278c9cc3068c154f67eb6a2 | 284,867 |
import json
def _get_codes(error_response_json):
"""Get the list of error codes from an error response json"""
if isinstance(error_response_json, str):
error_response_json = json.loads(error_response_json)
error_response_json = error_response_json.get("error")
if error_response_json is None:
... | 86e73be80735df115f1d24b5a45f091b62db4d42 | 681,965 |
from typing import Optional
from typing import List
def convert_to_base(
number: int, base: int, min_length: Optional[int] = None
) -> List[int]:
"""
Convert number to its representation in a given system.
:param number:
positive integer number to be converted
:param base:
pos... | bc8bb7a6fb966fc89e66b85c44bb7086e3d062d3 | 162,218 |
def get_option(args, config, key, default=None):
"""Gets key option from args if it is provided, otherwise tries to get it from config"""
if hasattr(args, key) and getattr(args, key) is not None:
return getattr(args, key)
return config.get(key, default) | 54d77c6ae3e40b2739156b07747facc4a952c237 | 708,580 |
import yaml
def load_config(yamlfile):
"""load yaml to a dict"""
with open(yamlfile, 'r') as stream:
_dict = yaml.safe_load(stream)
return _dict | 344fd620fad860d7bd24c757aafaa428c1d5a70b | 69,583 |
def remove_character(s, position):
"""Removes the character at the given position ie. 'abc', 1 -> 'ac'"""
s = s[0:position] + s[position+1:len(s)]
return s | 7260137e7cef2e2a324bb386e6e90732cb9be823 | 420,011 |
def from_digits(digits):
"""
Make a number from its digit array (inverse of get_digits)
"""
n = 0
multiplier = 1
for d in reversed(digits):
n += multiplier * d
multiplier *= 10
return n | c4aaf996b6fbce4e5ba0569eefbb41f1f96b92d8 | 526,071 |
def sumCounts(a, b):
""" Add up the values for each word, resulting in a count of occurences """
return a + b | e7830e2376399a54d9d23b57b41bfedf63e897bd | 202,839 |
from typing import List
from typing import Dict
from typing import Set
def get_unique_affected_entity_ids(security_problems: List[Dict]) -> Set[str]:
"""Extract all unique affected entity IDs from a list of security problems.
:param security_problems: the security problems, parsed from JSON to Dicts of Dicts
... | ffcfd9189e83ac7f0aa4c252216f47e2361713d7 | 664,413 |
def make_hit(card, cards, deck):
"""
Adds a card to player's hand
"""
if card in deck:
cards.append(card)
deck.remove(card)
return cards | 2420676fa793d07ee2674d2870428eeb6d580a97 | 691,338 |
def pl2_to_pl(src_dict, scale=1000.):
"""Convert integral flux of PL2 to prefactor of PL"""
index = src_dict['spectral_pars']['Index']['value']
emin = src_dict['spectral_pars']['LowerLimit']['value']
emax = src_dict['spectral_pars']['UpperLimit']['value']
f = src_dict['spectral_pars']['Integral']['v... | 7cc1a57ac8763e08968ea32a93c867311c242785 | 72,551 |
def pct_to_kelvin(pct, max_k=6500, min_k=2700):
"""Convert percent to kelvin."""
kelvin = ((max_k - min_k) * pct / 100) + min_k
return kelvin | 860a9716733249f3a4ee6076db5fad4926befc04 | 624,892 |
def split_X_y(df, column_name='label'):
"""
Split the data into a feature values (X) and targets or labels (y).
:param df: pandas dataframe to split
:param target: Name of the column holding the labels
:return: tuple containing X, y values
"""
if column_name not in df.columns:
return... | 022015ba93d93adf66ad1b1734a38c6864ee3b40 | 344,192 |
def degrees_of_freedom(s1, s2, n1, n2):
"""
Compute the number of degrees of freedom using the Satterhwaite Formula
@param s1 The unbiased sample variance of the first sample
@param s2 The unbiased sample variance of the second sample
@param n1 Thu number of observations in the first sample
@pa... | 5f076e33584c61dca4410b7ed47feb0043ec97cb | 397 |
def atc_station_tracer_query(station_code, samp_height, tracer, level=2):
"""
Return SPARQL query to get a data object for
a specific ICOS Atmospheric station, sampling height and tracer
CO2, CO or MTO, level 2 or level 1 (=NRT)
:input: ATC station code, sampling height, tracer, IC... | d4d3a57c6d6a245b9b636c345f14248551e00fe0 | 440,980 |
def is_root_soul(s):
"""
Returns a boolean indicating whether the key s is a root soul.
Root soul is in the form 'schema://id'
"""
return "://" in s | 24e0853f556e7c1a65bcb44881912cd67167d8b7 | 511,918 |
from typing import Tuple
def __nb_xy2rowcol(
xy: Tuple[float, float], inverse_transform: Tuple[float, ...]
) -> Tuple[float, float]:
"""numba version of xy2rowcol
Parameters
----------
xy : Tuple[float, float]
coordinate
inverse_transform : Tuple[float, ...]
affine parameter a... | acc1e9c98fc27bca383430b6e472d3a866f2a44d | 449,898 |
def add_dividers(row, divider, padding):
"""Add dividers and padding to a row of cells and return a string."""
div = ''.join([padding * ' ', divider, padding * ' '])
return div.join(row) | 7cbe235ddf8c320cadfcc4b4a3f17a28c2aaac1c | 695,365 |
def myComb(n, p):
"""
C(n, p), polyfill for python < 3.7. For higher python version, math.comb should be better.
Parameters
----------
n, p : int
Returns
-------
int
C(n, p)
"""
res = 1
for i in range(p):
res *= (n - i)
for i in range(p):
res = ... | 88295b319cee5ac3911ffc5823dd58a4d44d14e1 | 394,147 |
def to_equation(coefficients):
"""
Takes the coefficients of a polynomial and creates a function of
time from them.
"""
def f(t):
total = 0.0
for i, c in enumerate(coefficients):
total += c * t ** i
return total
return f | 32562826f4ffbf1bc502c715a0430358694a1e6c | 296,106 |
def funcparser_callable_space(*args, **kwarg):
"""
Usage: $space(43)
Insert a length of space.
"""
if not args:
return ''
try:
width = int(args[0])
except TypeError:
width = 1
return " " * width | 1033297ff5ce10b26e19d12a378e719afa6261d3 | 448,296 |
import fcntl
import errno
def obtain_lock(lock_filepath):
""" Open and obtain a flock on the parameter. Returns a file if successful, None if not
"""
lock_file = open(lock_filepath, 'w')
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
return lock_file
except IOError as e... | 1159860a436eb7e94054e031ae852b6491c1f937 | 549,734 |
def safeInt(v):
"""helper function for parsing strings to int"""
try:
ret = int(v)
return ret
except:
return None | bfd75432d459e083188b6f60b759edca0a395121 | 613,813 |
def _worker_one_task(incoming,outgoing):
"""A thread. Takes stuff from the incoming queue and puts stuff on
the outgoing queue. calls execute for each command it takes off the
in queue. Return False when we receive a terminator command"""
#msgb("WORKER WAITING")
item = incoming.get()
#msgb("WORKER GOT... | 840f14dc158a315f12c3a4300744ca7b5fc994fc | 381,059 |
def freeze(d):
"""Convert the value sets of a multi-valued mapping into frozensets.
The use case is to make the value sets hashable once they no longer need to be edited.
"""
return {k: frozenset(v) for k, v in d.items()} | b8e3b287838e5f8e52c71eb2d10e41823896dfe0 | 581,843 |
def read_file(filename):
"""
read the text of a file
:param filename: name of the file to read
:return: text of the file
"""
with open(filename, encoding="utf-8") as file:
return file.read() | 0df9e7f7df0cbf8896b62502efb0023f8c30f2b0 | 428,966 |
def istype(obj, allowed_types):
"""isinstance() without subclasses"""
if isinstance(allowed_types, (tuple, list, set)):
return type(obj) in allowed_types
return type(obj) is allowed_types | 5c441a69030be82e4d11c54ea366ee3463d388c8 | 691,257 |
from typing import Any
import inspect
def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if... | 6705869a4368316d926b10c0221cdce75b0160f2 | 432,656 |
import functools
def needs_semaphore(func):
"""Decorator for a "task" method that holds self.semaphore when running"""
@functools.wraps(func)
async def wrapper(self, *args, **kwargs):
async with self.semaphore:
result = await func(self, *args, **kwargs)
return result
return... | 3c34ae0b4e1d06e8b4c14de61eb81bf1427d4ec6 | 229,890 |
def find_bucket_key(s3_path):
"""
This is a helper function that given an s3 path such that the path is of
the form: bucket/key
It will return the bucket and the key represented by the s3 path
"""
s3_components = s3_path.split("/")
bucket = s3_components[0]
s3_key = ""
if len(s3_comp... | a75fb1b10216c9a36ac7428e3ae945b29c3045b8 | 485,107 |
def from_uniform(r, a, xmin):
"""
Inverse CDF of the power law distribution
"""
x = xmin*(1.-r)**(-1./(a-1.))
return x | a2d58f460a8a35874253377ec8b1b4cee913533a | 269,934 |
def indices(s):
"""Create a list of indices from a slice string, i.e. start:stop:step."""
start, stop, step = (int(x) for x in s.split(':'))
return list(range(start, stop, step)) | 8930bb7f32e65b8f40e2efe56b7aff7ce43731d6 | 353,134 |
def flatten(iter_of_iters):
"""
Flatten an iterator of iterators into a single, long iterator, exhausting
each subiterator in turn.
>>> flatten([[1, 2], [3, 4]])
[1, 2, 3, 4]
"""
retval = []
for val in iter_of_iters:
retval.extend(val)
return retval | 0a2132fc2c9e1dc1aef6268412a44de699e05a99 | 675,974 |
from typing import Tuple
def diagonal_distance(pa : Tuple[int, int], pb : Tuple[int, int]) -> int:
"""
Gets manhattan distance with diagonals between points pa and pb.
I don't know what this is called, but the fastest route is to take the
diagonal and then do any excess.
"""
(ax, ay) = pa
... | 5f4fb653ab8d8bb77172b1637af3edb7c2f0b704 | 659,684 |
def is_iterable(var):
"""This function identifies if a given variable is an iterable.
.. versionadded:: 3.5.0
:param var: The variable to check
:returns: A boolean value indicating whether or not the variable is an iterable
"""
is_iter = any((isinstance(var, list), isinstance(var, tuple), isin... | 49ed1945e3c66dfcaa875f1e607a89066630a831 | 370,739 |
def get_full_asetup(cmd, atlas_setup):
"""
Extract the full asetup command from the payload execution command.
(Easier that generating it again). We need to remove this command for stand-alone containers.
Alternatively: do not include it in the first place (but this seems to trigger the need for further... | ce899a3872e2c5c8a0d13f4c90ff2ff3688c15d9 | 562,349 |
def doAddition(a,b):
"""
The function doAddition accecpts two integer numbers and returns the sum of it.
"""
return a+b | c4afcdab6c5e4570eff848b2f6a0aa07713f0dda | 17,507 |
def get_note_key(timestamp):
"""Generates redis keyname for note"""
return "note_%s" % timestamp | d092a104d6840dd96de2a19ca73902fa12c36465 | 405,126 |
def rle_encode(s: bytes) -> bytes:
"""Zero-value RLE encoder
Parameters:
s (``bytes``):
Bytes to encode
Returns:
``bytes``: The encoded bytes
"""
r = b""
n = 0
for b in s:
if b == 0:
n += 1
else:
if n > 0:
... | 081d1998c56b7978592dbee451185f086499affc | 398,500 |
def Clamp(col):
"""
Makes sure col is between 0 and 255.
"""
col = 255 if col > 255 else col
col = 0 if col < 0 else col
return int(col) | 9e7049834f2026ea1e6f3d379880338834cdc562 | 225,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.