content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def two_sum(arr, target):
"""Function takes in two args, the input array
and the target.
T: O(n) - We loop through the array once
S: O(n) - We use an extra data structure to store the target-curr
:param arr: Input array
:param target: Target
:return: list of two numbers, else empty a... | 469b63e97bb346a4d344682f19e84f1f5c979e1b | 686,087 |
from typing import Type
from typing import Any
from typing import Hashable
def kwargify(item: Type[Any], args: tuple[Any]) -> dict[Hashable, Any]:
"""Converts args to kwargs.
Args:
args (tuple): arguments without keywords passed to 'item'.
item (Type): the item with annotations used to co... | 2ffd674fa048ccc79ef1589d28dcb743e9e3a237 | 686,088 |
import argparse
def get_parser():
""" Setup parser for command line arguments """
main_parser = argparse.ArgumentParser()
main_parser.add_argument('--data_path', type=str, default=None,
help='Path to database with filtered, generated molecules '
... | 8bb2ab24c6da9d77262cca2df85a580fbf436414 | 686,089 |
import torch
def MRR(logits, target):
"""
Compute mean reciprocal rank.
:param logits: 2d tensor [batch_size x rel_docs_per_query]
:param target: 2d tensor [batch_size x rel_docs_per_query]
:return: mean reciprocal rank [a float value]
"""
assert logits.size() == target.size()
sorted,... | 726f9b9171bc5de81e86693db7502b8b4c50df88 | 686,090 |
def sort_diffs(diff):
""" Sort diffs so we delete first and create later """
if diff['action'] == 'delete':
return 1
else:
return 2 | 56b0fc0d3230915b05972d3042942a1c8dd2c52c | 686,091 |
def update_query_object(query, data, exceptions=[]):
"""Iterates over given data object. Set attributes to SQLAlchemy query.
Args:
query (obj): SQLAlchemy query object
data (obj): Given request's arguments from JSON
exceptions (list): Keys for which iteration
... | d838844364097f2c6e8c97884988f72e6c84e0c0 | 686,092 |
def build_counts_dict_from_list(count_list):
"""
Add dictionary counts together
"""
if len(count_list) == 1:
return count_list[0]
new_count_dict = {}
for countdict in count_list:
for x in countdict:
new_count_dict[x] = countdict[x]+new_count_dict.get(x, 0)
retu... | 5ae5c12be432e2a59d83c930523f2a25fd0506e2 | 686,093 |
def pv_f(fv, r, n):
"""Objective: estimate present value
fv : = future value
r : = rate of discount
n : = num of iterations (usually num of years, num of months etc)
fv
formula : pv = --------
(1 + r) ^ n
"""
pv = 0
iCount = 0
for cash in fv:
... | 8cb1072c03125c9c9721bcf69b9ce534479a2a37 | 686,096 |
def _deep_get(instance, path):
"""
Descend path to return a deep element in the JSON object instance.
"""
for key in path:
instance = instance[key]
return instance | 3dad3eed0115c244ee60e887049747200ed1838c | 686,097 |
import torch
def rgb_transpose(img):
"""
from [..., y, x, rgb] to [..., y, x, rgb]
"""
_ = {img.shape[-1], img.shape[-3]}
assert 3 in _ and len(_) == 2, img.shape
if img.shape[-3] == 3:
return torch.einsum('...cyx->...yxc', img)
else:
return torch.einsum('...yxc->...cyx', i... | cb67392a67d97929098a3c81ea80fbbce3bc9698 | 686,098 |
def _is_db_connection_error(args):
"""Return True if error in connecting to db."""
# NOTE(adam_g): This is currently MySQL specific and needs to be extended
# to support Postgres and others.
conn_err_codes = ('2002', '2003', '2006')
for err_code in conn_err_codes:
if args.find(... | 0fb14a654443616f44f3b76eb55e3f6d04e7808c | 686,099 |
def linear_full_overlap(dep_t, dep_h):
"""Checks whether both the head and dependent of the triplets match."""
return (dep_h[0] in dep_t[0]) and (dep_h[2] in dep_t[2]) | f88820129d39e4914935633793cb274ea71a9bdb | 686,100 |
import numpy
def IM_mscore(params):
"""
ms core command for IM.
"""
s,nu1,nu2,T,m12,m21 = params
alpha1 = numpy.log(nu1/s)/T
alpha2 = numpy.log(nu2/(1-s))/T
command = "-n 1 %(nu1)f -n 2 %(nu2)f "\
"-eg 0 1 %(alpha1)f -eg 0 2 %(alpha2)f "\
"-ma x %(m12)f %(m21)f x "... | 2b0894dce1d8349f8fe85fa4f2f86684d4cb40d9 | 686,101 |
def points_2_xywh(box):
""" Converts [xmin, ymin, xmax, ymax] to [xmin, ymin, width, height]. """
box = [box[0], box[1], box[2] - box[0], box[3] - box[1]]
box = [int(round(x)) for x in box]
return box | 24873f02ae4b828c0e43f139eda5b7eca360d9f9 | 686,102 |
import random
def talk_time(msg):
"""Formulae for calculating how long to type for."""
return len(msg.content) * 0.01 + (random.random() * 2 + 1) | 30d94c5067f2e0e457cb0de47e0ca3ce935db747 | 686,103 |
def _find_appliance(oneandone_conn, appliance):
"""
Validates the appliance exists by ID or name.
Return the appliance ID.
"""
for _appliance in oneandone_conn.list_appliances(q='IMAGE'):
if appliance in (_appliance['id'], _appliance['name']):
return _appliance['id'] | 565a996fec27389c93e857e848ae971ba2bdc709 | 686,104 |
def reference_sort(dataframe):
"""Function to sort mechanistic drug targets based on number of references."""
if not dataframe.empty:
dataframe["rank"] = dataframe["ref_map"].str.count(",")
dataframe = dataframe.sort_values(by=["rank"], ascending=False).drop(columns=["rank"])
return datafram... | 319b942fea2850fb2204eb4cf386f0c4ff6294fb | 686,105 |
import time
def get_datetime_string(format_string='%m:%d:%Y:%X'):
"""
Returns a string representation of current (local) time
:kw format_string: Format string to pass to strftime (optional)
"""
return time.strftime(format_string, time.localtime()) | 62932e0c4ceea7c5c8078404681786caec3617b0 | 686,106 |
from functools import reduce
def sanitize_for_latex(text):
""" Sanitzes text for use within LaTeX. Escapes LaTeX special characters in
order to prevent errors.
"""
escape = '%_&~'
replacers = (lambda s: s.replace(e, r'\{}'.format(e)) for e in escape)
return reduce(lambda s, f: f(s), replacers,... | 817cc1497aafd46694165808d95fc2cb1b764a3d | 686,107 |
def mayanToNumber(mayanSymbols, mayan):
"""Find a mayan numeral in a list of mayan numerals."""
for val, nb in mayanSymbols.iteritems():
if ''.join(nb) == ''.join(mayan):
return val | 8fe8ce81a171be0057591cce35a821924c201db8 | 686,109 |
def make_free_energy_lines(condition_lambda0,
condition_lambda1,
alchemical_molecule,
lambda_step,
starting_lambda=0,
couple_intramol='no',
sc_alpha=0.5,
... | 66ab029b8482b8552145313251351b89c76cde6d | 686,110 |
def get_gdrive_id(url):
"""
Returns the gdrive ID by splitting with the delimiter "/" and getting the element on index 5 which is usually the gdrive ID for a file or folder
Requires one argument to be defined:
- The gdrive link (string)
"""
url = url.split("/")[5]
if "?" in url: url = url.s... | 27969ecaf04ccc28c352ccd6ce772bf3b6a8bcd4 | 686,111 |
from typing import List
import re
def split_quoted_string(string_to_split: str, character_to_split_at: str = ",", strip: bool = False) -> List[str]:
"""
Split a string but obey quoted parts.
from: "first, string", second string
to: ['first, string', 'second string']
Parameters
----------
... | eb85145bfe65c6f7ab0d49b1fb7ce31d393404c0 | 686,112 |
def postprocess(path,line1,line2):
"""return data as an array...
turn data that looks like this:
100 0.98299944 200 1.00444448 300 0.95629907
into something that looks like this:
[[100, 0.98299944], [200, 1.00444448], [300, 0.95629907], ... ]"""
y = []
d... | 6d6118741d2ebf49d0d7326a3c2c4ae35092a973 | 686,113 |
import re
def ValidateKeyId(key_id):
"""Ensures a key id is well structured."""
# Keys are hexadecimal
return re.match(r'[a-z0-9]+', key_id) | b7705d33135dfff38e48da0426eae339c45470d8 | 686,114 |
def find_invalid_venues(all_items):
"""Find venues assigned slots that aren't on the allowed list
of blocks."""
venues = {}
for item in all_items:
valid = False
item_blocks = list(item.venue.blocks.all())
for slot in item.slots.all():
for block in item_blocks:
... | 4773b19c5e8e792b61967217f5b75e85c69542db | 686,116 |
import re
def timespec_to_seconds(ts):
"""
turn either hh:mm:ss or %dw%dd%dh%dm%ds
into seconds. for the latter, things like "1w" or "1w1s" are
ok, but "1s1w" (out-of-order) is not.
:param ts: string timespec
:return: integer seconds
"""
c = {'w': 0, 'd': 0, 'h': 0, 'm': 0, 's': 0}
... | 72a8b65ed31c5bcc4587ad9106e867c0f39e887d | 686,117 |
def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb... | 1341f99b4cf39a20a675d0473bd8f381216f4384 | 686,118 |
import os
def get_abs_path(relative_path: str) -> str:
"""Attempts to return the absolute path of a relative path
by joining the relative path with the project root
Args:
relative_path (str): the relative path
Returns:
str: the absolute path
"""
project_root = os.path.dirname(o... | 383b14595c44f78f20ca30554abedeee1a8055e8 | 686,119 |
import re
def mobile(mobile_str):
"""
检验手机号格式
:param mobile_str: 被检验字符串
:return: mobile_str
"""
if re.match(r'^1[3-9]\d{9}$', mobile_str):
return mobile_str
else:
raise ValueError('{} is not a valid mobile'.format(mobile_str)) | 780f44ab42700a1850f0725f6d62a3d097d605b7 | 686,120 |
def create_multiset_format(n, rs, pfs):
"""
Function that converts the given n, rs and pfs into a multiset format.
Arguments
=========
n: Total length of the permutations
rs: How many of each non-X elements should be present within each permutation
pfs: The value of each non-X prime factor ... | 0b69e88efdc35e6c5d9f2f6d30431a725f97286a | 686,121 |
def absoluteBCPOut(anchor, BCPOut):
"""convert relative outgoing bcp value to an absolute value"""
return (BCPOut[0] + anchor[0], BCPOut[1] + anchor[1]) | 4e6b8f4816cd8f6ec6125d4910983be9c1151c43 | 686,122 |
import os
def fixPaths(details, spaceDirectory, subDirectory=None, fileName=None):
"""
:param details:
:param spaceDirectory:
:param subDirectory:
:param fileName:
:return:
"""
if subDirectory:
if not os.path.isabs(subDirectory):
finalPath = os.path.join(spaceDirec... | a323b0f75b158863f2e9d771cbfe4ca548d6d1d7 | 686,123 |
import logging
def is_db_user_superuser(conn):
"""Function to test whether the current DB user is a PostgreSQL superuser."""
logger = logging.getLogger('dirbs.db')
with conn.cursor() as cur:
cur.execute("""SELECT rolsuper
FROM pg_roles
WHERE rolname... | ee3038d79c354e76e9383011d4a2d515b959e793 | 686,124 |
def intersect(a1, b1, a2, b2):
"""
Détection d'intersection entre deux intervalles : renvoie `false` si l'intersection de [a1;a2] et [b1;b2] est vide.
Arguments:
a1 et b1 (float): bornes du premier intervalle
a2 et b2 (float): bornes du second intervalle
"""
return b1 > a2 and b2 > ... | b1da6d8f182f565425cc82d80fb576820c1b6541 | 686,125 |
from typing import Sequence
from typing import Tuple
def my_quat_conjugate(q: Sequence[float]) -> Tuple[float,float,float,float]:
"""
"invert" or "reverse" or "conjugate" a quaternion by negating the x/y/z components.
:param q: 4x float, W X Y Z quaternion
:return: 4x float, W X Y Z quaternion
"""
return q[0]... | 821e96dff3e65f4f578bb1ad626bac91a06f7401 | 686,126 |
def topic_to_message_handler(topic, register_list):
"""Register handler to topic."""
def register(func):
register_list["send.{}".format(topic)] = func
return func
return register | 67b75661ce3a39e4edc88c16070da05ca198a037 | 686,127 |
def generate_ac_data(csv_writer,ballots,round,ac_cnt):
""" generate output for accumulation chart
"""
# Cand is who is getting eliminated
# Round is who is getting eliminated
# Segment is when accumulated
# csv_writer.writerow(['Ballot','Round','Segment','Number','Ranks'])
d = dict()
fo... | d6273f4813220cadb30ae31c17e5a4f3316ddf61 | 686,128 |
def S_adjust_phase_data(_data_list, _transform):
"""
Returns data samples where the phase is moved by transform amount.
"""
a_data = []
ds = len(_data_list)
for i in range(ds):
a_data.append((_data_list[i][0]+_transform, _data_list[i][1]))
return a_data | 8225570aceda2d63fe724d68db605720e3bd3f80 | 686,129 |
def GetTopicName(args):
"""Get the topic name based on project and topic_project flags."""
if args.add_topic:
topic_ref = args.CONCEPTS.add_topic.Parse()
elif args.remove_topic:
topic_ref = args.CONCEPTS.remove_topic.Parse()
else:
topic_ref = args.CONCEPTS.update_topic.Parse()
return topic_ref.Re... | 59c529a0af8bbd951b2141717c6069afc602afff | 686,130 |
def example_4_10_4(v):
"""
Lemma 4.10.3: For any C-vector a over F, the function f: FC −→ F defined by f(x) = a·x is a linear function.
Bilinearity of dot-product Lemma 4.10.3 states that, for any vector w, the function x → w · x is a linear function
of x. Thus the dot-product function f(x, y) = x · y ... | 36c0161e743c776317b227ad5078445364ee5d66 | 686,131 |
from typing import Iterable
from typing import Sequence
def arg_str_seq_none(inputs, name):
"""Simple input handler.
Parameters
----------
inputs : None, string, or iterable of strings
Input value(s) provided by caller
name : string
Name of input, used for producing a meaningful er... | 8077c6faf36784274856da8fbd2ea031c98170e0 | 686,133 |
from typing import MutableMapping
from typing import Any
def flatten(
dictionary: MutableMapping[Any, Any], separator: str = ".", parent_key=False
):
"""
Turn a nested dictionary into a flattened dictionary
Parameters:
dictionary: dictionary
The dictionary to flatten
paren... | d12c668e317ab10df1f9c6e4bb4da76767130327 | 686,134 |
def ramp(x):
"""smooth ramp function from curl noise paper"""
if x > 1.0:
return 1.0
elif x < -1.0:
return -1.0
else:
return 15.0 / 8.0 * x - 10.0 / 8.0 * x * x * x + 3.0 / 8.0 * x * x * x * x * x | 2cfe84498bfbf54120b3a204dbfe17050ef6615f | 686,135 |
import statistics
def score(text, *score_functions):
"""Score ``text`` using ``score_functions``.
Examples:
>>> score("abc", function_a)
>>> score("abc", function_a, function_b)
Args:
text (str): The text to score
*score_functions (variable length argument list): function... | 26947c68ddc76f16c783a8e84e683645cfaf7787 | 686,136 |
import pandas
def normalize_features(features):
"""
Normalize the features of MAC addresses.
Parameters
----------
features : list
A list of tuples, where each tuple contains
the features of a MAC address.
Returns
-------
numpy array
A numpy array with the normalized features
of MAC... | 6470c6bd0b79da3736c2d7c91cbaf21351c3ee58 | 686,137 |
import numpy
def norm(vector):
"""just a Frobenius norm for now
>>> norm([1,1,1,1])
2.0
"""
return numpy.linalg.norm(vector) | 6d184bc67c49e13b8c9a8e1596e7dfb36929c771 | 686,138 |
import random
def random_ind(N, begVal = 0,endVal = 64):
"""
Summary :
Parameters
----------
N : TYPE,
DESCRIPTION
begVal : TYPE,
DESCRIPTION
endVal : TYPE,
DESCRIPTION
Returns
-------
rndInts : TYPE,
DESCRIPTION
"""
rndInts = []
... | 217f466a56c6059fbd40ec1d91fada81bf8fe98d | 686,139 |
def line_lister(line):
""" Returns a a list of stripped line split on ','. """
return [li.strip() for li in line.split(',')] | 9e58acfb7aed6786d5c5199106a3aff0e587c8aa | 686,142 |
def ip_key(key):
"""Function to make a 'canonical' IP string for sorting.
The given IP has each subfield expanded to 3 numeric digits, eg:
given '1.255.24.6' return '001.255.014.006'
"""
ip = key[0]
fields = ip.split('.')
result = []
for f in fields:
result.append('%03d' % ... | 4cf8e887b32c123060e3899d6eb5e48d08329d34 | 686,143 |
def to_camel_case(snake_case):
""" convert a snake_case string to camelCase """
components = snake_case.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | e7433ec546cc93700bd67bd4e559795a9add31ed | 686,144 |
def dispatch_dict(operator, _x, _y):
"""Use dictionary to dispatch operator."""
return {
'add': lambda: _x + _y,
'sub': lambda: _x - _y,
'mul': lambda: _x * _y,
'div': lambda: _x / _y,
}.get(operator, lambda: None)() | 79479a9b35bcaf4b3583b684ce29f4af826d5138 | 686,145 |
import os
import yaml
def load_topo_file(topo_name):
"""Load topo definition yaml file."""
topo_file = "vars/topo_%s.yml" % topo_name
if not os.path.exists(topo_file):
raise ValueError("Topo file %s not exists" % topo_file)
with open(topo_file) as fd:
return yaml.safe_load(fd) | 9d2ece0e8a04622c23805539c1a968642cf8e87c | 686,146 |
import re
def RemoveLocations(test_output):
"""Removes all file location info from a Google Test program's output.
Args:
test_output: the output of a Google Test program.
Returns:
output with all file location info (in the form of
'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or
'DIRECTORY\\... | 6003836c813eb9c29213f91a7ca1592073b80a17 | 686,147 |
def editar_contato(lista, x, st):
""" A função edita e informa se uma informação foi editada ou se ela já estava na lista;
list, int, str - > bool """
if x<0 or x>3:
return False
if x != 1:
return True
if int(lista[1][0]) == int(st) or int(lista[1][1]) == int(st):
return Fals... | 8a931af2078df9ddb1547aca25051b47318d0ae3 | 686,149 |
def _ValidateReplicationFlags(flag_dict):
"""Verifies correct usage of the bigtable replication flags."""
return (not flag_dict['bigtable_replication_cluster'] or
flag_dict['bigtable_replication_cluster_zone']) | 1462455171f631cf18dc2e09650df2322d451dd6 | 686,151 |
def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
"""Converts a text to a sequence of words (or tokens).
# Arguments
text: Input text (string).
filters: Sequence of characters to filter out.... | 120e03f5a4849c83bb1f686f08fe5316f142b899 | 686,152 |
def get_grants(df):
"""Get list of grant numbers from dataframe.
Assumptions:
Dataframe has column called 'grantNumber'
Returns:
set: valid grant numbers, e.g. non-empty strings
"""
print(f"Querying for grant numbers...", end="")
grants = set(df.grantNumber.dropna())
print... | 0e3c5ab5444e07360310d2f9baf2de2dc60a8dcd | 686,153 |
import math
def round_to_order(value, order, round_op=None, as_int=False):
"""
:param value:
:param order:
:param round_op:
:param as_int:
:return:
"""
if round_op is None:
round_op = round
if order == 0:
value = round(float(value))
return int(value) if a... | 66466e2c382c9a6dd714c11ce4dff174e9f3a229 | 686,154 |
def getNumCustomMapOptionValues(argsList):
"""
Number of different choices for a particular setting
argsList[0] is Option ID (int)
Return an integer
"""
return 0 | 6cfe3c064bb503730d6d8d8683805959dda5e7c6 | 686,155 |
from typing import Optional
from pathlib import Path
def join_paths(path1: Optional[str] = "", path2: Optional[str] = "") -> str:
"""
Joins path1 and path2, returning a valid object storage path string.
Example: "/p1/p2" + "p3" -> "p1/p2/p3"
"""
path1 = path1 or ""
path2 = path2 or ""
# co... | 828a6cb6800475ead52c418d8d67cf9294b42e44 | 686,157 |
def stock_price_summary(price_changes):
""" (list of number) -> (number, number) tuple
price_changes contains a list of stock price changes. Return a 2-item
tuple where the first item is the sum of the gains in price_changes and
the second is the sum of the losses in price_changes.
>>> stock_price... | f0b207de0e0ffb0733d56b15f61208da72351c17 | 686,158 |
import os
def run_phenotools(start, end, term, hpo):
"""
Run phenotools for a single category
:param categ:
:return:
"""
mycommand = "../phenotools hpo --hp %s --date %s --enddate %s --term %s --out tmp.txt" % (hpo, start, end, term)
print(mycommand)
os.system(mycommand)
subontolog... | 3a044ed2ff9b668a4194351f61e1407f5671416e | 686,159 |
from typing import List
def longest_increasing_sub(numbers: List[int]) -> int:
"""
Dynamic Programming.
Time Complexity: O(n*n)
Space Complexity: O(n)
"""
length = len(numbers)
res = [1] * length
for i in range(1, length):
for j in range(0, i):
if numbers[j] < numb... | 5c6c44f5e0ac299d86ab57f658139b4afba35ca9 | 686,160 |
import struct
def seq_to_bytes(s):
"""Convert a sequence of integers to a *bytes* instance. Good for
plastering over Python 2 / Python 3 cracks.
"""
fmt = "{0}B".format(len(s))
return struct.pack(fmt, *s) | 4fdb239b83afeec0e7caaf7c92d55835bb072312 | 686,161 |
def add(numbers):
"""Sums all the numbers in the specified iterable"""
the_sum = 0
for number in numbers:
the_sum += int(number)
return the_sum | c27969b30a3c38e754ec928e00e17bb8a3d32418 | 686,163 |
def parse_int_ge0(value):
"""Returns value converted to an int. Raises a ValueError if value cannot
be converted to an int that is greater than or equal to zero.
"""
value = int(value)
if value < 0:
msg = ('Invalid value [{0}]: require a whole number greater than or '
'equal t... | 699c4a23abc23edffb6168ce9e0d6c8381506a3a | 686,164 |
def _read_quoted_string(s, start):
"""
start: offset to the first quote of the string to be read
A sort of loose super-set of the various quoted string specifications.
RFC6265 disallows backslashes or double quotes within quoted strings.
Prior RFCs use backslashes to escape. This l... | 6bfeea891ac9e0504d7062d952f7fa8ba28e7a42 | 686,165 |
import argparse
def parse_args(args):
"""CLI options takes sys.argv[1:]."""
parser = argparse.ArgumentParser(
description="Un-Archive a directory prepped by archivetar",
epilog="Brock Palen brockp@umich.edu",
)
parser.add_argument(
"--dryrun", help="Print what would do but don... | 686d84741a756c93b5a489b2a19ff3b16800b7f0 | 686,166 |
def power(x, y):
"""
Question 5.7: Given a double x and an integer y,
return x ^ y
"""
result = 1.0
# handling negative case
if y < 0:
x = 1.0 / x
y = -y
while y:
if y & 1:
result *= x
x *= x
y >>= 1
return result | 9d1dbdda7979fedb6b7b351eb1c19e29d5950c93 | 686,167 |
def evaluate_difference(lst_a, lst_b):
"""
Determines how much overlap there is between the two input lists.
Essentially a value function to maximize.
"""
assert isinstance(lst_a, list)
assert isinstance(lst_b, list)
lst_a_len = lst_a.__len__()
if lst_a_len > lst_b.__len__():
r... | 052ae98f2ba8d6b43ed0275ff956383cdaef9848 | 686,169 |
import string
def remove_punct(value):
"""Converts string by removing punctuation characters."""
value = value.strip()
value = value.translate(str.maketrans('', '', string.punctuation))
return value | 604b8ac8ea6df1bb9319372fcf091cc4c80f0e27 | 686,171 |
def correct_name_servers(logger, result, zone):
"""
This is to deal with issues in the whois library where the response
is a string instead of an array. Known variants include:
- "Hostname: dns-1.example.org\nHostname: dns-2.example.org\nHostname..."
- "No nameserver"
- "dns... | 2a88f6bbbbb49c200578cc7d1a3af09940baadd1 | 686,172 |
def rearrange(arr: list) -> list:
"""Copy, Sort and fill
Time Complexity: O(n*log(n))
Space Complexity: O(n)
"""
temp: list = sorted(arr)
l: int = len(arr)
even: int = int(l / 2)
odd: int = even + 1
j: int = odd - 1
for k in range(0, l, 2): # odd positions
arr[k] = temp... | 53000524ed7152fa2131137bd601572661cb97b1 | 686,173 |
import csv
import json
def hmtvar_annotations(insilicos_path: str):
"""Extract HmtVar in silico predictions for tRNA variants, retrieved via API using get_hmtvar.py.
:param insilicos_path: path to the insilicos directory with required file
:return: matches_hmtvar dictionary with HmtVar prediction for eve... | a0bd76c030109abd76cea5ddeda4deaff782eb89 | 686,174 |
import os
import tarfile
def extract_tarfile(tarfile_name, output_path, target_file_name='target'):
""" 解压tar或tar.gz文件.
@params:
tarfile_name - tar或tar.gz文件.
output_path - 输出路径.
target_file_name - 输出模板文件名称.
@return:
On success - 解压信息.
O... | 405fb7b4a69cd7ff347c6f4a145472a4695633c7 | 686,175 |
def zero_finder(bin_system):
"""
Walking through a cubic bin-system containing zeros and ones, searching for
a zero.
Parameters:
-----------
bin_system: array (x, y, z, 1)
cubic system containing zeros and ones
Returns:
--------
array (3, ), the position of the first zero-b... | 820ebba006a75ebdfcbd1bb9fad6b8530e0ca480 | 686,176 |
import os
def load_settings(path):
"""
Take given file path and return dictionary of any key=value pairs found.
"""
if os.path.exists(path):
comments = lambda s: s and not s.startswith("#")
settings = filter(comments, open(path, 'r'))
return dict((k.strip(), v.strip()) for k, _... | 95862a67176f5da8008228f91bb008ed15965bc3 | 686,177 |
import pickle
def default_model_read(modelfile):
"""Default function to read model files, simply used pickle.load"""
return pickle.load(open(modelfile, 'rb')) | 61946419d5905422da3025fabee02dc388c2568a | 686,178 |
import warnings
def combine_cols(df, combos):
"""Combine columns within a single data frame with the aggregation function
specified in each combination.
Args:
df: Pandas data frame.
combos: Tuple of combination column name and a nested tuple of
the columns to combine as ... | 97341831f5208135572df11c06460d2b87f2db3e | 686,179 |
def _variant_genotypes(variants, missing_genotypes_default=(-1, -1)):
"""Returns the genotypes of variants as a list of tuples.
Args:
variants: iterable[nucleus.protos.Variant]. The variants whose genotypes we
want to get.
missing_genotypes_default: tuple. If a variant in variants doesn't have
... | 0e5c280614a5b630406e17bfca36300ff6186226 | 686,180 |
import struct
def byte(number):
"""
Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)
representation.
Use it as a replacement for ``chr`` where you are expecting a byte
because this will work on all versions of Python.
Raises :class:``struct.error`` on overflow.
:param number:... | a09b43e037307d6963b7718b079ff93b2222d859 | 686,181 |
def getYear(orig_date_arr):
"""
return an integer specifying the previous Year
"""
if orig_date_arr[1] == orig_date_arr[2] == 1:
return orig_date_arr[0] - 1
else:
return orig_date_arr[0] | aca5fc98f8687299ba9842d7d68c4e92ef4f5106 | 686,182 |
import random
def generate_events(grid_size, event_type, probability, event_max):
"""
Generate up to 'number' of events at random times throughout the night.
Return events as a list of lists containing the event type and time grid index at which the event occurs.
Example
-------
>>> events = ... | 8c432b3e7a2fa22775f8b25068763c1f397f65a2 | 686,184 |
import os
def nr_cores_available():
"""
Determine the number of cores available: If set, the environment variable
`PYABC_NUM_PROCS` is used, otherwise `os.cpu_count()` is used.
Returns
-------
nr_cores: int
The number of cores available.
"""
try:
return int(os.environ[... | cdb284c342bfb40fe49557e99b2a9fec706ca99b | 686,185 |
def calc_pos_protected_percents(predicted, sensitive, unprotected_vals, positive_pred):
"""
Returns P(C=YES|sensitive=privileged) and P(C=YES|sensitive=not privileged) in that order where
C is the predicited classification and where all not privileged values are considered
equivalent. Assumes that pred... | b8a75d2794fe488c1412831bb57fe042306ac134 | 686,186 |
def getMedian(alist):
"""get median of list"""
tmp = list(alist)
tmp.sort()
alen = len(tmp)
if (alen % 2) == 1:
return tmp[alen // 2]
else:
return (tmp[alen // 2] + tmp[(alen // 2) - 1]) / 2 | 7f5f814e61feeaa68e9125e0acbd12f2cfdd033a | 686,187 |
def last(inlist):
"""
Return the last element from a list or tuple, otherwise return untouched.
Examples
--------
>>> last([1, 0])
0
>>> last("/path/somewhere")
'/path/somewhere'
"""
if isinstance(inlist, (list, tuple)):
return inlist[-1]
return inlist | cb4d8e1e594667417be059eb42f53f2d0f14f46b | 686,188 |
import argparse
def parse(arguments):
""" Parse cmdline's args into a struct.
Arguments:
- arguments: A string list of cmdline's args.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--database",
default=":memory:",
help='''
You ... | ad01ff4e54ad0cf23baa7acc638b55a34ec62b27 | 686,189 |
from typing import Any
import pickle
def get_papers_pickle(filename: str) -> dict[str, Any]:
"""retrive papers (dict format) from file in folder data/papers"""
with open(f"data/papers/{filename}", 'rb') as papers_file:
return pickle.load(papers_file) | 1d8ef83d34fd4ac92f83068570ae26745d80d0d5 | 686,190 |
import string
def count_words(filename):
"""
builds and return the dictionary for the given filename
Parameters: filename (file)
Returns: words_dict (dictionary) with all the words in the file and the
amount of times each appears
"""
words_dict = {} # initializes the dictionary
with o... | b996ac0857ac1008a39c6418e446afdd757c77c5 | 686,191 |
import math
def pressure_dict(calib, f, t):
"""SBE/STS(?) equation for converting pressure frequency to temperature.
Inputs:
calib is a dictionary of coefficients
T1: coefficient
T2: coefficient
T3: coefficient
T4: coefficient
T5: not used
C1: coefficient
C2: coefficient
C... | a0e4bfc35daeedbd0f2e287c5645827510801fac | 686,192 |
def pandas_mpc_session_number(filenames):
"""Return the session number given a Series of file names
(this is probably the fastest way to do it)
"""
return filenames.str.split(".").str[1].astype(int) | b55d7db171c97aeb8ceaba43ec1fd602fb71010c | 686,193 |
def read_freq(filename):
"""Read the occurrences of each quality value of wine; Return a list of outliers"""
n = 0 # Total number of data entries
data = {} # Dictionary to hold occurrences of each quality
outliers = [] # Any ratings that are outliers
with open(filename, 'r') as f:
next(f)... | ebc47542d28426ef11322b50f7d510e0ee0ada30 | 686,194 |
import requests
from bs4 import BeautifulSoup
def get_article(url):
"""
Gets article content from URL
Input : URL of article
Output : Content in BeautifulSoup format
"""
r = requests.get(url)
html_soup = BeautifulSoup(r.content, 'lxml')
return html_soup | 4b1246d8a1e3f60b29a0b4c0bf9540d345c3a936 | 686,195 |
import numpy
def partition_int(n, q):
"""
:param int n: int to be partionned
:param int q: number of partions
:return int-array p: such that:
- sum(p) == n
- len(p) == q
- for all i, j: |p[i] - p[j]| <= 1
"""
return n // q + (numpy.arange(q) < n % q) | ebcfeda3751c45773f2f61e5485e4e057b5cc0ce | 686,196 |
def translate_file_diff(data):
""" Translates data where data["Type"]=="Diff" """
diff = '\\FloatBarrier \section{Configuration}'
sections = data.get('Data')
for title, config in sections.items():
title = title.replace('_', '\_')
diff += ' \n \\subsection{$NAME}'.replace('$NAME', title)
... | b0fe10f15ef0031dddf9c122e8849cc9356c1f4a | 686,198 |
def dedupe_by_keys(data, dedupe_by):
"""Helper function for deduplicating a list of dicts by a set of keys.
"""
output = {}
for d in data:
output["".join([str(v) for k, v in d.items() if k in dedupe_by])] = d
return list(output.values()) | 455589f683f809d82b8ae3019376427ad9cc176a | 686,200 |
import pandas
def read_csv_from_excel(filename, sep="\t", encoding="iso-8859-1"):
"""
Read a file stored in CSV format from Excel.
@param filename filename
@param sep column separator
@param encoding default encoding
@return DataFra... | 15b11e0c084a43ed52d3d60c22d8f8df97f33f0b | 686,202 |
def _convert_from_european_format(string):
"""
Conver the string given in the European format (commas as decimal points,
full stops as the equivalent of commas), e.g. 1,200.5 would be written as
1.200,5 in the European format.
:param str string: A representation of the value as a string
:return... | 219d197532fc4dae6d3fee7f47f431ea06ec7e0e | 686,203 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.