content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _find_frame(frame):
"""Find the frame with the caller on the stack."""
def _dirname_is_trax_layers_or_gin(frame):
"""Skip frames coming from trax/layers or .../gin."""
try:
dirname1 = frame.f_code.co_filename.split('/')[-3]
dirname2 = frame.f_code.co_filename.split('/')[-2]
return (dir... | e1509bdc5900789180036340252bfa680641c68e | 682,148 |
def _run_arrays(inner_fn, slice, arrays_dict, **kwargs):
"""
Assumes that the lengths of the value arrays are all the same.
"""
# SETUP the re-usable kwargs with parameters and arrays and then poke values one row at a time
res = []
for row_i in range(slice[0], slice[1]):
for field_i, (ke... | 36ee290fce9610fa4b7a297817297fbeb9ec917d | 682,149 |
import shutil
from pathlib import Path
import os
def executable_missing(monkeypatch):
"""Mocks an executable path that does not point to a file."""
def mock_which(*args, **kwargs):
"""Mock a call to `shutil.which()`, which produces an absolute file path."""
return args[0]
def mock_isfile... | f7c1afd8033b83bac5a82337f00e65b4a865d2b7 | 682,150 |
def create_reventail_axioms(relations_to_pairs, relation='hyponym'):
"""
For every linguistic relationship, check if 'relation' is present.
If it is present, then create an entry named:
Axiom ax_relation_token1_token2 : forall x, _token2 x -> _token1 x.
Note how the predicates are reversed.
"""
... | 2317274c9cae34adf2fd3cd13126f2e72d46c1fb | 682,151 |
def pad_ar_params(ar_params, n_lags, n_forecasts=1):
""" "
pads ar_parameter lists to the length of n_lags
ar_params: list of length n_forecasts with elements: lists of ar coeffs
n_lags: length to which pad each of the ar coeffs
"""
assert n_forecasts == len(ar_params)
if n_forecasts... | 8cfd6d9d5684dfd90ba4b319480c9e63c9085dcf | 682,152 |
from typing import List
def process_reactome_multiple_genes(genes: str) -> List:
"""Process a wrong ID with multiple identifiers."""
gene_list = []
for counter, gene in enumerate(genes):
gene = gene.strip()
# Strip the ' gene' prefix
if gene.startswith(' genes'):
gene =... | bf0f19809138616520d2ee55f7ced61a51d43c7f | 682,153 |
def _get_snap_name(snapshot):
"""Return the name of the snapshot that Purity will use."""
return "{0}-cinder.{1}".format(snapshot["volume_name"],
snapshot["name"]) | d78deb9ee0b8264868ac120f34b9c862784ab5e7 | 682,154 |
def is_even(n):
""" True if the integer `n` is even. """
return n % 2 == 0 | 3e23d6b821c1d396e9ca74d3bb9360531687e940 | 682,155 |
from pathlib import Path
def empty_html():
"""
Returns HTML retrieved with the following command:
curl https://www.roughtrade.com/events/store/rough-trade-east/2019/10 \
> rough_trade_calendar/tests/test_data/events_empty.html
"""
this_filename = globals()["__file__"]
path = P... | 879ebb51149eb01f27c44578df16b745b3904bfa | 682,156 |
def position_query(ra,dec, size=None, mcen=False):
"""
Parameters
----------
ra,dec: [float/str]
ICRS right ascension and declination in decimal degrees.
It identifies the point which returned images must contain, or the center of the search region.
size: [float/str/None] -option... | 69ba369c7bd2472d161ba5ac48140f19cf0a2157 | 682,157 |
def original_choice(door):
"""
Return True if this door was picked originally by the contestant """
return door.guessed_originally is True | 5d2c11e32ef4181b653642fb18a995427a3bae9b | 682,158 |
def get_neighbors(x, y):
"""Returns the eight neighbors of a point upon a grid."""
return [
[x - 1, y - 1], [x, y - 1], [x + 1, y - 1],
[x - 1, y ], [x + 1, y ],
[x - 1, y + 1], [x, y + 1], [x + 1, y + 1],
] | 21ec6d4f4143f717388ff20def80fd53127bc1ed | 682,159 |
def user_to_dict(user):
"""
Convert an instance of the User model to a dict.
:param user: An instance of the User model.
:return: A dict representing the user.
"""
return {
'id': user.id,
'demoId': user.demoId,
'email': user.email,
'username': user.username... | d3e41fc8f377faf35c3a64ce8716fac6e35a611e | 682,161 |
def alphanumerize(text, allowed_chars=["-"], replacement_char="-",
verbose=False):
"""Replace special characters, spaces etc in a text.
Replace characters which are not alphanumeric or in the allowed characters
list with the provided replacement character.
"""
clist = []
for c... | defe7a380709bb5a349917b672768283b66d628b | 682,162 |
def _suffix(name, suffix=None):
"""Append suffix (default _)."""
suffix = suffix if suffix else '_'
return "{}{}".format(name, suffix) | b7b90f14c2f656b31561b9cabd73649464d507cc | 682,163 |
def median(li):
"""Median of elements - shaonutil.stats.median(list of numbers)"""
n = len(li)
li.sort()
if n % 2 == 0:
median1 = li[n//2]
median2 = li[n//2 - 1]
median = (median1 + median2)/2
else:
median = li[n//2]
return median | 5c74cb14544d3c1c6c546a6c01f4bd91ccd4cb1b | 682,164 |
def get_no_departures_mock():
"""Mock no departures in results."""
data = {
"station": "Frankfurt (Main) Hauptbahnhof",
"stationId": "3000010",
"filter": "11111111111",
"journeys": [],
}
return data | 7d5e4f02f5cd1bcf534e338c1faf6dd885e1252f | 682,165 |
import os
import glob
def backward_extractor(i,j,phase, state, annealing_steps, parent_dir):
"""
pull the indices of all existing position files
"""
positions_template = os.path.join(parent_dir, f"lig{i}to{j}.{phase}.{state}.ani_endstate.*.{annealing_steps}_steps.positions.npz")
positions_filename... | c70a20fe5dcc444893316ac22355127cfc15d658 | 682,166 |
def test_orchestrator_backup_config(
self,
protocol: int,
hostname: str,
port: int,
directory: str,
username: str,
password: str,
) -> dict:
"""Test specified settings for an Orchestrator backup
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
... | 954e6c842af8f1a9f3effe81aad7683b1c35e36e | 682,167 |
import os
def validate_name(ctx, param, value):
"""Validate a project name."""
if not value:
value = os.path.basename(ctx.params["path"].rstrip(os.path.sep))
return value | 5da4205d0a9e1b3c945e835b0f7d877481a41916 | 682,168 |
import re
def get_entity(block, extracted_text):
"""Collect entity from the line1 of data block
Args:
block (list): block including lines of data for extraction
extracted_text (str): text which is already extracted from first line
Returns:
(str): entity
"""
try:
... | 58c04fae2edd2453fe3f2548fbf8509eb9dbeb03 | 682,169 |
def get_value_safe(d=None, key=None):
""" Return value of a given dictionary for a key.
@return: value for a key, None otherwise
"""
if d is None or key is None:
return None
if key not in d:
return None
return d[key] | 02201527fc100ef63f4731663f567fd1b5613867 | 682,170 |
import os
import sys
def quote_filename(filename):
""" quote a filename (could contain blanks or other special chars) in a
way suitable for the platform we run on.
"""
# XXX Use os.name AND/OR sys.platform?
if os.name == 'posix':
filename = "'%s'" % filename
elif sys.platform == 'w... | a229919d6002c757cb49d7d85e4d4bfb157943ab | 682,171 |
def number_keys(a_dictionary):
"""
counts the number of keys in a dictionary and returns it
"""
return(len(a_dictionary)) | 4ab56cdfc12a4330652a4111154456775171874b | 682,172 |
def get_electricity_production(power_utilities):
"""Return the total electricity production of all PowerUtility objects in MW."""
return sum([i.production for i in power_utilities]) / 1000 | 38bf68ae714846c0b2eeb6ef144b40a167b88798 | 682,173 |
def zcount(list) -> float:
"""
returns the number of elements in a list
:param list: list of elements
:return: int representing number of elements in given list
"""
c = 0
for _ in list:
c += 1
return c | e0a80eb05121721783bb1b8f469fb6fcd8589318 | 682,174 |
from typing import Dict
def node_matcher_strict(node_attr_1: Dict, node_attr_2: Dict) -> bool:
"""
If node n1 in G1 are the same as node n2 in G2
:param node_attr_1: Dictionary of node attrs
:param node_attr_2:
:return:
"""
# check if they have the same set of attributes
# only check i... | fa51320e9bd9c5394e495c297eb99ec113d7ee45 | 682,175 |
import math
def must_tack_to_get_to(self, other, boat, wind):
"""Checks if tacks will be necessary to get to the other point from self"""
bearing = wind.angle_relative_to_wind(other.bearing_from(self))
return math.fabs(bearing) < boat.upwind_angle | e1933449dfbb276de937fde629969d8a0aa18552 | 682,176 |
def get_city(df, city_name=None, city_index=None):
"""
returns an info dict for a city specified by `city name` containing
{city_name: "São Paulo", city_ascii: "Sao Paulo",
lat: -23.5504, lng: -46.6339, country: "Brazil", iso2: "BR", iso3: "BRA",
admin_name: "São Paulo", capital: "adm... | 2a18eb4f4dba2714db522acee58ddd2474915fd2 | 682,178 |
import os
def get_output_path():
"""Return the location of the test output artifacts"""
default_path = os.path.join('tests', 'artifacts')
path = os.environ.get('ZOOM_TEST_ARTIFACTS_PATH', default_path)
return path | fdc8a37d2938744753fc7ddd44da259ac32081e8 | 682,179 |
def traceback(score_mat, state_mat, max_seen, max_list, seq_m, seq_n):
"""
This function accepts two m+1 by n+1 matrices. It locates the coordinates
of the maximum alignment score (given by the score matrix) and traces back
(using the state matrix) to return the alignment of the two sequences.
Inpu... | 399e27d46d9ae772e8d35ad6c642a68a44ffdd8f | 682,182 |
def gen_group_names(n_groups):
"""
Generate `n_groups` random names.
"""
if n_groups == 0:
return
return [str(i) for i in range(n_groups)] | d43341b42900d76e68d71b563c8ad582f6257acf | 682,183 |
def find_fcb_offset(content):
"""
Find Flash Control Block offset
@return int offset >=0 on success, -1 if an error occured.
"""
try:
index = content.index(b'FCB ')
if (index > 4):
return (index-4)
return -1
except ValueError as exc:
return -1 | ba9eac4a51aa3ab07a202dc8a347d4504ecdd877 | 682,184 |
def get_last_n_letters(text, n):
"""
The below line is for unit tests
>>> get_last_n_letters('This is for unit testing',4)
'ting'
"""
return text[-n:] | 117f52a9eefb2e9e6aec062ccc5221fffa4fc32a | 682,185 |
def impute_missing(df):
""" This function detects all missing values and imputes them with the Median of the column each missing value belongs to. """
df=df[df.columns].fillna(df[df.columns].median())
return(df) | acf9a18848729bad4d16d7bec32169bf5105f2b7 | 682,186 |
def premint_token_address(accounts):
"""An address whose account on the foreign chain has been endowed with some tokens."""
return accounts[0] | 978dbb2e305f6fb7431151689dbeae9c16a77958 | 682,187 |
import argparse
def build_arg_parser():
"""Build an argument parser using argparse"""
parser = argparse.ArgumentParser(
description="Smatch calculator -- arguments")
parser.add_argument(
'-f',
nargs=2,
required=True,
type=argparse.FileType('r'),
help='Two files containing AMR... | 3f1a45f1c6938b3842d2f84a68cbeccdd8786259 | 682,188 |
import struct
def get_chunk(filereader):
"""Utility function for reading 64 bit chunks."""
data = filereader.read(8)
if not data:
print("prematurely hit end of file")
exit()
bit64chunk = struct.unpack('Q', data)[0]
return bit64chunk | 6d7ea9c1396242ad40c2bdd14cf1408748300f54 | 682,189 |
def _allowed_file(filename):
"""Return True if file extension is allowed, False otherwise."""
extensions = ['csv', 'xls', 'xlsx']
return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions | d170a8042a93022b1beaebe1955fd9a102d0ff96 | 682,190 |
def cli(ctx, organism_id, metadata):
"""Update the metadata for an existing organism.
Output:
An empty, useless dictionary
"""
return ctx.gi.organisms.update_metadata(organism_id, metadata) | 5bddae765f550e8826d17cb458110b9abad139a3 | 682,191 |
def findLastK(head, k):
"""
方法功能:找出链表倒数第 k 个结点
输入参数:head: 链表头结点;k: 需要寻找的位置
返回值:倒数第 k 个结点所存的数值
"""
if k < 1 or head is None or head.next is None:
return None
cur = head.next
cnt = 0
while cur is not None:
cnt += 1
cur = cur.next
if cnt < k:
return ... | 2b97c20a4e0ef1d299004524c2545ccdaac3f62a | 682,192 |
import os
def _identify_folder_name(base, name):
"""
Allows folder names to be lowercase on case-sensitive systems.
Returns "base/name" where name is lowercase if the lower case version
exists and the standard case version does not.
Args:
base: the path containing the desired folder.
... | 5decca24f91ffbeaede2471abe1a11a485153a03 | 682,193 |
import argparse
def generate_arguments(commands):
"""
Generates the arguments.
:param: commands: a list of callables decorated with @command
:returns: an ArgumentParser instance
"""
parser = argparse.ArgumentParser()
command_subparsers = parser.add_subparsers(dest="command")
for command in commands:
if ... | e3a603c59e736749e5fa0510eb93bb4d3547993f | 682,194 |
import re
import json
def _unmodel_hdf5(references):
"""Special JSON format from HDF5 prototype"""
# see https://gist.github.com/ajelenak/80354a95b449cedea5cca508004f97a9
ref = {}
for key, value in references["metadata"].items():
if key.endswith(".zchunkstore"):
source = value.pop... | e9d1a909ef99324f557df549f49c8446b898f526 | 682,195 |
import random
def create_random_graph(nodes):
""" Creates a random (directed) graph with the given number of nodes """
graph = []
for i in range(0, nodes):
graph.append([])
for j in range(0, nodes):
rand = random.randint(1, 100)
if rand % 2 == 0 and i != j:
... | 57401f41d0dbbd871dcefd369c22b82fc453b3f3 | 682,196 |
def critical_damping_parameters(theta, order=2):
""" Computes values for g and h (and k for g-h-k filter) for a
critically damped filter.
The idea here is to create a filter that reduces the influence of
old data as new data comes in. This allows the filter to track a
moving target better. This goe... | eb42e82d619650b107c16da049c3d59043b1be70 | 682,197 |
import numpy
def argsort(x, topn=None, reverse=False):
"""
Return indices of the `topn` smallest elements in array `x`, in ascending order.
If reverse is True, return the greatest elements instead, in descending order.
"""
x = numpy.asarray(x) # unify code path for when `x` is not a numpy array... | dbc6103e305aa9b0ad31f26e648aa0fa69d1188d | 682,198 |
import argparse
import os
import json
def main():
"""Main entry point of the script."""
parser = argparse.ArgumentParser()
parser.add_argument('--root', default=os.path.join(os.getcwd(), 'pigweed'))
parser.add_argument(
'--json', default='pw_env_setup/py/pw_env_setup/cipd_setup/pigweed.json')
parser.a... | 4697b0d97de81d0bef1c046427e821a1e8bc7d28 | 682,199 |
def clo_dynamic(clo, met, standard="ASHRAE"):
""" Estimates the dynamic clothing insulation of a moving occupant. The activity as
well as the air speed modify the insulation characteristics of the clothing and the
adjacent air layer. Consequently the ISO 7730 states that the clothing insulation
shall be... | 7ac9c7274a3333c389e226c611e127d5ed101468 | 682,200 |
def easeInOutCubic(currentTime, start, end, totalTime):
"""
Args:
currentTime (float): is the current time (or position) of the tween.
start (float): is the beginning value of the property.
end (float): is the change between the beginning and
destination value of the propert... | e9cdb21918cea625fff8bd38deb2eb09dfae4b86 | 682,201 |
def is_valid_part2(entry):
"""
Validate the password against the rule (part 2)
Position 1 must contain the token and position 2 must not.
"""
# note that positions are 1 indexed
pos1 = entry.param1 - 1
pos2 = entry.param2 - 1
result = (entry.password[pos1] == entry.token) \
and... | 3af62a4c76045aaf30ed02ad7f2dcd5abf2fb242 | 682,202 |
def reform_prediction(df, prediction, mva=30):
"""
This was really intended only to work as the very last point in the
known data. So if using intermediate points, you have to cut off the df
at the last point before it's being predicted.
:param df: a pandas dataframe of the known data. This should... | 6065d220b5b23c3855fc4dfe5019b8b8699d839d | 682,204 |
import sys
def extract_params():
"""
Extract parameter from line of commands.
Output:
params = list of parameters from original command line
"""
params = sys.argv
return params | 9f18750656a3a5e1421cc4c3b53394874e75440b | 682,206 |
def get_index_by_excel_title(title: str):
"""根据Excel 的title 名称 值获取Excel 数据index值"""
title = title.upper()
name_dict = {v: i + 1 for i, v in enumerate(list("ABCDEFGHIJKLMNOPQRSTUVWXYZ"))}
index = 0
for c, t in enumerate(title[::-1]):
index += name_dict[t] * 26 ** c
return index | 9efbb922a8f7dc96bd61010619734c0be061ade1 | 682,208 |
def prepareFixed(query, ftypes, fixed):
"""Called by :meth:`.FileTreeManager.update`. Prepares a dictionary
which contains all possible values for each fixed variable, and for
each file type.
:arg query: :class:`.FileTreeQuery` object
:arg ftypes: List of file types to be displayed
:arg fixe... | 7a67b5828d19229954e6e7ddbfa93e743f0c678c | 682,209 |
def manhattan(p1, p2):
"""Return manhattan distance between 2 points."""
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1]) | 2836b18004733be2fe9a04adfec2e67651ea1f03 | 682,210 |
def process_ping_rpc(ping_output):
"""Process data in RPC output object."""
# format string for reply header
ping_reply_header = ('Sending 5, 100-byte ICMP Echos to {destination}, '
'timeout is 2 seconds:\n')
# format string for reply trailer
ping_reply_trailer = ('\nSuccess... | c1b422b4bfb2b3a62e256ccafc539e74a8788efb | 682,211 |
def __putBackEntities(str):
"""Put 'back' entities for the '&', '<', and '>' characters, to produce kosher XML string.
Used by XML Literal
@param str: string to be converted
@return: string with entities
@rtype: string
"""
return str.replace('&', '&').replace('<', '<').replace('>', '&... | ff25ec7a77e6ba755661e29d3964a7292fc78b9b | 682,212 |
import re
def _load_line(fh) -> str:
"""Loads a line from the file,
skipping blank lines. Validates
format, and removes whitespace.
"""
while True:
line = fh.readline()
line = line.rstrip()
line = re.sub(" ", "", line)
if line:
# Not blank.
... | 4792f9acfd6a0bfc7055bfbe78d78c0a211f222f | 682,213 |
def find_all_lowest(l, f):
"""Find all elements x in l where f(x) is minimal"""
if len(l) == 1: return l
minvalue = min([f(x) for x in l])
return [x for x in l if f(x) == minvalue] | 3e7154dc626086643d37115579fba51c6ae1c09a | 682,214 |
def switch(switch_factory):
"""
Fixture that represents a simple on/off switch as a "state machine".
"""
switch_factory.state = 'off'
return switch_factory() | cb719ac5a845a2511b158db716cf4000b4facdec | 682,215 |
import random
def random_prob(prob):
"""
随机生成真值
"""
x = random.choices([True, False], [prob, 1-prob])
return x[0] | f1f6f6cbfc05d83e78f9f1e72aabe7a1ae889a31 | 682,216 |
def transcriptHasOutOfFrame(t):
""" check to see if the annotations contain an outOfFrame label
"""
for a in t.annotations:
if 'outOfFrame' in a.labels:
return True
return False | 93be779146b1ab88903863c5c7208b9d398d3dbe | 682,217 |
def get_num_attachments(connection):
"""Get the number of attachments that need to be migrated"""
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql")
return cursor.fetchone()[0] | 3030a564c922bc77c10de9e84a7646731a1e0c6a | 682,218 |
import os
import yaml
def load_data_yaml(file_path):
"""
Loads yaml file from the .setup/data directory returning the parsed structure
:param file_path: name of file to load
:return: parsed YAML structure from loaded file
"""
if not os.path.isfile(file_path):
raise IOError("Missing the... | 029bcf4f02eacb754d4305c5b91b6766e865cef5 | 682,220 |
def is_sorted(ls):
"""Returns true if the list is sorted"""
return ls == sorted(ls) | 28e3b0f57ef7ae0a2032c71951572eba50e87230 | 682,221 |
import os
import argparse
def check_file(a_file):
"""For validating CLI input, and ensuring the supplied file is real.
:Returns: String
:param a_file: The value passed to the CLI
:type a_file: String
"""
a_file = os.path.abspath(a_file) # for better error messages
if not os.path.isfile(a... | 307e5960504a728f8250a42e956d6be1ce1afcac | 682,222 |
def decode(x: bytes) -> str:
"""Decode a string like done in `os._createenviron` (hard-coding utf-8)"""
return x.decode("utf-8", errors="surrogateescape") | 65a3116a4ad00ef2fac3ee63eddec665fed8f8de | 682,224 |
import math
def sin100( x ):
"""
A sin function that returns values between 0 and 100 and repeats
after x == 100.
"""
return 50 + 50 * math.sin( x * math.pi / 50 ) | ceb2d7627ff7d478f5aef40a9fc8027fb48174bd | 682,225 |
def curve_between(
coordinates, start_at, end_at, start_of_contour, end_of_contour):
"""Returns indices of a part of a contour between start and end of a curve.
The contour is the cycle between start_of_contour and end_of_contour,
and start_at and end_at are on-curve points, and the return value
... | 56996fd7ed196ab6b0b7cae966fa34d5f5849b9a | 682,227 |
def get_max(a: int, b: int) -> int:
"""
if a < b then -(a < b) = -1
elif a > b then -(a < b) = 0
(a^b) & -1 = a^b
(a^b) & 0 = 0
"""
return a ^ ((a ^ b) & -(a < b)) | f7baee131a95844f23a49f7444993972f93a69e3 | 682,229 |
from typing import Dict
def _to_kwargs(params: Dict) -> str:
"""Stringify the params as an arg list
:param params: The params
:return: A string representation of the parameters in the for `param=arg`.
"""
return ", ".join(f"{k}={v}" for k, v in params.items() if k != 'name') | 1e9fec386238395ff088d22186727421250f2267 | 682,230 |
import mmap
def get_num_lines(file_path):
"""get the number of data point in the csv file
Args:
file_path (string): path to a csv file
Returns:
int: number of lines in csv file
"""
fp = open(file_path, "r+")
buf = mmap.mmap(fp.fileno(), 0)
lines = 0
while buf.readline... | c9421f37085c2397600bf5624b82d36860f46b5b | 682,231 |
import sys
import os
def __generate_filename():
"""Generate a log filename based on pid and program name.
Conventional log filename has the following format:
``/<log dir>/<program name>. <pid>.log``
(e.g. "/tmp/hello_world.1234.log").
Returns:
A string for the log filename.
"""
... | 99b3f9b175b6b63cc327f62f57d0b6990d46d224 | 682,233 |
def qsort1(list):
"""Quicksort using list comprehensions"""
if list == []:
return []
else:
pivot = list[0]
lesser = qsort1([x for x in list[1:] if x < pivot])
greater = qsort1([x for x in list[1:] if x >= pivot])
return lesser + [pivot] + greater | ce243ea1b40d20012cb05f3c00692e6b0b1d0e87 | 682,234 |
def encode_output(app, text):
""" Encode the output to be suitable for the terminal
:param app: The Cement App (unused)
:param text: The rendered text
:return: The encoded text
"""
return text.encode("utf-8") | 38de95c7d79492f6614ed1b99b5024f4d3f7823f | 682,235 |
def X_y_split(data: list):
""" Split data in X and y for ML models. """
X = [row[0] for row in data]
y = [row[1] for row in data]
return X, y | c81aff64f2c44b3663715a23375ab7fdc0818636 | 682,236 |
def chunked(arr, chunk_size: int, include_remainder=True):
"""
return an array of array chucks of size chunk_size.
This is NOT an iterable, and returns all the data.
"""
size = (len(arr) + chunk_size - 1) if include_remainder else len(arr)
return [arr[chunk_size*i:chunk_size*(i+1)] for i in rang... | 86d3e33897c2bfbe5fd37e80715c4a2e36d1b9e8 | 682,237 |
def reverse_complement(seq):
"""
Exercice 1.3.2 ReverseComplement
Description: Reverse complement a nucleotide pattern.
Input: A DNA string seq.
Output: the reverse complement of seq
Sample Input:
AAAACCCGGT
Sample Output:
ACCGGGTTTT
"""
r = []... | e8868d429beda67625098b696573d9c674b31964 | 682,239 |
def blackBox(thing1, thing2, num):
"""Do crazy stuff!"""
return thing1 * num + thing2 | 8b2f5e10264a356cd36a6bd35073ee3b64bf0395 | 682,240 |
import os
def _check_files(*args):
""" Check if files exist.
Arguments
---------
args: str
List of files to check.
Returns
-------
int:
Number of non-existing files.
"""
n_error = 0
for filename in args:
if filename is None:
continue
... | bfec6767babf6d11971e214bf0ace773cc87930d | 682,241 |
def attr_str(ctrl_name, attr_name):
"""
join the two strings together to form the attribute name.
:param ctrl_name:
:param attr_name:
:return:
"""
return '{}.{}'.format(ctrl_name, attr_name) | d4d31919d8f972045e739f3d02ed793e4d368c58 | 682,242 |
def percent_change(starting_point, current_point):
"""
Computes the percentage difference between two points
:return: The percentage change between starting_point and current_point
"""
default_change = 0.00001
try:
change = ((float(current_point) - starting_point) / abs(starting_point)) ... | 3344139c838f92cf26d798899829f700231efa46 | 682,243 |
def internal_header_to_external(internal_header: str) -> str:
"""
Within our app we access headers in this form
HTTP_LMS_TYPE but they are supplied like LMS-TYPE.
This converts the internal form to the external form for error reporting
purposes.
"""
assert internal_header.startswith('HTTP_'... | 32b0efade8b74d1ef543b2c5f686bf1d3c4080a6 | 682,244 |
import re
def percent_chinese(sentence: str)-> bool:
"""
过滤掉英文字符和数字占30%的文档
:param sentence:
:return:
"""
#文本总的长度
tol = len(list(sentence.split()))
pattern = '[a-z0-9]+'
#英文和数字的长度
english_count = len(re.findall(pattern, sentence))
return english_count/tol < 0.3 | cbc4e0fa568657562273424b965afd1b3e8e872a | 682,245 |
import unicodedata
import re
def removespetialchar (palavra, feature, parent):
"""
Substitui caracteres especiais.
<h2>Examplo:</h2>
<ul>
<li>removespetialchar('coração') -> coracao </li>
<li>removespetialchar('gênesis') -> genesis</li>
</ul>
"""
# Unicode normalize transforma ... | 683ead98be94bdd846c741010fd34ad47b490092 | 682,246 |
def get_deps(project_config):
""" Get the recipe engine deps of a project from its recipes.cfg file. """
# "[0]" Since parsing makes every field a list
return [dep['project_id'][0] for dep in project_config.get('deps', [])] | eb3fa956348cea97f5c819f2c1e860b12a367947 | 682,247 |
def get_major(parent_decision) -> bool:
"""returns the major parent decision in boolean form"""
return True if parent_decision[0] > parent_decision[1] else False | 8f1016d5dc70665ef33a0636b935808c4018d8cb | 682,248 |
def get_variables():
"""Create and return a dictionary of test variables for the specified
test case.
:returns: Dictionary of test variables - settings for Honeycomb's Policer.
:rtype: dict
"""
policer_data = {
"policer_data": {
"name": "policy1",
"cir": 450,
... | b98270cfd78d6b0e9b463a5d9007922092972f8f | 682,249 |
from typing import Any
import base64
import gzip
import json
def compress(input: Any) -> str:
"""
Convenience function for compressing something before sending
it to Cloud. Converts to string, encodes, compresses,
encodes again using b64, and decodes.
Args:
- input (Any): the dictionary t... | 915a4e60fcf1eb62b14a23ebeeb52143493a27b3 | 682,251 |
def FindNumbersWithSum(arr, value):
"""
(一)递增排序arr,在数组中查找两个数,使其和为value
:param arr:
:param value:
:return:
"""
result = []
left = 0
right = len(arr) - 1
while left<right:
if arr[left] + arr[right] == value:
result.append([arr[left], arr[right]])
le... | a91d352634bdc8b12b018357289180eeb881909d | 682,252 |
def _parameterval(tsr,sol,coef):
"""
Creating polynomial surface based on given coefficients and calculating the point at a given TSR and solidity
Parameters
----------
tsr : float
specified tip-speed ratio
sol : float
specified solidity
coef : array
the polynomial s... | 7059cfaa833d027f3d9776df1c9687f586d1efff | 682,254 |
def get_all_events(cursor):
""" gets a list of all the events
Args:
cursor: the cursor
Returns:
tuple with the names of the events
"""
cursor.execute("Select eventname,eventdescription,hostname,location from Events")
events = []
while True:
res = cursor.fetchone(... | ddc80100af79c77500c8debfb9e8943d145e83f1 | 682,255 |
def get_callback(request, spider):
"""Get ``request.callback`` of a :class:`scrapy.Request`"""
if request.callback is None:
return getattr(spider, 'parse')
return request.callback | 090332b01311cbcdb45f5bdd51c5351146626f45 | 682,256 |
def create_header(stack):
"""
This function generates a header to initilise the stack
"""
prehead = map(lambda x: ''.join([
''.join(['+']*(x//2**8)),
'>+>',
''.join(['+']*(x%2**8))]),
stack)
head = ''.join(['+>',
'>+>'.join(prehead),
'<<<'])
... | c3f719ac39fa4b655dfac647f055aa949f4d2823 | 682,257 |
import hashlib
import binascii
def verify_password(stored_password, provided_password):
"""Verify a stored password against one provided by user"""
pwdhash = hashlib.pbkdf2_hmac(
"sha256",
provided_password.encode("utf-8"),
stored_password["salt"].encode(),
10000,
)
ret... | 38808c8a713ed1c78df82847c885d4f57d07d4e1 | 682,259 |
import requests
def get_transcript_ids(gene, ref37=False):
""" Get transcript ids from ensembl
REST API from ensemble gene ID
"""
if ref37:
server = "http://grch37.rest.ensembl.org/"
else:
server = "http://rest.ensembl.org"
ext = "/lookup/id/{0}?species=homo_sapiens;expand=1"
... | 8aa174991850ec10e6e7932d741edb91669625ab | 682,260 |
import re
def unescape_str(str, indent):
"""
Unescape string function which handles email addresses and urls
:param str: string
:param indent: indent
:return: string
"""
indent += "\t"
str = str.replace('\n', "\n{}".format(indent))
str = str.replace('\r', "\r")
str = str.replac... | 72740d3497e7225e364f7a5e55a5ce2447c41a29 | 682,261 |
def circular_algorithim(state_list,vals,vecs,param):
"""
alogorithim specifically written to find circular states, where the
s state above is also being calculated.
Assumes the largest returned eigenstate is always a given state.s
"""
idx = vals.argsort() #first sort the returned eigens f... | cafe1cc11d43184328649ebc5810726f96dd61a5 | 682,262 |
def get_lat_lon_alt(pandora_filepath):
"""Returns a dictionary of lat, lon, alt extracted from the pandora file
:param pandora_filepath: The pandora file
:type pandora_filepath: str
:returns: A dict of {"lat":lat, "lon":lon, "alt":alt}
:rtype: dict{str:int}
"""
lat = None
lon = None
... | f363978431a03ee09855c8895e7c164e6934b8df | 682,263 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.