content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def ExtractTagFromLine(line):
"""Extract a tag from a line of HTML, C++, JS or JSON."""
# HTML-style
m = re.search('i18n-content=[\'"]([^\'"]*)[\'"]', line)
if m: return m.group(1)
# C++/Javascript style
m = re.search('/\*i18n-content\*/[\'"]([^\`"]*)[\'"]', line)
if m: return m.group(1)
# M... | feca74f896f3aef5e66ca818ca9299c96b70694e | 602,933 |
def flatten_dict(obj, previous_key=None):
"""Flatten a nested dictionary with keys as obj1.obj2... and so on"""
result = {}
for k, v in obj.items():
if not isinstance(v, dict):
key = f"{previous_key}.{k}" if previous_key is not None else k
result.update({key: v})
else... | fdef647ee44686eaab4f906b77496d2e4055aeac | 602,934 |
def measure_shadow_work(sim, n_steps):
"""Run the sim for n_steps and return the accumulated shadow work."""
w0 = sim.integrator.get_shadow_work(dimensionless=True)
sim.step(n_steps)
w1 = sim.integrator.get_shadow_work(dimensionless=True)
return w1 - w0 | a937a6b91927b4f2352d9bb17e5ef04953ef2ad4 | 602,936 |
def extract_jobs(filename):
"""Extract total number of jobs, job weight, length.
Args:
filename: text file with job data
Returns:
(int, list of tuples) -> (total num of jobs, [(weight, length), ...])
"""
total = 0
jobs = []
with open(filename) as f:
... | beb4a34e6c8237059f25120c078e499bd6363c14 | 602,939 |
def merge_sort(nums: list) -> list:
"""Sort an array using the merge sort algorithm.
Args:
nums (list): The unsorted input array.
Returns:
list: The sorted output array.
"""
def split_array(nums: list) -> list:
"""Recursively split array in half.
Args:
... | 52d1ba5f91c463cd75630d746005812332691c51 | 602,940 |
def tag_list_to_dict(tags_list):
"""Convert Boto3-style key-value tags list into dict"""
tags_dict = {}
for tag in tags_list:
if 'key' in tag:
tags_dict[tag['key']] = tag['value']
elif 'Key' in tag:
tags_dict[tag['Key']] = tag['Value']
return tags_dict | b62a9cff4b73540d6988bab6b7421c8fc2c63f95 | 602,941 |
def _is_complex_type(item_type: str) -> bool:
""" Checks to see if the type is a complex type (as primitives are decoded differently)
Args:
item_type: A string that has the type of the object
Returns:
True if complex, False if primitive
"""
if item_type == 'Boolean' or item_type =... | 8ca3689bd29b2922bed63dff4792dfd37b6a7372 | 602,945 |
def get_candidate_type_and_position(e, idx):
"""Returns type and position info for the candidate at the given index."""
if idx == -1:
return "[NoLongAnswer]"
else:
return e["long_answer_candidates"][idx]["type_and_position"] | 0082b40e47d5820d4f47383a6d288ef2c13f04e8 | 602,948 |
def sqrt(num):
"""
Find the Square Root on integer without using internal sqrt
:param num: integer
:return: floor(sqrt(num))
"""
if num < 2:
return num
result = 0
start, end = 1, num // 2
while start <= end:
mid = (start + end) // 2
sqr = mid ** 2
# ... | dc55c71d8b69893ea47d717aefaaafc810abfbea | 602,950 |
def average_color(colors):
"""
Returns average for the list, or None of the list is empty. Each element is
an inner list of 4 numbers.
"""
count = len(colors)
if count == 0:
return None
totals = [0, 0, 0, 0]
for color in colors:
for i in range(0, 4):
totals[i]... | b1c75abe7e359ecbae89a5d8fded07fbdeb6893d | 602,951 |
def generate_obj_key(instance_or_type, **vary_by):
"""
Generate a cache key for a model instance or type.
:param instance_or_type: Model type or instance
:param vary_by: optional values to vary by.
:return: String key for use in cache.
"""
opts = instance_or_type._meta
vary_string = ',... | 8fc1a2541da277bb13667d184ae544d9f33c0418 | 602,952 |
def bs_cost(bw, bf, nodes=1, depth=1, max_depth=16, total=1):
"""
Estimate the number of leg evaluations performed in a Beam Search,
with a given beam width (`bw`) and branch factor (`bf`), to
reach a score of `max_depth`.
"""
if depth == max_depth:
return total
n = nodes * bf
to... | 21e1d4254893dd6f7f6e1877e1092645d890ded7 | 602,953 |
def lin_shced(start, end, pos):
"""Linear scheduler."""
return start + pos * (end - start) | daddcaacb7c3ee4ce8e01e01ed86e06a8c994bfa | 602,956 |
def get_choice(options : str, lower : int, upper : int):
"""Gets choice from user. Validates input based on passed parameters.
Outputs options menu based on parameter passed
return: choice:str
"""
valid = []
for num in range(lower, upper + 1):
valid.append(str(num))
print(options)
... | 1695e5ae382de7a3665a22e68ce3245fd32acf6f | 602,957 |
def straight(ranks: list) -> bool:
"""
Возвращает True, если отсортированные ранги формируют последовательность 5ти,
где у 5ти карт ранги идут по порядку (стрит)
Returns True if sorted ranks make up an increasing sequence of 5 cards, where ranks differ by 1.
:param ranks: list of ranks, like [10, ... | bba8ced4dff80ae862555108a43d6966bbc7ea7f | 602,962 |
def freq_in_kmskpc(vo,ro):
"""
NAME:
freq_in_kmskpc
PURPOSE:
convert a frequency to km/s/kpc
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
OUTPUT:
conversion from units where vo=1. at ro=1.
HISTORY:
2013-09-01 - Written - Bovy (IAS)... | 64f772917dfd78e1029e07d7987f9999bd171e39 | 602,964 |
def orient2d(pa, pb, pc):
"""Twice signed area of triangle formed by points a, b and c
Direction from pa to pc, via pb, where returned value is as follows:
left : + [ = ccw ]
straight : 0.
right : - [ = cw ]
:param pa: point
:type pa: sequence
:param pb: point
:type pb... | 2f0822730b4f6ad1dc93a2c944a801aa7c65a457 | 602,965 |
import toml
def load_zola_md(filepath):
"""
Loads a zola markdown file and returns its metadata (as dict) and
content as string
"""
meta = {}
text = {}
with open(filepath) as f:
md = f.read()
split = md.split("+++")
if len(split) != 3:
print("invalid zola markdo... | f0062e30f8f5ef5d32bb99292665319e0667904d | 602,967 |
def correlate_objects(objects, attr):
"""Correlate several objects under one dict.
If you have several objects each with a 'name' attribute, this
puts them in a dict keyed by name.
Example::
>>> class Flintstone(DumbObject):
... pass
...
>>> fred = Flintstone(name="... | dbea18b2ff9de1a268987c98049603f41ca52556 | 602,968 |
from typing import OrderedDict
def _color_categorical(series, colors, bg_color):
"""Converts a categorical annotation column to colors."""
if series.dtype.name == 'category':
str_values = series.cat.categories
else:
str_values = set(series.dropna())
if isinstance(colors, dict):
... | 33fbeb2b3c9702ddfd1246e9d149cc5f43a6c904 | 602,969 |
import random
import string
def random_string(N):
"""Return a random ascii_uppercase + digits string of length `N`"""
return ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(N)) | 45f83aef1153b442638f097a86491454e3656c8c | 602,972 |
def get_efermi(calc):
"""Get the fermi energy from a finished calculation"""
efermi = None
if calc:
p_res = calc.get_outputs_dict().get('results')
efermi = p_res and p_res.get_dict().get('efermi')
return efermi | 386feb77f696aa8d6167a141b789c6a26db5622c | 602,977 |
def count_elements(obj, xpath=None):
"""
Returns a count of the XML elements that match a specified XPath expression.
This function encapsulates API differences between the lxml and ElementTree packages.
:param obj: a tree or element object
:param xpath: an XPath node set/selection expression
... | 7d2841af30666100c1c999bffc622b492e461228 | 602,978 |
def vecDotProduct(vec1, vec2):
"""The vector dot product (any dimension).
>>> vecDotProduct((1,2,3),(4,-5,6))
12"""
return sum(x1 * x2 for x1, x2 in zip(vec1, vec2)) | 93215c2344d85595e10681297c742b269e8c7e6e | 602,986 |
def __toCurveString(c):
"""
Returns the string description of the curve.
:param c: The curve
:type c: Curve
:return: str -- The curve's name if not empty, otherwise, the curve's plotname
"""
if c.name:
return c.name
return c.plotname | f54ddc1d5fe96a034c8eb83f7a54b6c1e37de5c0 | 602,987 |
import requests
import csv
def download_cereals(_):
"""Example of a Dagster solid that returns a list of objects."""
response = requests.get("https://docs.dagster.io/assets/cereal.csv")
lines = response.text.split("\n")
return list(csv.DictReader(lines)) | 87a779822c0f3c2235eeb88571b85454ced12807 | 602,990 |
def get_adjacency_data(cur):
"""
Return list of adjacency data,
[cell1,cell2,amount_of_contact,image_number]
Parameters:
-----------
cur : MySQLdb cursor
"""
sql = ("select pre,post,weight,imgNum "
"from adjacency2")
cur.execute(sql)
return [(a[0],a[1],int(a[2]),a[3]... | 8defab4efa6f893055f2df4c00293e58fae2ba20 | 602,991 |
def apris_human_alias(x):
"""
A predefined function for convenience
It extracts transcript IDs from the full names of appris genomes.
"""
return x.split("|")[4] | ce0f50405bde9db32b3887e672f1b7d487e5d0a0 | 602,993 |
def adjacent(a, b):
"""
Return whether a is 8-way adjacent to b. a and b need to have
.x and .y members. Sitting on the same spot counts as adjacent.
"""
return abs(a.x - b.x) < 2 and abs(a.y - b.y) < 2 | c62d9a8a6e30cf13f5c72d4730f5e817503c101b | 602,996 |
from typing import Type
from typing import Any
from typing import Set
def all_subclasses(class_: Type[Any]) -> Set[Type[Any]]:
"""Return a set of all subclasses for a given class object
Recursively collects all subclasses of `class_` down the object
hierarchy into one set.
Parameters
----------
... | c0984db1e6321295f52bf99fc9d085ba39971d0f | 602,999 |
def ceil(a, b):
"""
Returns a/b rounded up to nearest integer.
"""
return -(-a//b) | be6c0c923d73cc4d316963075f54f20f927274c7 | 603,008 |
def format_time(time):
"""Formats a datetime as an ISO 8601 compliant string."""
return time.strftime('%Y-%m-%dT%H:%M:%SZ') | 35289450a8ede1681cf5374f369c25e6f21fcf21 | 603,009 |
def crop(image, bboxes, crop_size):
""" center crop image and bboxes
cropped shape is min(im_shape, crop_shape)
Args:
image (np.array): [h, w, c]
crop_size (list of length 4): cropped size [starty, startx, h, w] must be small than image size
bboxes: [n_bbox, 4] x... | 187e4faa1b53718658bff1e3a9c7030d1c92b03e | 603,011 |
import json
def load_json_file(path):
"""
Returns a dictionary representing the content of a json file
"""
with open(path) as json_file:
return json.load(json_file) | ae1a562364156b32dbe9433c462b74dd45f3704b | 603,012 |
import torch
def cumavg(a: torch.FloatTensor):
"""
Parameters
----------
a : torch.tensor
Shape: l,b,e
Returns
-------
Cumulative average : torch.tensor
Shape : l,b,e
avg over l dimension
"""
# l,b,e
cumsum = torch.cumsum(a, 0)
batch_size = cumsum.... | 5f4b3cc45a25911c8c586b34dd21baa27c9f4105 | 603,014 |
def integer_to_letter(i):
"""
Return the capital letter associated with the input integer (1=A, 2=B, etc.)
:param: i The integer to change to letter
:return: str The capital letter as a string
"""
return chr(i + 64) | 7b0624086491e7a53f90d5aac540de930ca0d550 | 603,017 |
def generate_statistic_string(patterns_of_interest):
"""
Create a string representing the statistic for determining introgression like "(ABBA - BABA)/(ABBA + BABA)"
Input:
patterns_of_interest --- a tuple containing the sets of patterns used for determining a statistic
Output:
L_statistic --- a ... | 62e5b08aad2f4490a9b13015a0190c8f6d60f8cc | 603,018 |
def cradmin_appurl(context, viewname, *args, **kwargs):
"""
Template tag implementation of :meth:`cradmin_legacy.crapp.App.reverse_appurl`.
Examples:
Reverse the view named ``"edit"`` within the current app:
.. code-block:: htmldjango
{% load cradmin_legacy_tags %}
... | cfda3426b495bb741da02f9259a5c472d15a23af | 603,020 |
def get_alpha(R, xi1):
""" Find radius scale factor alpha
Positional Arguments:
R -> Stellar Radius in cm
xi1 -> xi value of surface
Returns:
Alpha scale factor such that R = alpha * xi
"""
return R/xi1 | 742874073ba6992647c54d90a14f0e83cfde4d6a | 603,022 |
from typing import List
def strict_binary_search(lst: List[int], val: int) -> int:
"""
Strict binary search, val should be exist in lst
Return the index of val in lst
"""
left, right = 0, len(lst) - 1
while left < right:
mid = (left + right) // 2
if lst[mid] < val:
... | 343ce7012e585a5c6c7df967ebecdd55de2e41ea | 603,023 |
def generate_model_masks(
depth,
mask = None,
masked_layer_indices = None):
"""Creates empty masks for this model, or initializes with existing mask.
Args:
depth: Number of layers in the model.
mask: Existing model mask for layers in this model, if not given, all
module masks are initiali... | b7a56adacf77c1e7249ae53446032e9f877db65a | 603,024 |
import random
def get_random_int() -> int:
"""
获取 2**32 -1= 4294967295 范围内的随机整数
:return:
"""
return random.randint(0, 2 ** 32 - 1) | 44487cecfc8d489a6e2190cca74b4cc24c5524f5 | 603,027 |
def __partition3way__(arr, lo, hi):
"""
Function to achieve 3-way partitioning for quicksort
1. Start with 3 pointers (lt, i, gt), choose first element (lo) as pivot
2. Invariant: everything to the
(a) left of lt is less than pivot
(b) between lt and i is equal to pivot
(c) right... | 7d51e71ab9b98803d7ac75cf91b5c8f08eafc15a | 603,031 |
def sanitize_function_name(name: str) -> str:
"""Sanitizes the function name to use.
Note that this is a slightly leaky abstraction, but this is really just a single case in which we want to strip out
dunderscores. This will likely change over time, but for now we need a way for a decorator to know about th... | 3a5cee3a65ed5264cded8fa5f5c391822d65dfb3 | 603,034 |
def find_largest_digit_helper(n, max_digit_now):
"""
:param n: int, the number which user wants to find max digit now
:param max_digit_now: int, the max digit now
:return: int, the max digit of n
Reduce one digit in each recursive case to approach base case(n<10)
"""
if n < 0:
# Negative number, should plus -1... | b579589a1084ad7200fb25e76f7c9277c8a70de5 | 603,035 |
def _parselistofdicts(domobj, containerstr, prefix, listofkeys):
"""Parses what's basically a list of dictionaries contained in a container
elements of the form
<container><prefix:key1>VAL1</prefix:key1><prefix:key2>...
</prefix:key2>...</container>
and returns it as a list of dictionaries"""
ou... | b4e4d62041d81c47890f856d2b58b6124dbb3819 | 603,036 |
def compute_lambda_tilde(m1, m2 ,l1 , l2):
""" Compute Lambda Tilde from masses and tides components
--------
m1 = primary mass component [solar masses]
m2 = secondary mass component [solar masses]
l1 = primary tidal component [dimensionless]
l2 = secondary tidal component [d... | 620ae66de9e06cdbf08561fd1bf2514b4cc6ba63 | 603,038 |
def bubble_sort(array):
""" Read more about bubble sort here https://www.geeksforgeeks.org/bubble-sort/
>>> bubble_sort([3,2,1])
[1, 2, 3]
"""
length = len(array) # length of array
for i in range(length - 1):
for j in range(length - i - 1):
if array[j] > array[j + 1]:
... | c599413eee94fe2fd27c1699afa91da957d051b4 | 603,041 |
def _find_requirements(file: str) -> list:
"""Import requirements from an external file in compatible format with setuptools."""
with open(file, 'rt') as requirements_file:
requirements = [requirement.strip() for requirement in requirements_file.readlines()]
return requirements | 3350db40fab87843c05fbc59db4629b36a27739b | 603,042 |
def is_misc(_item):
"""item is report, thesis or document
:param _item: Zotero library item
:type _item: dict
:returns: Bool
"""
return _item["data"]["itemType"] in ["thesis", "report", "document"] | 2b0232a658717769ae34e06d006831efb20a791d | 603,048 |
def _get_line_col(code: str, idx: int):
""" Get line and column (1-based) from character index """
line = len(code[:idx + 1].splitlines())
col = (idx - (code[:idx + 1].rfind('\n') + 1))
return line, col | 6e7d8efd7d98cf1c03fa83c075d078f4f5c49037 | 603,049 |
import re
def tokenize_13a(line):
"""
Tokenizes an input line using a relatively minimal tokenization that is however equivalent to mteval-v13a, used by WMT.
:param line: a segment to tokenize
:return: the tokenized line
"""
norm = line
# language-independent part:
norm = norm.repla... | 3acc231dc574a48d106d10ae908115e1dbe695d5 | 603,056 |
import optparse
def WPFilterGroup(parser):
"""Define the group for options which apply filters to relogging of whole program pinballs."""
group = optparse.OptionGroup(
parser, "Whole program pinball filtering phases and options (relogging)",
"These options define phases which are used to 'fil... | 15d3cb8e4e2dab2739da33271cb0b86fc9092374 | 603,058 |
def remove_gaps(sequences):
"""
Function that removes any gaps ('-') from the protein sequences in the input.
The descriptors cannot be calculated if a '-' value is passsed into their
respective funtions so gaps need to be removed. Removing the gaps has the same
effect as setting the value at the in... | 7a524ed9c699f52b540039c06c8ffd9fba5965cb | 603,060 |
def parse_address(server_name):
"""
Parses the server ip and port
:param server_name: server name in format 10.0.0.1:3000
:type server_name: str
:return: dict with source IP and port
:rtype: dict
"""
addr = server_name.split(':')
return {
"sourceIp": addr[0],
"port":... | cdb59a2fbe2afe0d0329ee5c7b7d2e00488fe63c | 603,062 |
def init_mask_io_format(**kwargs):
"""
initiates and returns a dictionary
mask instance of ROI-IO format.
The following keys in the dictionary represent:
COM : A list of Center Of Mass of each 2-d image slice.
frame_idx : A list of frame(time) indices.
slice_idx : A list of slicie(z) indice... | 66a3ef6fd23a71cf282f40d5a62e33787e117c58 | 603,066 |
def get_maxobs(timfile):
"""Utility function to return number of lines in tim file.
:param timfile:
Full path to tim-file. For tim-files that use INCLUDEs this
should be the base tim file.
:returns: Number of lines in tim-file
"""
maxobs = 0
with open(timfile) as tfile:
... | e462c856b75579917ec1d6a6e77e2fef645ee2b7 | 603,067 |
def get_heat_flow_room_side_by_vent_layer_heat_resistance(r_i: float, theta_2: float, theta_r: float) -> float:
"""
室内側から通気層表面までの熱抵抗から室内側表面熱流[W/m2]を計算する
:param r_i: 室内側から通気層表面までの抵抗[(m2・K)/W]
:param theta_2: 通気層に面する面2(室内側)の表面温度[degC]
:param theta_r: 室内温度[degC]
:return: ... | fc93ac6e4c08a532c66d3fb5302b17b3a5515187 | 603,071 |
def _StateMeetsRule(state, rule):
"""A function that reproduces Caffe's StateMeetsRule functionality."""
if rule.HasField('phase') and rule.phase != state.phase:
return False
if rule.HasField('min_level') and state.level < rule.min_level:
return False
if rule.HasField('max_level') and st... | 02945565619eeb95b6a8c4c6a0682821d3a8982b | 603,074 |
def remove_dc_offset(image):
""" Removes 'DC offset' from image to simplify Gaussian fitting. """
return (image - image.min()).astype("float32") | 0ab464d83165f81c3245085bf5040b988e62ad46 | 603,075 |
def shift_mesh(mesh, vector):
"""
Shift a given mesh with a given vector.
Parameters
----------
mesh : single dict
dictionary containing
at least the following keyword
nodes : ndarray
Array with all node postions.
vector : ndarray
array contai... | 3ef89ee99328b3e14bb71a1bc60e13222f40c60c | 603,077 |
def int_to_bin(i, w, lend=False):
"""
Converts integer to binary tuple.
Parameters
----------
i : int
Integer to convert.
w : int
Width of conversion
lend : bool
Endianness of returned tuple, helpful for iterating.
Returns
-------
tuple of bo... | 9be77a85ec202dd86af692975f70ea0a7d1ef084 | 603,083 |
def extract_place(file_content):
"""
This function extracts five lines out of file_content,
which is a variable holding all of the file content from the calling function. Each extracted line represents,
in order, the place's name, location, latitude, longitude, and user color. The function returns the f... | fba93ad6679e1584153b228a333330e72ea94e13 | 603,085 |
def is_url(path):
"""
Whether path is URL.
Args:
path (string): URL string or not.
"""
return path.startswith('http://') or path.startswith('https://') | fed5b9352352baa5194fd23c6191a9469a3cb2e1 | 603,087 |
def convert_to_base(num, base):
"""
Converts integer num into base b format
ie number to configuration
Args:
num - intger to be converted
base - base to be converted into
Returns:
base b representation of num
"""
convStr = "0123"
if num < base:
return str(... | a4026955d1f644e49ccfd43b6ab0e3c8e81d8d14 | 603,092 |
def get_submission_target(df):
"""Identify target rows with missing click outs."""
mask = df["reference"].isnull() & (df["action_type"] == "clickout item")
df_out = df[mask]
return df_out | ce2c0171868d61e221bcaf0904da1f9ff44ec24e | 603,095 |
def extract_gene_name(record):
""" Extract gene name from FastA entry description
"""
return record.description.split('|')[3].split()[1] | 482cf3b393aedea6cf420015b0bf48a61ba41b20 | 603,096 |
def listify(data):
"""Ensure input data is a list."""
if not isinstance(data, list):
data = [data]
return data | 19905a4e95e55f0def0ddbb5afc93aeef17f4800 | 603,097 |
import csv
def read_estimates(infile):
"""
Reads a CSV File into memory
:param infile : an open file for reading
:returns : A list of lists containing the contents of the csv file
"""
rows = []
rdr = csv.reader(infile, delimiter=',', quotechar='"',
quoting=csv.QUOTE_NONNUMERIC)
for row in rdr:
rows.a... | 95e3ebd3ce04dfa13cc9669fe53065dab90e9c38 | 603,098 |
def _get_runtime1(movie):
"""Helper function to extract the minutes (int) from the runtime movie attribute"""
return int(movie.attrib["runtime"].rstrip(" min")) | 05296adc6511a158bbdf7e714d63ab0dca1b8d64 | 603,099 |
def update_config_from_override(default_config_dict, override_config_dict):
"""
Update a given dictionary values with settings on other dictionary.
Used to override the configuration
"""
for k in iter(default_config_dict):
if k in override_config_dict:
default_config_dict[k] = ov... | 2cc78f8161987af75241dec94fd51df60423b3cb | 603,100 |
def remove_blanks(letters: list):
"""Given a list of letters, remove any empty strings.
>>> remove_blanks(['a', '', 'b', '', 'c'])
['a', 'b', 'c']
"""
cleaned = []
for letter in letters:
if letter != "":
cleaned.append(letter)
return cleaned | 8ede4b682a95ef7f96f2d7c2507017083c5f278d | 603,103 |
def _pysymbol_key(name):
"""Return a sortable key index for name.
Sorting is case-insensitive, with the first underscore counting as
worse than any character, but subsequent underscores do not. This
means that dunder symbols (like __init__) are sorted after symbols
that start with an alphabetic cha... | 0eca4738a3702f79337852f13cc62b45d5348cf5 | 603,106 |
def read_lems_output_files_configuration(xml_root):
""" Read the configuration of the output files of a LEMS document
Args:
xml_root (:obj:`lxml.etree._Element`): LEMS document
Returns:
:obj:`list` of :obj:`dict`: configuration of the output files of a LEMS document
"""
output_file... | 8786380e3e64e4c0683c205f77ce898be34b5dec | 603,107 |
def sum_by_week(df, station):
"""Helper function to aggregate data by week per station."""
df_station = df[df['counting_station'] == station]
aggregated = df_station.set_index('datetime').resample('1W').agg({
'velo_in':
'sum',
'velo_out':
'sum'
}).reset_index()
aggreg... | 64cb50014535708de82c72f73ca75826ca1e7ac3 | 603,110 |
def read_input_files(input_file: str) -> list[int]:
"""
Extracts a list of numbers from the input file.
"""
with open(input_file) as input_fobj:
numbers = [int(line) for line in input_fobj]
return numbers | 86f569ee85f2a5cf48de73cc1db36f2ed915864a | 603,112 |
def closest_power_of_two(value: int) -> int:
"""
The smallest power of two greater than or equal to [value]."""
result = 1
while result < value:
result *= 2
return result | 293dcd7013f05a115c035ecd1c9cf3a3d086a6a3 | 603,119 |
import re
def parse_memory(memory: str) -> int:
"""Parse string expression i.e. 16M, 16MB, etc
M = 1024 * 1024, MB = 1000 * 1000
returns value in bytes"""
# Mega, Giga, Tera, etc
prefixes = "MGTPEZY"
value_error = ValueError(f"Unable parse value: {memory}")
if not memory:
raise ... | 70b771ac5f6b42f1b7ec0096b80a8f306b1c22e2 | 603,122 |
def weighted_predictions(res_tuple, x):
"""
Given res_tuple from expgrad, compute the weighted predictions
over the dataset x
"""
hs = res_tuple.classifiers
weights = res_tuple.weights # weights over classifiers
preds = hs.apply(lambda h: h.predict(x)) # predictions
# return weighted p... | 2a5dfcac5fd77b95e65623dae587a5a6c69f7cbc | 603,125 |
import json
def json_raw_to_dictionary(json_raw):
"""Helper method to that converts JSON to a dictionary"""
return json.loads(json_raw) | ff7842fa0492255b38d8db088ffc5cb8dfdfee8e | 603,128 |
from typing import Union
from typing import Callable
def is_divisible_by(divisor: Union[int, float]) -> Callable[[Union[int, float]], bool]:
"""Takes a ``divisor`` And returns a function (closure) That expects a dividend.
returns true if it passes the divisibility test.
for e.g.
>>> f = is_divisible_... | 5b2f0095f14862457b73c6e32ea96b5a1cafc8cc | 603,134 |
def _snake_to_camel(word):
"""Converts snake_case into camelCase"""
words = word.split('_')
return ''.join([words[0]] + [x.capitalize() for x in words[1:]]) | 067c9d1983851ce0045da9ff601df067c5fac2b9 | 603,135 |
import csv
def get_file_paths(csv_file, target_column):
"""Get file paths from CSV file as values in specific column
:param csv_file: path to target csv file
:param target_column: name of the column that contains file paths
:return: list of file paths
"""
with open(csv_file) as csv_file:
... | 98a64936609de6acfe074769a7f9df3a840635cb | 603,137 |
def compute_classifier_loss(X, y, encoder, classifier, sparse_ce):
""" compute the cross entropy loss for classification
"""
d = classifier(encoder(X))
return sparse_ce(y, d) | 4948a6284a05f615e7a288d6f3518e94d5480923 | 603,141 |
def calc_pad(pad, in_siz, out_siz, stride, ksize):
"""Calculate padding width.
Args:
pad: padding method, "SAME", "VALID", or manually speicified.
ksize: kernel size [I, J].
Returns:
pad_: Actual padding width.
"""
if pad == 'SAME':
return (out_siz - 1) * stride + ksi... | a93c5c3e07bb39ac725025daefd59b513826791b | 603,146 |
def make_command_line_arguments(bam_file_name,
bed_file_name,
config_file_name,
transcript_file_name,
gui_output_file_name):
"""
Utility function to construct a list of command-line ar... | 5190498ab669800e509b464917f07599fd0296b3 | 603,147 |
def get_delay_shift_frac(delay,fs,data_type=0):
"""
Compute integer and fractional shift.
Parameters
----------
delay : float
value for the delay [s].
fs : float
sampling frequency [Hz].
data_type : int
0 for real, 1 for complex.
Returns
-----... | a0b9cc6ab4f9761014ac7fd7f7f3e7fc7a7a2dcd | 603,150 |
def zero(m, n):
""" Create zero matrix"""
new_matrix = [[0 for row in range(n)] for col in range(m)]
return new_matrix | 433a9737b411c7a168ab106de311eb50bb84e76a | 603,151 |
def any_and_not_false(iterable: list) -> bool:
"""
Accept iter.
A reimplementation of any,
with the differnce that the first False short-circuits.
The purpose of this is to short circuit
the moment we get an auth or a denial from a radius server,
while letting non-responses fail over to the... | 5318a870df9ed8ba6a016b0305f72b5c8948f7be | 603,152 |
import torch
def _calculate_accuracy(output: torch.Tensor, actual_labels: torch.Tensor) -> float:
"""Calculates accuracy of multiclass prediction.
Args:
output (torch.Tensor): Output predictions from neural network.
actual_labels (torch.Tensor): Actual labels.
"""
predicted_labels = t... | 509576fedbfddd9cd1934779b2ee1d3cf04eeddf | 603,153 |
def get_cloudformation_template(cfn_client, stack_name):
"""
Returns the template body of a CloudFormation stack.
"""
response = cfn_client.get_template(StackName=stack_name)
return response["TemplateBody"] | 37d87f3c4d85e138cb58cd70ef84ce2f3abd2ee0 | 603,155 |
from typing import List
import struct
def serialize_record_pack(records: List[bytes]) -> bytes:
"""
num_records len_rec1 raw_rec1 len_rec2 raw_rec2 ... len_recN raw_recN
"""
raw_num_records = struct.pack(f'<i', len(records))
raw_records = [b''.join([struct.pack(f'<Q', len(rec)), rec]) for rec in r... | 30762956835088b989816d8a900e542d4228d59c | 603,157 |
def exponent_nice_str(exponent_str):
"""Convert exponent string like ``1e-04`` to ``$10^{-4}$``"""
split_str = exponent_str.split("e")
if split_str[0] == "1":
split_str[0] = ""
split_str[1] = "{" + f"{int(split_str[1])}" + "}"
nice_exponent_str = rf"{split_str[0]} 10^{split_str[1]}"
retu... | 5cc6b0950068e3ab71321fa098befddfc1f57df1 | 603,160 |
def create_test_set_from_folds(folds: list, i: int):
"""
Gets a list of k folds in the form [(test_0, val_0), (test_1, val_1),..., (test_k, val_k)] and a number of fold i
and separates this fold as test set ensuring no data leakage.
Returns:
The new list of train_val sets without the test set a... | db7b93802550ab8439a6e4d381ebc8eee6e2d6b8 | 603,161 |
def simplifyRoles(roles):
"""Sorts and removes duplicates from a role list."""
return sorted(set(roles)) | 7f58fec315518e9c40f78b8e18a74a63f831e692 | 603,162 |
def invdist(d):
"""
Inverse distance kernel.
Parameters
----------
d : ndarray, shape (N,) or (M,N)
One- or two-dimensional array of distances
Returns
-------
ndarray, shape (N,) or (M,N)
Inverse distance, i.e. d^{-1}
Raises
------
ZeroDivisionError : `d` i... | 3c48426cf06b0d4bd1934ed82514a86e4f137ec8 | 603,164 |
def dict_keys_to_str(dictionary: dict):
"""
Returns a single string of all the keys of the dictionary passed
:param dictionary: dict
:return str
"""
key_list = [key for key in dictionary.keys()]
return " | ".join(key_list) | 9ddcb4a2b832475f04dee119d0ef87ff7aa92b9a | 603,166 |
def rivers_with_station(stations):
"""This function, given a list of station objects, returns a container
(list/tuple/set) with the names of the rivers with a monitoring station. """
x = set()
for n in stations:
x.add(n.river)
x_sorted = sorted(x)
return x_sorted | 044fb4dce5310d6a2a62b1a77a64fc453ffbed5f | 603,170 |
def normalize(X, mu=0, std=1):
"""Normalizes the input array with mean mu and standard deviation std
:param X: Input array to be normalized
:type X: numpy.ndarray
:param mu: The mean, defaults to 0
:type mu: int, optional
:param std: The standard deviation, defaults to 1
:type std: int, opt... | 29f50d1a8d2218329f39aedd596be991d1c81a06 | 603,172 |
import re
def camel_to_underscore(name):
"""Convert camel case name to underscore name."""
name = re.sub(r"(?<!\b)(?<!_)([A-Z][a-z])", r"_\1", name)
name = re.sub(r"(?<!\b)(?<!_)([a-z])([A-Z])", r"\1_\2", name)
name = name.lower()
return name | 5e3bf813e9f3ddddc4d9ccb25a0ebc1d83d1fb6d | 603,174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.