content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def mat_exp(mat, p, mod):
"""
Fast Matrix Exponentiation with modulo
Parameters
----------
mat: numpy matrix
The matrix to exponentiate. It must be a matrix that supports the *
operator.
p: int
The power to raise the matrix to.
mod: int
The modulo value used t... | 56aae230633d5b76095961cd540fb5dbfc5e88de | 579,781 |
import io
def open_rt(path):
"""Open a file in text mode for reading utf-8."""
return io.open(path, 'r', encoding='utf-8') | 6dbb7c5d53d84f6de41ffa3284416a0f1d24caea | 579,790 |
def guarded_match(pattern, excerpt, pos=0):
"""Does a regexp match, avoiding any escaped characters in the match.
:Parameters:
- `pattern`: compiled regexp pattern
- `excerpt`: excerpt of text that should be matched
- `pos`: starting position of the match
:type pattern: re.pattern
:t... | b5d0ba047becd1f6ab0b653adb9d5ae607afe472 | 579,796 |
import re
def parse_label_map(label_map_path):
"""Parse label map file into a dictionary
Args:
label_map_path:
Returns:
a dictionary : key: obj_id value: obj-name
"""
# Open image has different label maps: {name: ... id: .... display_name: ...}
# MSCOCO and PASCAL has: {id:... name: ...}
is_oi... | 58199c2badb4d2bd9ced4aa41d098a26b85b12da | 579,797 |
def format_version(major, minor, patch, prerelease=None, build=None):
"""Format a version according to the Semantic Versioning specification
:param str major: the required major part of a version
:param str minor: the required minor part of a version
:param str patch: the required patch part of a versi... | e4682e5753f540f99a64fa4fff15f9cc03a38654 | 579,798 |
import math
def tile2latlon(x, y, zoom):
"""Convert x/y/zoom to lat/lon
Reference: https://github.com/stamen/the-ultimate-tile-stitcher
"""
n = 1 << zoom
lat_radians = math.atan(math.sinh(math.pi * (1.0 - 2.0 * y / n)))
lat = lat_radians * 180 / math.pi
lon = 360 * x / n - 180.0
retur... | 17a631cfe72847ad931e65b6810bfbf32e60e059 | 579,799 |
def hex_neighbours(x, y, z):
"""Returns the hexes that share an edge with the given hex"""
return [
(x + 1, y, z - 1),
(x, y + 1, z - 1),
(x - 1, y + 1, z),
(x - 1, y, z + 1),
(x, y - 1, z + 1),
(x + 1, y - 1, z),
] | c1fa08f6620fa695c46743d7b13f29f2621189ef | 579,800 |
def get_mf6_nper(tdisfile):
"""Return the number of stress periods in the MODFLOW 6 model.
Parameters
----------
tdisfile : str
path to the TDIS file
Returns
-------
nper : int
number of stress periods in the simulation
"""
with open(tdisfile, "r") as f:
li... | 80bb4103b56f865965355e5ed80f8c9635119e6d | 579,805 |
def tokyo_gas_2(contract, power):
"""
TOKYO GAS「ずっとも電気2」での電気料金計算
Parameters
----------
contract : str
契約アンペア数
power : float
前回検針後の使用電力量(kWh)
Returns
-------
fee: int
電気料金
"""
fee = 286.00
if power <= 360:
fee += 19.85 * power
else... | 6cacd6f042e64f5c93148d693588901d47a11c96 | 579,807 |
def check_special_non_rotor_cases(mol, top1, top2):
"""
Check whether one of the tops correspond to a special case which could not be rotated
`mol` is the RMG Molecule to diagnose
`top1` and `top2` are indices of atoms on each side of the pivots, the first index corresponds to one of the pivots
Spe... | 8b2dc235f6b75591e532ee579b977b3899decce5 | 579,809 |
def parse_sourceparams(sourceparams):
"""
Split sourceparams string of the form key1=val1[,key2=val2,...]
into a dict. Also accepts valueless keys i.e. without =.
Returns dict of param key/val pairs (note that val may be None).
"""
params_dict = {}
params = sourceparams.split(',')
if ... | d2ab62472c7c3b82794159389ae570a818fbea67 | 579,814 |
def ListUnion(list_1, list_2):
"""Returns the union of two lists. Python sets can have a non-deterministic
iteration order. In some contexts, this could lead to TensorFlow producing
two different programs when the same Python script is run twice. In these
contexts we use lists instead of sets. This function is ... | dad99d32c895da1cb6e050cd5b73d3226ef9a4c9 | 579,817 |
def symsStr() -> str:
"""Returns all speacial characters as a string"""
symbols: str = "`~!@#$%^&*()_-+={[]}|\\:;\"'<,>.?/"
return symbols | 4e18bf8604954eb55617bf06a894d9a63c43a26c | 579,822 |
def new_config(random_dt):
"""Create a configuration that will not hit the database."""
new_config = dict(
name='supernaekei',
# refers is missing on purpose
metadata={'user': 'tsirif',
'datetime': random_dt,
'orion_version': 0.1,
'us... | 9973982a0bca01206e1a2b7615913c79df786b53 | 579,824 |
from typing import Union
from typing import List
def replaced(obj: Union[int, List], old: int, new: int) -> Union[int, List]:
"""Return a new nested list that is the same as obj, but with all
occurrences of old replaced by new.
>>> replaced([[[4, 5], [5]], [3, 5, [[20]]], 3], 5, 555)
[[[4, 555], [555... | 262ee96b5fa40eecaef4e0ef68b5e3da0372c024 | 579,828 |
def Uunbalance_calc(ua,ub,uc):
"""Calculate voltage/current unbalance."""
uavg = (ua + ub + uc)/3
return (max(ua,ub,uc) - min(ua,ub,uc))/uavg | 59dcba54c98f3068b0332dcd24631f06a34a2976 | 579,830 |
def xstr(s):
"""Converts None to '' if the object's value is None"""
if s is None:
return ''
return str(s) | 7197dfa4fe1d0e2d3abe81c113c923b3cdf6938e | 579,832 |
def get_lambda_path_from_event(event) -> str:
"""Builds the lambda function url based on event data"""
lambda_path = event["requestContext"]["path"]
lambda_domain = event["requestContext"]["domainName"]
return f"https://{lambda_domain}{lambda_path}" | 7373866276356b518633252328be91fadd0c5eb2 | 579,836 |
def check(move, occupied, width, height, n=1):
"""
_Purpose:
takes a move coord and returns a score based on how many free spaces are around the move of distance n
_Parameters:
move (tuple): xy coord of the move
occupied (list): xy coords all occupied spaces on board
width (int): width of board
height (int): ... | 1d2034e28a940fae4d67495d30f83046f363c8f5 | 579,838 |
def drop_rows_over_max_taxa(
data, max_taxa_per_query):
"""
Drop rows where "n_taxa" is greater
than max_taxa_per_query. This removes uninformative
rows with too many taxa.
"""
return data[data["n_taxa"] <= max_taxa_per_query] | 7d90025ea224ab366aa6176f7576d5337d464ddd | 579,839 |
import re
def _normalize_github_url(url):
"""Normalize a GitHub url so that there is one unique URL representation
per repo.
"""
url = re.sub(r'\.git$', '', url) # Strip trailing .git
url = re.sub(r'\.$', '', url) # Strip trailing period
return url.lower() | 7a875bc88e47caef894a673cd27fef0702bbdfe9 | 579,840 |
def formatnumber(value, p=1):
"""return a formated number with thousands seperators"""
try:
return "{:,.{}f}".format(float(value), int(p))
except (ValueError, TypeError):
return None | 249ee6259a30752ca528f2377393a058d1c4065a | 579,843 |
import random
def rand_9() -> int:
"""
Generates a single, randomly generated 9-digit number.
Returns:
The generated 9-digit number.
"""
return random.randrange(1000000000) | 2725fbb3f600f60e1d787582dd666855362c3f90 | 579,844 |
def read_box(path):
"""Read side lengths of the simulation box.
Parameters:
path: str
File path to Lammps' data file (or molecule file).
"""
lines = (line.lstrip().rstrip() for line in open(path))
lx, ly, lz = (None,) * 3
done = False
for line in lines:
if not done:
if line.endswith("... | 04bb572ffde8021e5c2de27f57dd5769df91c3a3 | 579,846 |
import codecs
def fetch_file(parsed_url, config): # pylint: disable=unused-argument
"""
Pull files from the local file system.
"""
with codecs.open(parsed_url.path, 'r', encoding='utf-8') as _file:
contents = ''.join(_file.readlines())
return contents | 999c13c4401c8664e15191b0984f332208529f1c | 579,849 |
def get_cache_entry(key, cache=dict()):
"""
Return the value at index `key` in the Opaque Client cache or None if the
index `key` doesn't exist.
parameters
----------
key : str
Key in the cache
cache: dict
The cache dictionary. This should only be set by the decorator functi... | 548914f8dc00cc42090ea66bb6bcfa5602306cb5 | 579,852 |
def align_down(alignment, x):
"""Rounds x down to nearest multiple of the alignment."""
a = alignment
return (x // a) * a | 7441aa9fc7be9720ad6f518f62ca7400bb800013 | 579,857 |
def Btu_lb2J_kg(x):
"""Btu/lb -> J/kg"""
return x*2326.0 | d47f337f3a5734e04a8eb2905d0b0ee9aa7f8a48 | 579,858 |
def alert2subject(alert_obj):
"""
Transforms an alert into a subject for mails
:param alert_obj:
:return:
"""
return '[WEBMONITOR] WEBSITE : ' + alert_obj['website'] + ' IS ' + alert_obj['status'] | d582eb5c0c02ea643ba7e5ee7d323f997bff8a30 | 579,866 |
def getStateCentre(state):
"""
The 'centre' tuple contains the lat/long and 'width (in whole degrees)'
of the centre of the 'state' (or the Country 'AUS').
The return value is not always strictly within the state.
"""
try:
centre = {
'NSW': (-32, 145, 3),
'QLD': (-24, 145, 4),
'VIC': (... | a8f2c66499a72fcb214d08a3f7c133be23473971 | 579,869 |
def update_dataframe(df1, df2):
"""Update df1 with the contents of df2
This operation:
- returns df1 if df2 is None,
- adds new columns in df1 (initialized to 0), if columns in
df2 exist that are not already in df1,
- overwrites rows in df1 with rows from df2, or adds rows
in df1 from ... | 8ba79cec8ffc95c73ede4fb629102cad3a12bd4f | 579,873 |
def _normalize_row(row, mean_arr, std_arr):
"""
Normalize individual row by computing the standard score (z-score) of each
feature with respect to mean mean_arr and standard deviation std_arr.
Args:
row: Individual row of DataFrame.
mean_arr: The mean with respect to which standard scor... | 634e176c2a6d03510ea83e79db778ae067d0f418 | 579,874 |
import zipfile
def unzipfile(zip_file_path: str, unzipped_dir_path: str) -> bool:
"""
unzip file
:param zip_file_path: path to zipfile
:param unzipped_dir_path: directory path to unzip
:return: bool, if success
"""
z = zipfile.ZipFile(zip_file_path, 'r')
# for file in z.namelist():
... | 4fbafaaefca06b640837bef4ddb3aa07a732ece7 | 579,880 |
def has_rule_for_os(os_dict, os_name, os_version):
"""Return True if os dict has a rule for os name/version."""
if 'any_os' in os_dict:
return True
if os_name in os_dict:
version_dict = os_dict[os_name]
return os_version in version_dict or 'any_version' in version_dict | 80625118b11ce4b1689895679ddf1f8529a22f2e | 579,882 |
def highestPerfectSquare(n):
"""
Function which returns the highest perfect square less than or equal to its parameter.
Parameters:
n (int or float); the number for which the highest perfect square below it is to calculated.
Returns:
ans(int); the highest perfect square less than o... | f42ce19b1be49fc5930a1b89315ba2c9b007c6d2 | 579,885 |
def wants_metadata(request):
"""
Determine if a client request wants metadata to be included in the response.
This method checks to see if an incoming request has an Accept header with
the 'metadata=true' qualified attached to the MIME-type.
:param request: HTTPServerRequest or equivalent from cli... | b6ee44ff4ff07ee3a5bdd881e5bb1ec62ef95481 | 579,889 |
from typing import List
from typing import Tuple
def split_stack(stack: List, num_removed: int) -> Tuple[List, List]:
"""Splits a list into two sub-lists.
Args:
stack: A List to be split
num_removed: An int representing how many items to remove from the end.
Returns:
A tuple cont... | 7b348561dd565e2c85f61b497e519eeb1354971e | 579,894 |
import torch
def load_weights(checkpoint_path: str):
"""
Load weights from a checkpoint file.
:param checkpoint_path:
A string representing the absolute/relative path to the checkpoint file.
"""
return torch.load(checkpoint_path, map_location='cpu') | 1d65d949648efc91c5afd6b80efca3551c821027 | 579,897 |
def qtName(name: str, lower: bool = True) -> str:
"""Transform a name into the Qt naming style (camelCase).
"""
first, rest = name.split('_', maxsplit=1)
if lower and not first[0].islower():
first = first[0].lower() + first[1:]
elif not lower and first[0].islower():
first = first[0].... | 2d5057614dc75e8cb77a5eab86246b6bbb285fdd | 579,898 |
from io import StringIO
import csv
def csv_string_as_dicts(csv_string):
"""Parse a CSV string into a list of dicts
Args:
csv_string (str): CSV string data
Returns:
list: A list of dicts, one per CSV row
"""
with StringIO(csv_string) as fin:
reader = csv.DictReader(fin)
... | 62c282eff119f8635795c8236d4628b7c1af599b | 579,899 |
def get_config_params(stage, seq=1):
"""Maps config keys to stage arguments as a dictionary.
:param dict stage: The stage to map.
:param int seq: The stage sequence.
:rtype: dict
:return: The mapped keyword arguments.
"""
return dict(
sequence=seq,
runner_type=stage.get('run... | dba6b520215f04e54855ed7f93cd1f2a0fe56ea2 | 579,906 |
from typing import Union
from pathlib import Path
def expand_path(path: Union[Path, str]) -> Path:
"""
Take a path or a string, expand '~' and convert to an absolute path
"""
return Path(path).expanduser().absolute() | bcc8c023f62f6eb103fa47576ab35ebbf448f07f | 579,909 |
import struct
import socket
def ipToInt(ip):
"""Transform a string IP into an integer (long)
Keyword arguments:
ip -- (string) IP as a string ("xxx.xxx.xxx.xxx")
return: (long) IP number
"""
return struct.unpack("!L", socket.inet_aton(ip))[0] | f27a8e3e4f23aacf68a38f804f2305a4dc620036 | 579,910 |
def filter_table(table, otu_subset=None, sample_subset=None):
"""Filters a table given otu and sample ids
Parameters
----------
table : biom.Table
Table to be filtered
otu_subset : Optional[list[str]]
List of otu's to keep in table. If None, keep all otu's.
sample_subset : Op... | 0f51a48dd96a82db1293d03ac3a72aa85fb6c8b6 | 579,911 |
def aws_ok(resp):
""" Return true if response status is ok """
if resp['ResponseMetadata']['HTTPStatusCode'] == 200:
return True
return False | e983b74b9188b3673d62392e5140ef885811ea09 | 579,913 |
def promote_empty_dims(ds):
"""Convert empty dimensions to actual coordinates"""
ds = ds.copy()
for di in ds.dims:
if di not in ds.coords:
ds.coords[di] = ds[di]
return ds | b1c722b0f01c8325f06f336d9bb0f112a1557352 | 579,918 |
import random
def apply_tournament_selection(individuals, tot_rounds: int):
"""Tournament selection based on dominance (D) between two individuals, if
the two individuals do not interdominate the selection is made
based on crowding distance (CD). The *individuals* sequence length has to
be a multiple ... | c3c234bda7c71fea3d5a2c3bf1a35059597d8567 | 579,919 |
def _find_missing_keys(specs, required_keys):
"""
Checks whether all keys in a dictionary exist and have the right values.
Args:
specs(dict): The dictionary to check.
required_keys(list): All required keys.
Returns:
A list of missing keys.
"""
missing_keys = [item for ... | e388717067bb49cea988eb074335947573aca8ff | 579,922 |
def invert_number(number: int) -> int:
"""
number: 7 = 0b111 -> 0b000 = 0
number: 111 = 0b1101111 -> 0b0010000 = 16
number: 10000000000 = 0b1001010100000010111110010000000000 -> 0b0110101011111101000001101111111111 = 7179869183
:param number
:return: invert number
"""
return int(''.joi... | 3b55293ca4564b31845bffa749a9e404bb5242b5 | 579,927 |
import torch
def absolute(field, weights=None):
"""Precision matrix for the Absolute energy
Parameters
----------
field : (..., *spatial) tensor
weights : (..., *spatial) tensor, optional
Returns
-------
field : tensor
"""
if weights is not None:
backend = dict(dtype... | 66f6e02e5eea138d059be1d833061d02f57db33c | 579,929 |
def commaSplitNum(num: str) -> str:
"""Insert commas into every third position in a string.
For example: "3" -> "3", "30000" -> "30,000", and "561928301" -> "561,928,301"
:param str num: string to insert commas into. probably just containing digits
:return: num, but split with commas at every third dig... | c6d3fde49662b1a83bc07655c9a3e914b27a60ff | 579,931 |
def pull_container_needed(ctx):
"""Returns whether or not pulling a container is needed.
Args:
ctx: the Bazel context object.
Returns:
Returns true if its necesary to pull a container to generate configs.
"""
# We don't pull a container if we have found a config_version to use
#... | 14594ec516b76a22d2f1fa35ba1e0be57d577deb | 579,932 |
def get_xml_node_namespace_tag_target(etree, target_namespaces=None):
""" Get the namespace, tag, and target of an XML node
Args:
etree (:obj:`etree._Element`): element tree
target_namespaces (:obj:`dict`, optional): dictionary that maps the prefixes of namespaces to their URIs
Returns:
... | 6563959f22dcac56244825f6ec75892e5de3f3e1 | 579,937 |
import pickle
def read_results(filename):
"""Load a dictionary containing best model, performance, and ymap."""
with open(filename, 'rb') as hdl:
results = pickle.load(hdl)
return(results) | adfe95c6a364ff784195530c0a0219bf7c420669 | 579,945 |
import signal
def get_wakeup_fd() -> int:
"""
Returns the file descriptor stored by :func:`~signal.set_wakeup_fd`.
Currently, the only way to determine the fd is
is to use :func:`~signal.set_wakeup_fd` using a dummy value,
because it returns the previous fd,
and then once more to restore it.
... | 0f44b929ffaaf0692444092b632363d625bb6734 | 579,949 |
def deserializer(key, value, flags):
""" Converts a value from memcached to one that pymemcache will return.
Args:
key: A bytestring specifying the encoded memcached key.
value: A bytestring specifying the value.
flags: An int specifying the flags.
Returns:
A tuple in the form of (value: bytestri... | a37fe59ce650ad8cbe8e1ba7b8cfb1619dbed219 | 579,953 |
def segment_tree_range_sum_query (tree, l, r):
"""The function tells the sum of elements in a given range using the segment tree in O(log(n))
input : segment tree, array starting and ending index of range
returns the sum of elements of array in that range"""
m = len(tree)
l,r = l+m//2, r+m/... | 889fbc79cb21b7674c0b06a5b00f6ce2730d0d0b | 579,954 |
def convert_list_to_matrix(in_matrix, n_rows, n_columns):
"""converts a list into a list of lists (a matrix like) with n_rows and n_columns."""
return [in_matrix[j:j + n_rows] for j in range(0, n_rows * n_columns, n_rows)] | e8f5cbac07a154e5283efb965f1e63122db01ada | 579,958 |
def is_package_cs(csname):
"""
If 'csname' is a package C-state name, returns 'True'. Returns 'False' otherwise (even if
'csname' is not a valid C-state name).
"""
return csname.startswith("PC") and len(csname) > 2 | 983dd2c8a29505558619971088445bd70023a73a | 579,959 |
import copy
def transform_point(p, transform):
""" The function to transform a 3D point using a transformation matrix
Args:
p (list): the point to transform; [X, Y, Z, ...]
transform (numpy array): 4x4 transformation matrix
Returns:
(list): the transformed po... | 551530ac2bcefe2cf46acc5e224a051ba2b78182 | 579,961 |
def _minor(x, i, j):
"""The minor matrix of x
:param i: the column to eliminate
:param j: the row to eliminate
:returns: x without column i and row j
"""
return [[x[n][m] for m in range(len(x[0])) if m != j]
for n in range(len(x)) if n != i] | 8168b56914109ff52f6e5572dfa533db462d5d0c | 579,963 |
def canStringBeParsedAsInt(str):
"""
return True if int(str) would produce a value rather than throwing an error,
else return False
"""
try:
int(str)
return True
except ValueError:
return False | 70d7850de7739814e234be197e7e188ea09363c7 | 579,967 |
def flatten(captions_list):
""" Flatten all the captions into a single list """
caption_list = [
caption for captions in captions_list for caption in captions
]
return caption_list | 345f14a406646f286a8f38e91c42e1aefb796861 | 579,968 |
import requests
import json
def call_gitlab_events_api(api_url: str, api_key: str) -> list:
""" Call a gitlab API and return its response as list.
:params api_url: The full url for the api request.
:params api_key: The key for the API.
:returns: The API response.
"""
_header = {"PRIVAT... | 88358f5877ebd9a317dfeb4aacad8af1c1e2bd44 | 579,969 |
from typing import List
from typing import Tuple
def percent_edges_in_other_edges(edge_list: List[Tuple[str, str]], edge_list2: List[Tuple[str, str]]) -> float:
"""Calculate what proportion of the first list of edges can be found in the second list.
checks edges in both node orders to account for directed ed... | 0d7d7c80c1d560034ec59a2575d88563e8d250d9 | 579,971 |
import math
def permutation(a, b):
"""
Calculate the number of permutations from a choose b
"""
if a > b:
return int(math.factorial(a) / math.factorial(a - b))
raise Exception("a should be less than b") | 14ce881b5f8e7d322d3f507154e70ea51375813b | 579,975 |
from typing import Dict
from typing import Any
def pick(base: Dict[str, Any], *keys: str) -> Dict[str, Any]:
"""
Helper to select keys from an arbitrary dictionnary of keyword
arguments when key is defined and not null.
"""
return {key: base[key] for key in keys if key in base and base[key] is no... | 39da8fdffad160a503f900e60db1f6560a5fdcd5 | 579,982 |
import requests
from bs4 import BeautifulSoup
def soup(url):
"""Return a soup object of the page's content."""
try:
response = requests.get(url)
response.raise_for_status()
return BeautifulSoup(response.text, 'html.parser')
except requests.HTTPError:
return None | 543b3713f856e62cb17423f6aa9512a7dad97960 | 579,984 |
from typing import List
def parse_extensions(files: str) -> List[str]:
"""
Parse extensions from option and convert them into a list
:param files
"""
return files.split(",") | aae5d64ac960d2b48aca48b9b65d04788b2d93f9 | 579,989 |
def pt2pt(pt=1):
"""Dummy conversion."""
return pt | 62972347c05817bb4b02855982cb12000fb63d73 | 579,990 |
def pictures(listing):
"""Score by number of images."""
nimages = len(listing.images)
if nimages == 0:
return -500
elif nimages == 1:
return -200
elif nimages < 4:
return 0
else:
return 200 | c9a9a2cf089a1f2a9b0e00c104c5ccdb46e79260 | 579,991 |
def NumberFromDigits(*args):
"""Given an array of Int digits, returns an Int as if they were read left-to-right"""
num = 0
for arg in args:
num = (10 * num) + arg
return num | 27afdb11b7a2faa9fd012f74ae086a678327d4e9 | 579,992 |
import gzip
def get_ascii_header_variables(filename, gz=False):
"""return the header and variables of an ascii file"""
if gz:
with gzip.open(filename, 'rt') as fname:
header = fname.readline().split()
fname.readline()
variables = fname.readline().split()
else:
... | e7cd61a0c71ae2862430da3e11092c0904e5bece | 579,993 |
def get_open_edges(nut_1, index_1, nut_2, index_2):
"""Suppose that nut_1 and nut_2 match up at index_1 and index_2: return open edges on left and right.
Args:
nut_1: Nut
index_1: int
nut_2: Nut
index_2: int
Returns:
tuple(tuple(int, int), tuple(int, int)) Left edge... | de3a49e345c8f50753bc0b425ba75ec9bbdefd04 | 579,998 |
def generate_kml_placemark_from_point(point_latlon, color=None, info=None):
""" Generates a placemark representation for a point [lat, lon]
"""
if color is None:
color = 'ff0000ff'
lat = point_latlon[0]
lon = point_latlon[1]
d = 0.0008
kml_str = '<Placemark>'
kml_str += '<name>Po... | ed8e31c3053ca0c730c0a0e43137a45946f7e51d | 580,001 |
from typing import Mapping
def replace_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with renamed keys including keys only found in key_map."""
return {key_map[k]: v for k, v in record.items() if k in key_map} | 9680f12d7625e5838d6a1834ca60c4147e13c600 | 580,002 |
def get_recovery_image_len(xml, sig_len):
"""
Calculate the recovery image length from the processed recovery image data. The total includes
the headers, image(s), and signature.
:param xml: The processed recovery image data
:param sig_len: The recovery image signature length
:return the tota... | 4cff9c8cc11c63908ed5b9937fdac0ee7f632cb7 | 580,004 |
from math import radians,cos,sin,asin,sqrt
def haversine(lon1,lat1,lon2,lat2):
"""
Returns the great circle distance between two points
on a spherical Earth.
Parameters
----------
lon1 : float
Longitude (degrees) of first point.
lat1 : float
Latitude (degrees) of first po... | 4d5f253dd2075dd7400f290df3d578ef9b5d4fa5 | 580,009 |
def validate_str(prompt_text="Please enter a string: ",err_text="Please make sure that you entered a STRING"):
"""
Prompts, returns and validates that the input is a string, if not, it warns
Takes in 2 arguments: prompt_text and error_text - the text that user wants to be the prompt
and the text that d... | 09b0fdccb2397c7d21976ef07e5358d3e4753c0a | 580,012 |
import json
def load_ontology(dataset, ontology_file=None):
"""
Read ontology file for event to argument mapping.
"""
ontology_dict = {}
if not ontology_file: # use the default file path
if not dataset:
raise ValueError
with open("event_role_{}.json".format(dataset), "... | bc3c0e77e06d880bec9c16f862134d69ee28fa7f | 580,013 |
def divide_list_by(ls, n):
"""
Divide all elements of list by n.
"""
return [e / n for e in ls] | 094d4c9cd005929e0fb7b8bc229453cabf784007 | 580,014 |
import logging
import collections
def get_full_tax(idx):
"""
Getting full taxonomy for all genes.
return: {(tax_lev1, tax_lev2, ...) : genome_ID : genome_len}
"""
logging.info('Compiling the taxonomy for all genomes...')
tax_idx = collections.defaultdict(dict)
for cluster_id,v in idx.items... | ca50221a6cb3b486ea402cf13ca3542e23be606a | 580,017 |
def get_vcf_column_headers(line, sample_ids, sample_indices):
"""Get VCF column headers, including only relevant samples
Parameters
----------
line : str
A line from a vcf file (e.g. from an open file descriptor)
sample_ids : list, tuple
All sample IDs in the input VCF file
... | 496616202b820224c54b91111678c54554bca771 | 580,019 |
def get_dv_switch_manager(vim):
"""Get reference of DistributedVirtualSwitchManager."""
return vim.service_content.dvSwitchManager | efe1c5f63512a50f3c1de9d139a996fc6cc6d9fc | 580,020 |
def normalization_factors(self):
"""Compute normalization factors for a DataFrame."""
norm_factors = self.sum() / self.sum().mean()
return norm_factors | 83dd4a68e87ac35c8e360c79d7d91783626aaa85 | 580,021 |
from typing import Any
def convert(value: str, type_: type) -> Any:
"""Convert string `value` to type `type_`."""
if type_ is bool:
return value.lower() in ("1", "t", "true", "y", "yes")
return type_(value) | 2ce7fbe77c29536a9ce727d40dde28e9e210c088 | 580,023 |
import torch
def color_normalization(images, mean, stddev):
"""
Perform color nomration on the given images.
Args:
images (tensor): images to perform color normalization. Dimension is
`num frames` x `channel` x `height` x `width`.
mean (list): mean values for normalization.
... | f6482c3ed3d6f44a63ad407783983bf81f5b8995 | 580,024 |
import requests
def get_sgg_phases(tournaments):
"""return list of json objects containing
phase data for each given smash.gg tournament URL
by querying the sgg API for each phase
input
---------
tournaments: list of json blobs (requests.get().json)
for smashgg tournament & event:
... | a1f1d6a0f952610ce6aedbd9d2b0e8214d8bb16c | 580,025 |
def restrict_to_vocab(txt, vocab):
"""
Remove characters that do not belong the a vocabulary.
"""
txt = ''.join(char for char in txt if char in vocab)
return txt | 6d0eb6b6f4243139bdcc2ef0af4a03a4c946907f | 580,030 |
def add_2_numbers(a, b):
""" Function to add to numbers
:param a: First number
:type a: int, float
:param b: Second number
:type b: int, float
:return: The sum of the two numbers
:rtype: int, float
"""
return a + b | 67ebdfa0b6c72dae5856b4862f27ff77249e4505 | 580,032 |
def get_beta_variance(a, b):
"""Compute variance of beta distribution based on shape parameters `a` and `b`."""
return a*b/(a+b)**2/(a+b+1) | 527067dd0b0dbb4e331eab9030a252ecb0be835d | 580,037 |
def runner_kwargs(options):
"""Given the command line options, return the arguments to
:py:class:`EMRJobRunner`
"""
kwargs = options.__dict__.copy()
for unused_arg in ('quiet', 'verbose', 'list_relevant', 'list_all',
'cat_relevant', 'cat_all', 'get_counters', 'step_num',
... | 9a864c0e9d71284a2ab9fe89a6ffc7662064806d | 580,040 |
def rl(infile):
"""
Lazy function to read a line from a while and remove redundant whitespaces.
Args:
infile (str): Path to input file.
Returns:
str: Stripped line
"""
return infile.readline().strip() | f8c664b046fea39b9c3e9b3513b4467ce6dcc936 | 580,042 |
def json_request(method, url, client, headers={}, data=None):
"""Executes json requests.
:method: 'GET', 'POST', 'PUT' or 'DELETE' (case sensitive)
:url: a string object (valid as url)
:client: flask.Flask.test_client
:headers: Optional headers.
As default uses Content-Type: application/jso... | 10075772d5db6d3622807603e68618d2409cf1eb | 580,044 |
def get_3d_nopersp(minspan_len, traj_2d_left, traj_2d_top, cam_left, cam_top):
"""Find the 3D trajectory of the ball by orthographic projection nor camera exact positions
:param minspan_len: number of time points
:param traj_2d_left: trajectory found by the left camera
:param traj_2d_top: trajectory fo... | b181fbc9d4cfe4e84cc4e91ce991ef2155e5b023 | 580,049 |
def sanitize_plugin_class_name(plugin_name: str, config: bool = False) -> str:
"""
Converts a non-standard plugin package name into its respective class name.
:param: plugin_name: String a plugins name
:param: config: Boolean true if it should convert into a config name instead of a class name. For give... | a39a6aaef7e16fd8b76defb7e4370b96821bbba7 | 580,050 |
def get_feature_types(df):
"""
Gets all features in the dataframe grouped by whether they are numerical or non-numerical (e.g. string).
:param df: (pandas.DataFrame) the dataframe
:return: a dict containing the categorical and numerical features
"""
cn_features = {
'numerical': [f_name f... | a1e12af02b5e777141d017400f9ab96c69cb835c | 580,053 |
def matching_tag(tag):
"""Returns matching tag to the one given
Args:
tag (str): Given tag
Returns:
str: Matching tag to the one given
"""
if tag[1] == '/':
return "<" + tag[2:]
return "</" + tag[1:] | 95fb73be1bc3cb16eed01a4d57c39ca4c90cce43 | 580,054 |
import math
def hour_angle_radians(lmst, ra):
"""Returns hour angle radians from local time and right ascention."""
return ((lmst - ra + math.pi) % (2 * math.pi)) - math.pi | 1d32c0e6a8dd7ab5c790e557c73d551ef8a24cc2 | 580,057 |
import re
def clean_text(text):
"""Remove HTML links and special characters from text.
Parameters
----------
text : str
The text to clean.
Returns
-------
str
The cleaned text.
"""
regex = r'(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)'
cleaned_text = re.s... | 0516dedfb0884b1ad732682c107d61bac1bd5981 | 580,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.