content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def squares(g):
"""
Count the number of squares for each node
Parameters
----------
g: igraph Graph object
The input graph.
Returns
-------
List with N entries (N is number of nodes) that give the number of squares a node is part of.
"""
cliques = g.cliques(min=4, max=4)... | 6247a00554b2cab703b71e2015babb2dbf13838d | 594,941 |
import torch
def gaussian_log_prob(x: torch.Tensor, gm: dict) -> torch.Tensor:
"""calculate the Gaussian log-likelihood of data x
Args:
x: tensor of size (N, 1, d)
gm: mean and cov of sizes (K, d) and (K, d, d)
Return: N-by-K matrix of log-likelihood
"""
if x.dim() == 2:
... | a8635474f21c5d6651e6870bc06f18f8a308f21c | 594,943 |
import random
def random_string(prefix='rand', n=8, suffix=''):
"""Return a string containing random digits
:param prefix: the exact text to start the string. Defaults to "rand"
:param n: the number of random digits to generate
:param suffix: the exact text to end the string
"""
digits = "".j... | c4beb1f275297f55608ef6249865c0eed282a10b | 594,944 |
def _get_snapshot_id_and_previous_session_id(session_spec, data_store):
"""Retrieve the snapshot ID and previous session ID in a tuple.
Args:
session_spec: session_pb2.SessionSpec proto containing info about current
session to draw the previous session and snapshot from.
data_store: data_store.DataSt... | 85493e3fa6ab1cf24d289d6d70372fb79cd218b6 | 594,947 |
import yaml
def load_yaml(config_file):
"""Load game config from YAML file."""
with open(config_file, 'rb') as fp:
config = yaml.load(fp, Loader=yaml.FullLoader)
return config | d1a3a5f60bbc41aa302d1a40107baca83306d7e6 | 594,948 |
def sort_mem(member):
"""Function key for sorting PW_Member objects."""
return member.end - member.start | ada179301a5ca1fc566b914a3a1dd6df85ac4849 | 594,953 |
import typing_extensions
def _get_from_anno_type(anno: typing_extensions.Annotated):
"""
Handles dealing with Annotated annotations, getting their (first) type annotation.
This allows correct type hinting with, say, Converters,
for example.
"""
# this is treated how it usually is during runtim... | 4c5d67595c5912c72ace5c2e04ccb531e209d9f0 | 594,959 |
import torch
def gelu_fused(x):
"""
Approximate GELU activation, same as in Google BERT and OpenAI GPT (as of Dec 2021)
the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
"""
return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))) | d83e22f34b236733062db310084402fc7074d7a1 | 594,960 |
def swap(L, i, j):
"""Swaps values at indices i and j in list L."""
L[i], L[j] = L[j], L[i]
return L | 81191753f24b65830f6ab262bb02d10c47368f89 | 594,969 |
import re
def _get_authenticity_token(session):
""" Parse the page to get the authenticity token. """
response = session.get('https://www.recurse.com/login')
matches = re.findall('<meta\s*?name="(.*?)"\s*content="(.*)".*/>', response.text)
for name, content in matches:
if name == 'csrf-token... | dc1c80981699240e7aff426bc2b8ad8d2e7cf8a9 | 594,973 |
import re
def server2dirname(server):
"""Convert a server URL to a directory name."""
urld = re.sub(r"https*://", "", server)
urld = re.sub(r'/', '_', urld)
return urld | faeff7049485ccc0b1b418ecdf930f3f023b3e8f | 594,977 |
import math
def round_repeats(repeats: int, depth_coefficient: float) -> int:
"""Returns rounded number of repeats based on depth coefficient."""
return int(math.ceil(depth_coefficient * repeats)) | 54a8b9a12f5c845d5cc26a3ed868e0872620968e | 594,980 |
import unicodedata
def has_diacritic(*diacritics):
"""
Given a collection of Unicode diacritics, return a function that takes a
string and returns a boolean indicating if any of those diacritics exist
in the string.
"""
def _(text):
for ch in unicodedata.normalize("NFD", text):
... | 7d8b1b7a31aee1d5b0b4405b89dd15a637d88287 | 594,981 |
import six
def decoder_template(job_name, model, image, logdir, decoder_type,
decoder_gpus):
"""Constructs the base yaml config for the decoder."""
name = six.ensure_str(job_name) + ".decoder"
container_name = name.replace(".", "-")
job = "decoder_" + six.ensure_str(decoder_type)
return... | 5773d9220b1f6af63bc9500327b2ededfb6ef7e7 | 594,982 |
import math
def compute_shannon(data):
"""
Calculate Shannon entropy value for a given byte array.
Keyword arguments:
data -- data bytes
"""
entropy = 0
for x in range(256):
it = float(data.count(x))/len(data)
if it > 0:
entropy += - it * math.log(it, 2)
r... | 3be2cdd3a3f7bea43cdcd4175b3d1717859379af | 594,984 |
from typing import Callable
from typing import Set
import click
def list_clusters_command_factory(
existing_cluster_ids_func: Callable[[], Set[str]],
) -> Callable[[None], None]:
"""
Return a Click command for listing clusters.
Args:
existing_cluster_ids_func: A function which returns existin... | e409cc4fdb01855df53a3893d9130e1f23609f75 | 594,989 |
def pytest_report_teststatus(report):
"""Adapted from https://pytest.org/latest/_modules/_pytest/skipping.html
"""
if report.outcome == "rerun":
return "rerun", "R", ("RERUN", {"yellow": True}) | 08032629a836c0cb2139567341566ade635871ca | 594,990 |
def dfs_recursive(self, start=0):
"""
Recursive depth first traversal starting from vertex `start`.
"""
visited = [False] * self.n
order = [start]
visited[start] = True
def dfs_util(v):
for i in self.adj_list[v]:
if not visited[i]:
order.append(i)
... | f2d1f1f4a87cd432732c864285deb2fd7fc40cb8 | 594,998 |
def get_height(width, aspect_ratio):
""" return height with respect to given aspect ratio """
return width//aspect_ratio | 33c434d2621e4796b95aa7c739f16dbff26d2688 | 595,000 |
def get_token(http_request):
"""Get token from request object
Args:
http_request (HTTPRequest): Http request object
Returns:
token (string): Token string
"""
token = http_request.META.get('HTTP_AUTHORIZATION')
if not token:
return {'message': 'No token provided in reque... | c84d2916d4dce79c31e3fd72183ff9e988fdb987 | 595,002 |
def configure(context=None):
"""Make from plain python method benchmark.
It sets 2 attributes to function:
is_scenario = True # that is used during discovering
func.context = context # default context for benchmark
:param context: Default benchmark context
"""
def wrapper(func)... | 6daa7b79a6b25f9697679ac0d914ac19065bbabf | 595,004 |
def find(lst, key, value):
"""Find a dictionary entry from a list of dicts where the
key identified by 'key' has the desired value 'value'."""
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return None | aa8e57dea77e0ea18ec94ce406c74f3b52d58a1a | 595,007 |
def linear_search(array: list):
"""Find and return the greatest value with a linear search"""
maxValue = array[0]
for number in array[1:]:
if number > maxValue:
maxValue = number
return maxValue | aeec1944ab8425d0bef041833196b1aac75909f9 | 595,009 |
from unittest.mock import call
def get(path, body=None, mime=None, tags=[], custom_headers={}, **kw):
"""
Convenience method for fluidinfo.call('GET', ...)
"""
return call('GET', path, body, mime, tags, custom_headers, **kw) | 455e7d5dd2c790aa9a9e424d0caf5098e6954880 | 595,010 |
def load_events(file_path):
"""
Load events saved to a .txt file
parameters
-----------
:param file_path: str
Path to .txt file
:return: dictionary
Dictionary of event words- {incrementing ID: [event words]}
"""
event_words = dict()
try:
with open(file_path, ... | c1272ccb00ffd1c4926e8dcdf826562075873a0c | 595,015 |
def calculate_initial_differences(delta, a, b, c, d):
"""
Calculate initial differences vector as
[ d ]
[ aδ³ + bδ² + cδ]
[ 6aδ³ + 2bδ² ]
[ 6aδ³ ]
"""
delta_2 = delta ** 2
delta_3 = delta ** 3
return [
d,
a * delta_3 + b ... | b1baeb7578196fb5a071652352f54ad1371e6b14 | 595,018 |
def merge_sort(nums):
"""A comparison based sorting algorithm."""
the_length = len(nums)
left_list = []
right_list = []
final_list = []
if the_length == 1:
return nums
i = 0
for item in nums:
if i < round(the_length / 2):
left_list.append(item)
i +... | 32e2a07dc8a1c9f46893500bc4955b5f7ea2f4b8 | 595,024 |
import json
import string
def is_slate_value_empty(data):
"""
Given a slate value serialized to JSON, return true if it's empty
"""
try:
value = json.loads(data)
except json.JSONDecodeError:
# if it's not JSON, it's plaintext
return data == "" or data.isspace()
doc_text... | e862ac034deeef1220aa8d348ce251a61ccb2654 | 595,025 |
def identity(x):
"""Canonical identity function. The purpose of defining identity()
here is to allow it to serve as a default value and to be
able to check whether a function parameter has been assigned
another than the default value or not."""
return x | 3b0596c08940f0b41d9a7fd673271507a413d213 | 595,028 |
def left_remove(text, to_remove):
""" Removes a part of a string, if it starts with it.
Similar to str.lstrip, see note below on right_remove
"""
if text.startswith(to_remove):
return text.replace(to_remove, '', 1)
else:
return text | f8b9fa83a78eab45c634e3fcc77e63ad95f3a9cc | 595,029 |
import socket
def is_address_available(host, port):
"""
Test whether a (host, port) pair is free
"""
try:
s = socket.socket()
s.bind((host, port))
s.close()
return True
except:
return False | 431d63f4770e04c204d2fe0a4dd1af7e9bd33283 | 595,031 |
import time
def formatFnameDate(when=None):
"""Given a time in seconds since the epoch, returns a date value suitable
for use as part of a filename, in YYYYMMDD format. Defaults to the
current time."""
if when is None:
when = time.time()
return time.strftime("%Y%m%d", time.localtime... | d96d7b5e79dee5b4ec8946eeb73f87645414528e | 595,032 |
import random
import string
def randomstring(N):
""" Generate a random string of length N """
return "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(N)
) | 914c21e180c4921ab29b48b704e36f008a213e81 | 595,035 |
def parse_line(line):
"""Parse instruction and return it as tuple of operator and value"""
op, val = line.split()
val = int(val)
return op, val | e4963becf24beb7b998e969f7301d06744dd107e | 595,036 |
import torch
def gaussian_filter(distances, offsets, widths, centered=False):
"""
Filtered interatomic distance values using Gaussian functions.
B : Batch size
At : Total number of atoms in the batch
Nbr : Total number of neighbors of each atom
G : Filtered features
Parameters
... | 36ce8cd77628ff3649a0dafe3961e688a77671f9 | 595,037 |
from typing import Any
def is_array(entry: Any) -> bool:
"""
Checks if entry is an array
"""
return isinstance(entry, dict) \
and 'type' in entry \
and entry['type'] == 'array' | 0f86e70a38e7e9292873b9e32c19c66efa3211b2 | 595,040 |
import hmac
def hmacsha256(key, msg):
"""Generate an HMAC-SHA-256 message authentication code."""
return hmac.new(key, msg, 'sha256').digest() | e876b484dc7d77eb9744b3e147ad718e57c83f51 | 595,042 |
def get_overlay_name(segmentation_name):
"""Get the appropriate name for an overlay."""
splitted = segmentation_name.split('.')
splitted[-2] = splitted[-2] + '-overlay'
output_path = '.'.join(splitted)
return output_path | 9b53358234252a4fa9ecb1a7538d930b8b627a8c | 595,045 |
from typing import List
from typing import Dict
def _get_segmentation(polygon: List[Dict], width: int, height: int) -> List[int]:
"""Convert RedBrick polygon to coco segmentation field."""
segment = []
for point in polygon:
segment += [
int(point["xnorm"] * width),
int(poin... | 03d4f262d479768456b798e53a23842c0f8702ed | 595,048 |
def as_sorted_mapping_seq(licenses):
"""
Given a `licenses` iterator of to_dict()'able objects, return a sorted list
of these.
"""
return sorted((l.to_dict() for l in licenses), key=lambda x: tuple(x.items())) | f413492f9fd352c270dfde263f0a03c705dc56b8 | 595,051 |
def get_file_lines(name):
"""
Get the number of lines in a file
Parameters
----------
str name: filepath and name of file
"""
lines = 0
with open(name, "r") as stream:
lines = len(stream.readlines())
return lines | 56e1aaa889a2d1fab81c1de261c18c4e94588e9c | 595,053 |
def floyds_cycle_detection(head):
"""
My Python implementation of Floyd's cycle detection algorithm
Checks if a cycle exists in a linked list, and if it does, returns the starting node of the cycle.
Time complexity: O(μ+λ), μ = Starting index of cycle, λ = Length of cycle
Space complexity: O(1)
... | 61519ad478be8a0091f2b03eabe0b7b11d46c815 | 595,054 |
def get_dashboard_names(accessor):
"""
given an instance of an accessor, get the configured dashboard names
"""
dash_documents = accessor.get_all_documents_from_collection("dashboard")
dash_names = [dash["title"] for dash in dash_documents]
return dash_names | c8c13d23320d82162ffab1471b22568ab70cb41c | 595,057 |
def to_json(request):
"""Takes DmailRequest and turns it into a json object (dict)"""
return {
'whoami': request.whoami,
'parameter': request.parameter,
'data': request.data,
} | 92d79d554ff10646a961d85e91caba43a754c01c | 595,067 |
def label_format_hms(deg, pos):
"""
Format decimal->HH:MM:SS. Called by the label formatter.
"""
hrs = deg/15.0
angle = abs(hrs)
sign=1
if angle!=0: sign = angle/hrs
# Calcuate the hrsrees, min and sec
dd = int(angle)
rmndr = 60.0*(angle - dd)
mm = int(rmndr)
ss =... | 72dc252a6b885739b37de601f492c8f12eb079f3 | 595,070 |
def bare_msg_type(msg_type):
"""
Compute the bare data type, e.g. for arrays, get the underlying array item type
:param msg_type: ROS msg type (e.g. 'std_msgs/String'), ``str``
:returns: base type, ``str``
"""
if msg_type is None:
return None
if '[' in msg_type:
return m... | bde402cd3afe4fdb60203f9118b730289010f077 | 595,071 |
def collapse(pah, **m):
"""Returns the marginal for the dimensions supplied.
First we slice the matrix where we want
Then we marginalize over the dimensions we want
:param pah: the histogram
:param m: each keyword argument must match a dimension
if the value of the argument is None, then we keep... | 0e447240dcf58e674f4048a3bb80bfa89d520863 | 595,073 |
def class_exists_in_fink_taxonomy_hierarchy(classification: str, branch: list):
"""
Recursively look for a given fink class in a fink's taxonomy hierarchy
Arguments
----------
classification : str
Classification to look for
branch : list
Branch of a taxonomy hier... | cc6194a867e2d6ed5a8edb837739b0de1a5dc124 | 595,074 |
def _to_result(arr, ops, wrap=True, skip=None):
"""
把公式格式化成字符串
:param arr: 二维数组,每一行代表公式的数字,例如 [a, b]
:param ops: 二维数组,每一行代表公式的操作,例如 [+, =]
:param wrap: 自动加括号,例如 a + (-b)
:return: str list,例如 ['a1 + b1 = ', 'a2 + b2 = ']
"""
if skip is None:
skip = {}
res = []
for row, op ... | 0160565bfcc86bb60e45ec03972bdfdbc1a71775 | 595,079 |
def dopplerShift(wvl, flux, v):
"""Doppler shift a given spectrum.
Does not interpolate to a new wavelength vector, but does shift it.
"""
# Shifted wavelength axis
wlprime = wvl * (1.0 + v / 299792.458)
return flux, wlprime | c396f949abd16179716cfda3516045616ae8167c | 595,080 |
def nice_time(delta):
"""
Gets time delta in seconds and returns a pretty string
representing it in the format of 1w2d9h16m44s
"""
weeks = 0
days = 0
hours = 0
minutes = 0
seconds = 0
seconds_in_minute = 60
seconds_in_hour = 60 * seconds_in_minute
seconds_in_day = 24 * ... | 2048b7f9db2e4863e8a6f8d3a04c638e5a990b7b | 595,081 |
def is_supplementary_code_point(body: str, location: int) -> bool:
"""
Check whether the current location is a supplementary code point.
The GraphQL specification defines source text as a sequence of unicode scalar
values (which Unicode defines to exclude surrogate code points).
"""
try:
... | da3c3d41515f21526599d349e880f3efb8161bf4 | 595,084 |
def powerlaw(x, scale, power, return_components=False):
"""
Defines a power law
Returns
-------
scale * x**power
"""
return scale*x**power | 04f047bbcdc34a87e788bd7d9727d9cde32d67c7 | 595,090 |
def format_node_address(*, node):
"""
Format address for node
"""
ip_address = node.ip_address
port = f':{node.port}' if node.port else ''
protocol = node.protocol
return f'{protocol}://{ip_address}{port}' | 8140a3580d35c22975c9a33b56d85fd2a4a2c6df | 595,096 |
def synset_to_wordnet_id(syn):
"""Converts synset to WordNet ID.
Args:
syn: A synset.
Returns:
A unique WordNet ID as used in ImageNet.
"""
pos = str(syn.pos())
offset = str(syn.offset())
len_offset = len(offset)
# Pad offset number with leading zeros.
if len_offset... | 5e50569bb6cf92bde1c0333c45ecf8ee54f046d8 | 595,099 |
def get_countersigners(advice_to_countersign):
"""Get a set of user ids representing the users that have already
countersigned the advice supplied by `advice_to_countersign`.
"""
countersigned_by = set()
for user_advice in advice_to_countersign.values():
for advice in user_advice:
... | f67a6f42519790a7042adc536c1a13772679ce65 | 595,106 |
def next_power_of_2(n):
""" Return next power of 2 greater than or equal to n """
n -= 1 # greater than OR EQUAL TO n
shift = 1
while (n + 1) & n: # n+1 is not a power of 2 yet
n |= n >> shift
shift *= 2
return max(4, n + 1) | 9a850e45c701c8f5b830bb383d25c650b17b1f4d | 595,108 |
def bb_intersection_over_union(box_a, box_b):
"""
Find out how much 2 boxes intersect
:param box_a:
:param box_b:
:return: IOU overlap
"""
# determine the (x, y)-coordinates of the intersection rectangle
x_a = max(box_a[0], box_b[0])
y_a = max(box_a[1], box_b[1])
x_b = min(box_... | bd420cb1b991c350e1554e77666dfaff9c0472ef | 595,109 |
def dict_get(d, *args):
"""Get the values corresponding to the given keys in the provided dict."""
return [d[arg] for arg in args] | 0202cbed5cc2b81b1d8b74986630e3c797596837 | 595,111 |
from typing import Iterable
def getSqlQuery(db_table_name: str='movie') -> Iterable[str]:
"""Get the SQL query by table name.
"""
query = ''
if db_table_name == 'movie':
query = f'''
INSERT INTO {db_table_name} (
rg_id,
scraped_timestamp,
... | 658ffd8de7060e291700fc29af886013270ed17a | 595,114 |
def gridify(n, f):
"""
e.g., (1.1243, 0.005) -> 1.120
"""
return round(n / f) * f | 5f4c0192b9093f87deeda6b2253e0229b4431440 | 595,115 |
import json
def get_recipes_from_file(file_input: str) -> dict:
"""Get recipes from file
Attributes:
file_input (str): filepath
Returns:
recipes (dict): collection of recipes for input language
"""
try:
with open(file_input, "r") as file:
recipes = json.loads(... | 9415c214c09cb8ab7f255405f40a549bb6f00ab1 | 595,118 |
import re
import uuid
def extract_uuid(filename):
"""
Given a filename containing a kernel, extract the uuid in
the kernel name.
Parameters
----------
filename : str
The name of the kernel-...-json file with the connection info.
Returns
-------
uuid : str or None
... | eccad7b6eaef3e0f16b531baec6bf701db4a960d | 595,122 |
from typing import Union
def complex_decode(dictionary: dict) -> Union[complex, dict]:
"""Restore a `complex` object from a json dictionary.
Use this as the optional `object_hook` argument to `json.load` or
`json.loads` to restore a `complex` object."""
if tuple(dictionary.keys()) == ('complex', 'rea... | ed66d00c6a77c448fa8b277c0210f159b5a6710e | 595,124 |
def SetupPMLForEnableDisable(Name, Enable = True):
"""Setup PML command for enabling or disabling display of a PyMOL object.
Arguments:
Name (str): Name of a PyMOL object.
Enable (bool): Display status.
Returns:
str: PML command for enabling or disabling display of an object.
... | fa2f2713a2c649aca122d8130c0e4675cccab50a | 595,125 |
def flatten(list_of_lists: list) -> list:
"""Helper function to flat a list out of lists
Args:
list_of_lists (list): [description]
Returns:
list: [description]
"""
flat_list = []
for sublist in list_of_lists:
for item in sublist:
flat_list.append(item)
r... | 755ae2da5edf531378891ea0a5babddcc37278db | 595,126 |
def meanColor(c):
"""Calculate mean of nnz values in array.
Args:
c (array): Array for which to calculate mean.
Returns:
Mean of non zero values in c.
"""
nnz_total = (c > 0).sum()
if nnz_total == 0:
return 0
return c.sum()/nnz_total | 21282fa9a725ef72c3fd1e0663304da7de6819c2 | 595,131 |
def coding_problem_23(matrix, start, end):
"""
You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall.
Each False boolean represents a tile you can walk on. Given this matrix, a start coordinate, and an end coordinate,
return the minimum number... | c9249dc51ad9ff982dcff0e42597c9bba7eda94b | 595,139 |
import re
def svg_needs_png(fname):
"""
Check to see if this SVG needs to be represented as a png
"""
svg = open(fname).read()
# Detect metafile foreign objects. These mess up SVG conversion
return re.search('<v:foreignData .*?v:data="data:metafile', svg) | b5f5e7e59cf3877db029a5ea34be3f9c0ec1d11e | 595,140 |
def _to_int_map(network, find_pair):
"""Given a dictionary of edges {'rowN': 'colM', ...}, and a
function to find the mate node.
Return a dictionary of {N: M, ...}
"""
entityMap = {}
for node in network:
if node.startswith("row") and len(network[node]):
paired_node = find_pai... | d653a90b8b54740215f9e72e98bce9e971e7cbcc | 595,141 |
def is_uncompressed_pk(pk_bytes):
"""
Uncompressed public keys are 65 bytes long and prefixed by '04'.
:return True for valid uncompressed format.
"""
return len(pk_bytes) == 65 and pk_bytes.startswith(b"\x04") | 7a7ef6d62edce74075ed3a28708ecb4de1da50b1 | 595,146 |
def load_model(known_loaders, outname, **kwargs):
"""If `model_type` is given, use it to load an addon model and construct that OW use default
:param known_loaders: Map of baseline functions to load the model, typically a static factory method
:param outname The model name to load
:param kwargs: Anythi... | 5d82e2dd420c8fe985115a72cc48ee0531930846 | 595,148 |
from typing import List
def get_id_str(cadastre_id: List[int]) -> str:
"""Get cadastre ID string from digit list."""
result: str = ''
for i in range(len(cadastre_id)):
if i in [2, 4, 11]:
result += ':'
result += str(cadastre_id[i])
return result | d2ac0f159ce09898e3ceb956ab3bb746c0b77399 | 595,151 |
def opened_image(mocker):
"""Mock opening an image file for reading."""
opened_image = mocker.patch("PIL.Image.open")
opened_image = opened_image.return_value.__enter__.return_value
opened_image.size = (1, 1)
opened_image.mode = "L"
return opened_image | a5db3e13d8c0abcb23deedba3a0cf15fab3055a3 | 595,152 |
def attribute_hash(attribute):
"""
Given an attribute object, generate a hashable value
that can be used for comparison
"""
uid = ""
# When we iterate over attribute properties use sorted
# to get a consistent ordering
for property_name in sorted(attribute.keys()):
property_valu... | f627fb9e3733a24e0b911bdfa04e9635c50c9e5c | 595,153 |
def escape(s, to_escape, escape_with='\\'):
"""Returns ``s`` with characters in ``to_escape`` all prepended with ``escape_with``.
"""
return ''.join((escape_with + c if c in to_escape else c) for c in s) | c2d22b80a65942fa10318e49984fef7cff2e4286 | 595,154 |
def get_location(response):
"""
Returns location of a transaction as returned in the header of a response object.
:param response: response object succeeding a successful post request.
:type response: requests.models.Response
:return: str
"""
resource_location = response.headers('location')
... | 82bc9fb272d47fd8e9d245cb15d4581455c690a8 | 595,157 |
def get_side_idi(sipper, side):
"""
Returns the interdrink intervals for the left or right bottle of a Sipper
Parameters
----------
sipper : Sipper
sipper data loaded into the Sipper class
side : str ('left' or 'right')
side to return the interdrink intervals for
Returns
... | 62dd916b7ea6bab4ec8a115537ec6aaff83bf00e | 595,158 |
def search_lhn(city):
"""
Search for existing LHN within city. Returns True, if LHN is found.
Parameters
----------
city : object
City object of pyCity_calc
Returns
-------
has_lhn : bool
Defines, if LHN system exists in city
"""
has_lhn = False
for edge i... | 37e435918d93179d8ffb11e476da99798a7ca701 | 595,162 |
def find_percentages(billable_hours, internal_hours, total_hours):
"""
Take total billable, internal, hours to find out the percentages of each.
"""
billable_percent = 0.0
internal_percent = 0.0
if total_hours > 0:
billable_percent = round(billable_hours/total_hours*100, 1)
inter... | 3b1d17ebcf4e2734a49001c2d692ff63cd18441c | 595,165 |
def get_last_material_name(row, table):
"""Return name of the last non-DATA material in a table row"""
name = None
for i in range(len(row)):
cell = row[i]
header = table['field_header'][i]
if (
header['obj_cls'] == 'GenericMaterial'
and header['item_type'] != ... | aed39e759ba6c741474f809052fbbced06c1498a | 595,170 |
def getFork(user, upstream, create=False):
"""Get user's fork of the specified repository.
:param user:
Github user or organization which owns the requested fork.
:type user:
:class:`github:github.NamedUser.NamedUser`,
:class:`github:github.AuthenticatedUser.AuthenticatedUser` or
:class:`github:g... | 9ac0d41a2b4aa27ed9addf3df9597b557909d0e7 | 595,172 |
def smartopen(fileHandle, mode='r'):
"""Return an open file object, if passed a filename;
otherwise just return the object.
@param fileHandle: Input or output file or filename
@param mode: IO mode ('r', 'w', ...)
@return: the open file object
"""
if type(fileHandle)==str:
ioFile... | 1025fa25cd1f4026f2d5f8b2cb3d9a03b2a40ace | 595,174 |
def cell_from_screenspace(screenspace_coords: tuple, tile_size: int):
"""
Helper function to convert from screenspace coordinates to tile row and column.
Calculations based on texture base tile size; no boundary checking is performed.
Parameters:
screenspace_coords (Tuple[float, float]): The X ... | 717f2f6e60a9bd973ca32bba1c7173734fcb7266 | 595,175 |
def marconi_time_correction(t):
"""Corrects the marconi pulsetime [us] by 0.059 us"""
return t - 0.059 | fe64fd016db4a035d87a1371191d9c261ebf4ecc | 595,177 |
import re
import hashlib
def checksum_mzml_stream(stream):
"""Calculate the SHA1 checksum of an indexed mzML file for the purposes
of validating the checksum at the end of the file.
Parameters
----------
stream : file-like
A file-like object supporting a `read` method.
Returns
--... | f3498201cee00737f84b2ee214cbf176cc4aa3c5 | 595,180 |
def parse_fasta_file(path: str) -> str:
"""Parses contents of an input text file in FASTA format.
Args:
path: Path to input text file.
Returns:
The sequence.
"""
file = open(path, "r")
contents = file.readlines()
text = "".join(contents[1:]).replace("\n", "")
file.clos... | 890e45d2cd732cd708f6f0dead9072492be0d384 | 595,185 |
def line_func(p1: list, p2: list):
"""Take two x,y points. Return a linear function through them both.
:param p1: list of [x1, y1] ordered pair (point)
:param p2: list of [x2, y2]
:return: (linear) function in 1 variable, which passes through both points.
"""
assert len(p1) == len(p2) == 2
... | 8f86675d409e14cbd351185e54402e05f7b26792 | 595,186 |
import re
def PipeFormat(contents):
"""Takes in contents of txt file that is delimited with pipes, orders data
appropriately, converts gender letters into strings, and returns a list"""
temp_list = []
regexp_pipe = r"(\w+)\W+(\w+)\W+\w\W+(\w)\W+(\w+)\W+(\d+/\d+/\d+)"
reg_return = re.findall(regexp_pipe, con... | ca1b9a36c28bcf77a083286507fd12774970c86c | 595,189 |
def verse(bottle):
"""Sing a verse"""
if bottle > 2:
return '\n'.join([
f'{bottle} bottles of beer on the wall,',
f'{bottle} bottles of beer,',
'Take one down, pass it around,',
f'{bottle - 1} bottles of beer on the wall!\n'
])
if bottle == 2:
return ... | 38ffd9b3480ecf6068a8032acdb1dab0fcea57da | 595,191 |
def _value_set(query_set, field_name):
"""
Short-hand for creating a set out of a values-query for a single model field
"""
return set(query_set.values_list(field_name, flat=True)) | 7a04f82d38d0a948f1c61731b52bc265bf08724e | 595,194 |
def parse_cookies_str(cookies):
"""
parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict
"""
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
... | 0ebc35418d2d9b077c201cf066ef3176d79af631 | 595,198 |
def get_list_items(input_path):
"""
Function creates a list of items that were found by HMMScan
:param input_path: file with contigs and their KEGG annotations
:return: list of unique KOs, { contig_name1: [KO1, KO2,...], contig_name2: [...], ...}
"""
items = []
dict_KO_by_contigs = {}
wi... | 289e72a06c84df268c55e561b2d9b6c61d119798 | 595,200 |
import torch
def consensus(global_model, client_models):
"""
Computes the consensus value of each client model by comparing it to the global
one. We use Mean Square Error to measure the distance between two weight vectors
and average the consensus values of each parameter vector.
Params:
... | f797e0cabb6739a1a4db760def066a91f7fc1162 | 595,201 |
def request_help_privacy(twhandler):
"""Return the handler for GET help/privacy."""
return twhandler.help.privacy | aafb7e1ed7328fe5eff31933249205867a239657 | 595,204 |
def correlation(list1, list2):
"""Calculates correlation for the given lists"""
n = len(list1)
sum_xy = sum([x * y for x, y in zip(list1, list2)])
sum_x = sum(list1)
sum_y = sum(list2)
sum_x2 = sum([x**2 for x in list1])
sum_y2 = sum([y**2 for y in list2])
corr = ((n * sum_xy) - (sum_x ... | ef0edc9dd64695bbd252b2c0d032c10fbb244e4c | 595,205 |
from typing import Optional
from typing import Iterable
from typing import Dict
from typing import Any
def build_loggers_dictionary(
loggers: Optional[Iterable[str]], logger_config: Dict[str, Any]
) -> Dict[str, Dict]:
"""
Build a dictionary of loggers to configure.
This will automatically include a ... | a464a46f64505e6053ab9297c8b01b1e8ec30d32 | 595,209 |
def slice_fn(tuple_slice):
"""Makes a function that slices a list.
Args:
tuple_slice (`tuple`): tuple of 2 floats denoting
the percentage at which to split the argument
of the function.
Returns:
A function that slices an iterable.
"""
return lambda l: l[slic... | 119b0923730e0135463d3453d1f80ed45e6987fd | 595,212 |
from typing import Dict
from typing import Any
from typing import List
def get_all_cards_and_tokens_from_content(
all_printings_content: Dict[str, Any]
) -> List[Dict[str, Any]]:
"""
Convert the content of AllPrintings into a list of card objects
:param all_printings_content: Content of AllPrintings
... | 3aed7755d7f58d458b321945c73b9593071b760a | 595,217 |
def is_valid_int(val):
""" Checks if given value is int """
if val and not isinstance(val, int):
return False
return True | 0ec27bac3593da04de584dca749ed449410ea535 | 595,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.