content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def patch_id(options):
"""Returns the review ID or the GitHub pull request number."""
return options['review_id'] or options['github'] | 7623a25f4d74c4794d8c56c94c6b98f3db80a604 | 413,934 |
def add_http_parameters(url: str, params: dict) -> str:
"""
Adds HTTP parameters to url.
:param url: url address
:param params: http parameters
:return: url with added http parameters
"""
result: str = url + "?"
params_added: int = 0
for param in params:
result += param + "=... | 0918c263d764efe8b1fc668f73a70dc953f2ba90 | 57,946 |
def get_adi_ids(metadata):
"""Returns a list of the adipose shell IDs for each sample
Parameters
----------
metadata : array_like
Array of metadata dicts for each sample
Returns
-------
adi_ids : array_like
Array of the adipose IDs for each sample in the metadata
"""
... | b057d56e0e47bc2b604ccfa28bca1660ff711d5f | 126,307 |
import json
def has_value(json_str, value):
"""Check for the presence of a value in a JSON-serialized dict."""
return value in json.loads(json_str).values() | e05307b1b12debb702eda2c1d0c87baf6e0ebcb0 | 261,842 |
def bin_search_recursive(array, what_to_find, left=0, right=None):
"""
Finds element in a sorted array using recursion.
:param list array: A sorted list of values.
:param what_to_find: An item to find.
:returns: Index of the searchable item or -1 if not found.
"""
right = right if right is... | 83ff4dbcd9cab179c5e83f73d5fdc7c5a6bca4d4 | 8,712 |
import requests
def _get_access_token(key: str, secret: str) -> str:
"""
Requests an access token from Bitbucket.
:param key:
The OAuth consumer key
:param secret:
The OAuth consumer secret
:return:
The Bitbucket access token
"""
url = 'https://bitbucket.org/site/o... | 78330eb368129a7d94ca8b790698e4a0a4fc39f5 | 230,575 |
def sequentialize_header_priorities(header_priority_pairs):
"""
In a case where a H3 or H4 succeeds a H1, due to the nature of the Table of Contents generator\
which adds the number of tabs corresponding to the header priority/strength, this will sequentialize\
the headers such that all headers have a p... | ba90688adf7917d898b836f5913040ef2e1c4e6d | 363,258 |
import random
def _random_float(low, high):
"""
:param low: the inclusive minimum value
:param high: the inclusive maximum value
:return: a random float in the inclusive [low, high] range
"""
return (random.random() * (high - low)) + low | 87be42ad3185e1937709f2bcb80fce7afa9a2639 | 435,270 |
def is_path_prefix_of_path(resource_prefix, resource_path):
"""
Return True if the arborist resource path "resource_prefix" is a
prefix of the arborist resource path "resource_path".
"""
prefix_list = resource_prefix.rstrip("/").split("/")
path_list = resource_path.rstrip("/").split("/")
if ... | 49415f67cb7d28adf1a5f88bc421864872c267fb | 200,845 |
def _is_member(s, e):
"""Return true if `e` is in the set `s`.
Args:
s: The set to inspect.
e: The element to search for.
Result:
Bool, true if `e` is in `s`, false otherwise.
"""
return e in s._set_items | 810336bb16babcca3af8bc9c931da3d058b6f14f | 694,242 |
from functools import reduce
def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: ... | c155a9ad2b0e704d1cc3a981d10d9be1ac2e905a | 668,333 |
def addr2str(addr):
"""
Converte um endereço IPv4 binário para uma string (no formato x.y.z.w)
"""
return '%d.%d.%d.%d' % tuple(int(x) for x in addr) | bbb48bc6d3c2abc929e08ba0396f30fe397fccc1 | 219,251 |
from typing import List
def listToCSV(lst: List) -> str:
"""
Changes a list to csv format
>>> listToCSV([1,2,3])
'1,2,3'
>>> listToCSV([1.0,2/4,.34])
'1.0,0.5,0.34'
"""
strings = ""
for a in lst:
strings += str(a) + ","
strings = strings[0:len(strings) - 1]
return s... | 89fc272c4b9fc0a3a406f67d7b655b2c72755d07 | 35,479 |
def default_hash(i: int, x: int, n: int):
"""Return a hash value for x.
Arguments:
i: hash function index within family
x: value to be hashed
n: domain
"""
return (x + i) % n | fb58c2acaad8c5c3dd3be7e14892ca18dfbdb2b8 | 516,587 |
import typing
def id_class_name(value: typing.Any) -> str:
"""Provide class name for test identifier."""
return str(value.__class__.__name__) | 9d7fae15e07dd994f865baf67d753b43031efd31 | 93,471 |
import re
def vertical_sep_in_line(line):
"""
Find the indices in a line which are potentially or probably
vertical separators (characters commonly used to indicate
the end of columns).
"""
VERTICAL_SEP = r"[+|\.`'╔╦╗╠╬╣╚╩╝┌┬┐╞╪╡├┼┤└┴┘]"
return [m.start() for m in re.finditer(VERTICAL_SEP,... | c8d99a5ae9eee8558e75183b27334afa28d3794d | 523,431 |
import torch
def convert_to_one_hots(a, num_classes: int, dtype=torch.int, device=None):
"""
Convert class index array (num_sample,) to an one hots array
(num_sample, num_classes)
Args:
a: index array
num_classes: number of classes
dtype: data type
Returns:
one ho... | 04a7465b03736704ba0eabb22e32194efbd4d7a6 | 221,918 |
import json
def GetValueInJsonFile(json_path, key, default_value=None):
"""Reads file containing JSON and returns value or default_value for key.
Args:
json_path: (str) File containing JSON.
key: (str) The desired key to lookup.
default_value: (default:None) The default value returned in case of miss... | 99e7d22b967b9f47ca3c49cd441e2aac364e0e14 | 201,079 |
import re
def words(string):
"""
Split a string into a list of words, which were delimited by one or more
whitespace characters.
"""
return re.split('\s+', string) | bcd77a2b5005b8418cc55efd96214c4b86f09a5a | 213,261 |
import torch
def quaternion_to_rotmat_jac(q):
"""
Converts batched quaternions q of shape (batch, 4) to the jacobian of the
corresponding rotation matrix w.r.t. q of shape (batch, 9, 4)
"""
qr = q[:, 0:1]
qi = q[:, 1:2]
qj = q[:, 2:3]
qk = q[:, 3:4]
z = torch.zeros_like(qk)
r1... | 0b97c5232b4b11f1feabf27df39e38db135443d7 | 58,868 |
def max_or_0(it):
"""
>>> max_or_0([])
0
>>> max_or_0(iter([]))
0
>>> max_or_0(iter([-10, -2, -11]))
-2
"""
lst = list(it)
return max(lst) if lst else 0 | d45222ae48af18be28d3625d950a61e9e58ec0b4 | 129,143 |
def _qualified_type_name(class_):
"""
Compute a descriptive string representing a class, including
a module name where relevant.
Example outputs are "RuntimeError" for the built-in RuntimeError
exception, or "struct.error" for the struct module exception class.
Parameters
----------
cl... | e1000f66b7ab0e10553beadd3ad91214c31fa3ed | 156,507 |
def dec_to_bin(x):
"""Convert from decimal number to a binary string representation."""
return bin(x)[2:].zfill(4) | b3b2734c7b4fc0c028a27de142783b31dad48792 | 412,244 |
def read_segs(segfile):
"""Returns a dict with scid as the key and segments as value from a '.seg' file.
A '.seg' file consists of a set of lines with the following format:
scene_name[\t]segment_name[\t]start_time[\t]end_time[\n]
scene_name is the id of the Scene that this Segment belongs to,
segm... | 49cfeed5606aa8dc9b2636dc8aa5661427de4314 | 294,724 |
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int:
"""
Iterate through the array to find the index of key using recursion.
:param list_data: the list to be searched
:param key: the key to be searched
:param left: the index of first element
:param right: the index of las... | a567469caa72be724097594f08e971875f3bb527 | 611,230 |
def scol(string, i):
"""Get column number of ``string[i]`` in `string`.
:Returns: column, starting at 1 (but may be <1 if i<0)
:Note: This works for text-strings with ``\\n`` or ``\\r\\n``.
"""
return i - string.rfind('\n', 0, max(0, i)) | 2aa922fa81dbd700f2da2f3ca177a94351282660 | 387,791 |
def this_extra_edition_number(edicao):
"""
Gets a string 'edicao' that states which is this DOU's edition
(e.g. 132-B or 154) and returns the number (int) of extra editions up
to this current one. No extra editions (e.g. 154) is 0, first
extra edition (134-A) is 1, and so on.
"""
last_char ... | 21e313308e691b82539a4ed2d942422bc0c53f33 | 518,776 |
def format_relation(
relation_type: str, start_id: str, end_id: str, **properties) -> dict:
"""Formats a relation."""
relation = {
':TYPE': relation_type,
':START_ID': start_id,
':END_ID': end_id,
}
relation.update(properties)
return relation | 88ccbefcb530556673ee8d6b44a761da84044a8c | 262,604 |
def cal_triangle_area(p1, p2, p3):
"""
Calculate the area of triangle.
S = |(x2 - x1)(y3 - y1) - (x3 - x1)(y2 - y1)| / 2
:param p1: (x, y)
:param p2: (x, y)
:param p3: (x, y)
:return: The area of triangle.
"""
[x1, y1], [x2, y2], [x3, y3] = p1, p2, p3
return abs((x2 - x1) * (y3 -... | 61d5f16c2573cf912ba7a3c21f3465eb68395971 | 369,362 |
def unescape_special(v):
""" Unescape string version of literals.
"""
if v == 'True': return True
elif v == 'False': return False
elif v == 'None': return None
else: return v | 8566509cffb2f5ee4f8382df9ff43da0da1ef4eb | 282,018 |
def trim_precision(value: float, precision: int = 4) -> float:
"""
Trim the precision of the given floating point value.
For example, if you have the value `170.10000000000002` but really only care about it being
``\u2248 179.1``:
.. code-block:: python
>>> trim_precision(170.10000000000002, 2)
170.1
>>> ... | 20eab8f72e5e7a426523fac70eca4a46b9334ca1 | 203,266 |
def pop_filter(items, predicate=None):
"""Remove the first object from the list for which predicate returns True;
no predicate means no filtering.
"""
for i, item in enumerate(items):
if predicate is None or predicate(item):
items.pop(i)
return item | 9ebe00c41be32054e7f33600e3459488411d68e1 | 556,880 |
def speed_to_pace(x):
""" convert speed in m/s to pace in min/km """
if x == 0:
return 0
else:
p = 16.6666666 / x # 1 m/s --> min/km
return ':'.join([str(int(p)),
str(int((p * 60) % 60)).zfill(2)]) | 9f785fb5b704cb6040b8c468175093b196b6deab | 291,148 |
def num_to_int_str(num: float) -> str:
"""Takes a float and converts to int, and then returns a string version."""
return str(int(round(num))) | 33c5122ee51edd0d8be726ac6bdac9b7e4207be3 | 417,204 |
def milliseconds_to_seconds(milliseconds: int):
"""
Function that attempts to convert the passed in milliseconds into minutes and seconds
Parameters
----------
milliseconds: int
milliseconds for conversion
Returns
-------
int, int
first integer as minute and the second ... | c4bea38ca58e737a2141d86ebfc815210081c5ff | 185,945 |
def lam2rgb(wav, gamma=0.8, output='norm'):
"""
Convert a wavelength [nm] to an RGB colour tuple in the visible spectrum.
This converts a given wavelength of light to an
approximate RGB colour value with edge attenuation.
The wavelength must be given in nanometres in the
range from 380 nm - 750... | ecd90f0a4f5a2765d755dac6723d4c43307d5773 | 170,716 |
def output_fn(prediction, response_content_type):
"""
Serialize and prepare the prediction output
"""
if response_content_type == "application/json":
response = str(prediction)
else:
response = str(prediction)
return response | cb0bd922011190bf36aa37b792ecd904a545c915 | 225,608 |
def rk4_backward(f, x, h, **kwargs):
"""Implements a backwards classic Runge-Kutta integration RK4.
Parameters
----------
f : callable
function to reverse integrate, must take x as the first argument and
arbitrary kwargs after
x : numpy array, or float
state needed by functi... | f1a017131b41303d82392d7b9283a4ee2955064b | 619,232 |
async def convert_to_json(response):
""" Converts the aiohttp ClientResponse object to JSON.
:param response: The ClientResponse object.
:raises: ValueError if the returned data was not of type application/json
:returns: The parsed json of the response
"""
if "Content-Type" in response.headers ... | 9644dc2d7b9b24a7be980dabb8faa57c81ef7ed1 | 419,708 |
def read_file(file_name, verbose=False):
"""Takes a file name and returns the lines from the file as a list. Optional verbosity param
:param file_name: path to file to be read
:param verbose: run with extra logging
:returns lines: list strings representing lines in the file
"""
if verbose:
... | 3f689a78d61b7d1d4eb35f0c232fa945ee123074 | 31,469 |
def getFloatFromUser(message):
"""
Obtains positive real number from user.
Arguments:
message -- the message that is printed for the user, describing what is expected
Returns:
var -- a positive real number that the user entered
"""
var = None # initialize the variable ... | 1cb7ecfcb34e89c2da2d3534a9b5eace4a81f14b | 423,801 |
import torch
def xyxy2xywh(xyxy):
"""Convert bounding box enconding from [x1, y1, x2, y2] to [x, y, w, h]."""
# the input tensor must have four components in the last dimension
xywh = torch.zeros_like(xyxy)
xywh[:, 0] = (xyxy[:, 0] + xyxy[:, 2]) / 2
xywh[:, 1] = (xyxy[:, 1] + xyxy[:, 3]) / 2
x... | 67e2a3db9a5194d88284a7c2180cf3c1292ae1ac | 590,917 |
def unk_counter(sentence, vocab_to_int):
"""Counts the number of time UNK appears in a sentence."""
unk_count = 0
for word in sentence:
if word == vocab_to_int["<UNK>"]:
unk_count += 1
return unk_count | c20717c11c0a7a6a64d005aa9cd800b5119ad8d6 | 438,948 |
def fb_match_metadata(pageSoup):
"""
Extracts general information (teams, managers, captains, date, time, venue, attendance, score, xG) for a given match
Parameters:
pageSoup (html document): bs4 object of a match
Returns:
dict: metadata information
dict: match officials
"""
#... | 95e1be1b828ab85ca14458d1318e233acbfbd7f2 | 330,754 |
def keyfr(frame=0, duration=1000, **kwargs):
"""
Returns a single keyframe with given parameters
:param frame: name or number of image for this keyframe
:param duration: time in milliseconds for this keyframe
:param angle: degrees of clockwise rotation around a center origin
:param flipx: set True to flip image ... | e5d2970dbab84e5203bc55db5a8193010181a9c8 | 190,432 |
def is_palindrome(number: int) -> bool:
"""Test if a number is a palindrome."""
as_string = str(number)
return as_string == as_string[::-1] | c85456bcf921e60c3622c1a084162aa2159abc70 | 498,350 |
from pathlib import Path
def fixture_tmp_zipfile(tmp_path: Path) -> Path:
"""Path of the ZIP file in the temporary directory."""
return tmp_path.joinpath("zipfile_samples.zip") | d507d19ace236c2d4dd7ce1ffa823b99a16d018f | 385,478 |
def datetime_to_str(value, fmt="%Y-%m-%d %H:%M:%S"):
""" 时间类型转换为字符串。datetime to string.
:type value: datetime.datetime
:type fmt: str
:rtype: str
"""
return value.strftime(fmt) | 34b28de5fbfa8f73957ead7ba314b76f38a89f27 | 465,890 |
def line_side(start_vector, end_vector, position_vector):
"""
Find out what side a position_vector is on given a line defined by start_vector and end_vector.
Args:
start_vector (list): eg. [0,0,0] vector\
end_vector (list): eg. [0,0,0] vector
position_vector (list): eg. [0,0,0] ... | 26ebb60f6f8779c8be7ef2068bfb5e4c255657c0 | 47,877 |
def DeleteTypeAbbr(suffix, type_abbr='B'):
"""Returns suffix with trailing type abbreviation deleted."""
if not suffix:
return suffix
s = suffix.upper()
i = len(s)
for c in reversed(type_abbr.upper()):
if not i:
break
if s[i - 1] == c:
i -= 1
return suffix[:i] | 6805befcd30bfca8340383570ff555743f764c5f | 356,109 |
def pad_word_chars(words):
"""
Pad the characters of the words in a sentence.
Input:
- list of lists of ints (list of words, a word being a list of char indexes)
Output:
- padded list of lists of ints
- padded list of lists of ints (where chars are reversed)
- list of int... | 8b1d5dd5fc92bd95bce2888d2f0db150de1b2e66 | 560,796 |
def get_server_cloud(server_name):
"""Get the server cloud from the server name."""
if "." in server_name:
server_name, server_domain = server_name.split(".", 1)
return (server_name, server_domain)
else:
return (server_name, None) | 4c6485cacc456f8652ee57d5c42703fe1a4fc1d7 | 495,257 |
def _canonicalize_extension(ext):
"""Returns a transformed ext that has a uniform pattern.
Specifically, if ``ext`` has a leading . then it is simply returned.
If ``ext`` doesn't have a leading . then it is prepended.
Exceptions to this are if ``ext`` is ``None`` or "". If ``ext``
is "" then "" is r... | 935e85fd9a0f1bcfadc68c2390446ecbc814a0bc | 695,381 |
def is_first_char(input_string, char):
""" INPUT:
input_string = string of any length, typically a line in a file being parsed
char = string of the character we want to compare with to determine a match
RETURN:
True ; if char == first character in input_string
... | 308a27216e1c657e8cb762e67f1e6250bd205807 | 154,981 |
def post_list(db, usernick=None, limit=50):
"""Return a list of posts ordered by date
db is a database connection (as returned by COMP249Db())
if usernick is not None, return only posts by this user
return at most limit posts (default 50)
Returns a list of tuples (id, timestamp, usernick, avatar, ... | 6438f531446611b3de866a60b2fb146907628589 | 351,804 |
def getFirstColumn(df):
"""
:param pd.DataFrame df:
:return list-object: first column of df
"""
return df[df.columns[0]].tolist() | fc44f1a7fda04aa3ced5993646a663fd7acebc0a | 489,481 |
def lcm(a, b):
"""
Simple version of lcm, that does not have any dependencies.
:param a: Integer
:param b: Integer
:rtype: The lowest common multiple of integers a and b
"""
tmp_a = a
while (tmp_a % b) != 0:
tmp_a += a
return tmp_a | cf87f390267bda90631e9e349a9ea81ccac70fc9 | 550,669 |
def get_service_type(f):
"""Retrieves service type from function."""
return getattr(f, 'service_type', None) | fb4d98a4b4db0d10ab97d94d98ccfe21cea05fe9 | 701,472 |
def obj_version_from_env(env):
"""
Fetch an object version from a request environment dictionary.
This discards 'null' versions since they are not supported by the
oio backend.
"""
vers = env.get('oio.query', {}).get('version')
if isinstance(vers, str) and vers.lower() == 'null':
ve... | 876304f082884f5f645cdad8a412bcbbb0027b83 | 434,815 |
import torch
def _sort_batch_by_length(tensor, sequence_lengths):
"""
Sorts input sequences by lengths. This is required by Pytorch
`pack_padded_sequence`. Note: `pack_padded_sequence` has an option to
sort sequences internally, but we do it by ourselves.
Args:
tensor: Input tensor to RNN... | 0fd0df95135e82b02ce85f29c366e01c3e67409b | 76,724 |
def build_error_response(msg, code=-1, status="error"):
"""Make Error Response based on the message and code"""
return dict(status=status, success=False, result=dict(description=msg, code=code)) | 358b0de1d4cfdb3c858b9c6f988177ef1be6f4c3 | 436,043 |
import torch
def cat_arange(counts, dtype=torch.int32):
"""
Concatenate results of multiple arange calls
E.g.: cat_arange([2,1,3]) = [0, 1, 0, 0, 1, 2]
Credits: https://stackoverflow.com/a/20033438
:param torch.tensor counts: a 1D tensor
:return: equivalent to torch.cat([torch.arange(c) for c... | 61baf564bf03e7c0713ea2ef1b3ff9f08ae8949d | 648,733 |
def _safe(key, dic):
"""Safe call to a dictionary. Returns value or None if key or dictionary does not exist"""
if dic is not None and key in dic:
return dic[key]
else:
return None | c11b7f236d35f42bef6839a1fc244de446593e56 | 412,679 |
from passlib.context import CryptContext
def make_passwordmanager(schemes=None):
"""
schemes contains a list of replace this list with the hash(es) you wish
to support.
this example sets pbkdf2_sha256 as the default,
with support for legacy bcrypt hashes.
:param schemes:
:return: CryptCon... | fe278c057e735aca56716ecf397f7664ff010a37 | 671,069 |
def get_rendered_content_with_filled_template(total_movies, movie_entries):
""" Given data extracted from input file, fill in the html template
Args:
total_movies: total # of movies
movie_entries: the html content representing the individual movies
Returns:
the final render... | 2c49bb45e48973ae83a2e51faa6b30b24343ac1d | 547,664 |
def vecs_from_tensor(x): # shape (...)
"""Converts from tensor of shape (3,) to Vecs."""
# num_components = x.shape[-1]
# assert num_components == 3
return x[..., 0], x[..., 1], x[..., 2] | 5ce0a22daba590f054348ce9736126fc1a611d00 | 410,420 |
def create_udp_port(byte_array):
"""
Creates the UDP port out of the byte array
:param byte_array: The byte array we want to get the port number
:return: Integer of the port number
"""
first_two_bytes = [int(no) for no in byte_array]
first_two_bytes = first_two_bytes[:2]
return int.from_... | 88f9d62ce4b173b10c519c3d347d3e8372f8e2d2 | 470,388 |
import torch
def mul_complex(t1, t2):
"""multiply two complex valued tensors element-wise. the two last dimensions are
assumed to be the real and imaginary part
complex multiplication: (a+bi)(c+di) = (ac-bd) + (bc+ad)i
"""
# real and imaginary parts of first tensor
a, b = t1.split(1, 4)
#... | 15b676321f9e5846a8e3da12eba17ffd052cb6ff | 55,617 |
import calendar
def to_unix_timestamp(timestamp):
"""
Convert datetime object to unix timestamp. Input is local time, result is an
UTC timestamp.
"""
if timestamp is not None:
return calendar.timegm(timestamp.utctimetuple()) | 95481b7c9d1a3a63e6a428f28e8a2fd87e49c623 | 660,015 |
from typing import Dict
from typing import Set
from typing import Any
def axis_keys(D: Dict, axis: int) -> Set[Any]:
"""Return set of keys at given axis.
Parameters
-------------------------------
D: Dict
Dictionary to determine keys of.
Axis:int
Depth of keys.
Returns
--... | b44dac5a9265e917c76a6d60f26b6bbd4958d733 | 80,995 |
def mults_of_ns(mults=[1], limit=1000):
"""
returns the sum of all the values that are multiples of ns up to limit
"""
return sum(set([val for val in range(limit) for arg in mults if val%arg==0])) | a393a2b08b3a53b2136d0612e43fa26d334aa06c | 448,683 |
import math
def vect_len(a):
"""
Get the length of a vector
"""
return math.sqrt(a[0]**2 + a[1]**2 + a[2]**2) | 7d2bd0f2b7b499df60f0bcc35d0a320703710784 | 486,449 |
def pop_param(request_values, name, default=None):
""" Helper to pop one param from a key-value list
"""
for param_name, value in request_values:
if param_name.lower() == name:
request_values.remove((param_name, value))
return value
return default | e8d1fe8691c062fd49ceff323236668fbda98d3f | 318,033 |
def get_english_chapter_count(book):
"""
A helper function to return the number of chapters in a given book in the English version of the Bible.
:param book: Name of the book
:type book: str
:return: Number of chapters in the book. 0 usually means an invalid book or unsupported translation.
:rt... | e1ee5cb200550d9d34e1753968fb46c332d2c68d | 610,078 |
import socket
import time
def wait_for(ip, port, timeout, _type='tcp'):
"""Wait for service by attempting socket connection to a tuple addr pair.
:param ip: str. an IP address to test if it's up
:param port: int. an associated port to test if a server is up
:param timeout: int. timeout in number of s... | 507f046d0516ce862b547dcef74ab901bd38fdf6 | 110,582 |
def get_company_by_email(domains_index, email):
"""Get company based on email domain
Automatically maps email domain into company name. Prefers
subdomains to root domains.
:param domains_index: dict {domain -> company name}
:param email: valid email. may be empty
:return: company name or None ... | a0cc14e9a0dafb76c5f8309c8aec22f447824f45 | 440,145 |
def any_to_any(container1, container2):
"""
Returns whether any value of `container1` is in `container2` as well.
Parameters
----------
container1 : `iterable-container`
Any iterable container.
container2 : `iterable-container`
Any iterable container.
Returns
------... | 893842b4fa83434c396f8e484fbdf9ea5f20d247 | 154,965 |
def number_of_interactions(records, direction=None):
"""
The number of interactions.
Parameters
----------
direction : str, optional
Filters the records by their direction: ``None`` for all records,
``'in'`` for incoming, and ``'out'`` for outgoing.
"""
if direction is None:... | c4262273a2a2bf02f2bd715198d765d9a93335e4 | 162,553 |
import typing
def _remove_keys(
parameters: typing.Dict[str, typing.Any], exclude_labels: typing.List[str]
) -> dict:
"""
Remove keys from a dictionary without changing the original.
Attempts to remove keys that don't exist in the dictinary are silently
ignored.
Args:
parameters: Dic... | 17fdefa40cf558bb3b293f647edf6445dc9b58fd | 87,800 |
import math
def quaternion_from_matrix(M):
"""Returns the 4 quaternion coefficients from a rotation matrix.
Parameters
----------
M : list[list[float]]
The coefficients of the rotation matrix, row per row.
Returns
-------
[float, float, float, float]
The quaternion coeffi... | 6318208e9186ddbe26cdd1dc6175898918f39969 | 628,124 |
def indent(amount: int, s: str) -> str:
"""Indents `s` with `amount` spaces."""
prefix = amount * " "
return "\n".join(prefix + line for line in s.splitlines()) | 201dd126cfb46748fd5b0b0cefb3fc01f5fdb5f4 | 423,455 |
def combine_convergence_data(data_A, data_B):
""" Combine dictionaries with potentially overlapping keys. """
data = {}
for key in data_A:
data[key] = data_A[key]
if key in data_B:
data[key].update(data_B[key])
for key in data_B:
if key not in data:
data[k... | 5117c498ff1b27356de096b5d15768e2005e3e47 | 609,568 |
def module_to_xapi_vm_power_state(power_state):
"""Maps module VM power states to XAPI VM power states."""
vm_power_state_map = {
"poweredon": "running",
"poweredoff": "halted",
"restarted": "running",
"suspended": "suspended",
"shutdownguest": "halted",
"rebootgu... | 6c02106f08078e7366056b67619f47698a322d22 | 507,368 |
def to_returns(prices):
"""
Calculates the simple arithmetic returns of a price series.
Formula is: (t1 / t0) - 1
Args:
* prices: Expects a price series
"""
return prices / prices.shift(1) - 1 | 4bbe3a23bfe5e95e8b861b9dbf1a1b48a2c82865 | 232,395 |
def unflatten(flat_config):
"""Transforms a flat configuration dictionary into a nested dictionary.
Example:
{
"a": 1,
"b.c": 2,
"b.d.e": 3,
"b.d.f": 4,
}
would be transformed to:
{
"a": 1,
"b": {
"c": 2,
"d": {
"e": 3,
"f": 4,
... | f7788c41cabfd9e992349709db40364ac6e59fe5 | 221,028 |
def bubblesort(a):
"""Bubble Sort algorithm for sorting a sequence container of values.
"""
l = len(a)
swaps = 1
while swaps > 0:
swaps = 0
for i,j in zip(range(0,l-1),range(1,l)):
if a[i] > a[j]:
t = a[i]
a[i] = a[j]
a[j] =... | 47fe2888cba6f9654f014320038a38a6b24c0780 | 279,010 |
import re
def extract_page_nr(some_string):
""" extracts the page number from a string like `Seite 21`
:param some_string: e.g. `Seite 21`
:type some_string: str
:return: The page number e.g. `21`
:rtype: str
"""
page_nr = re.findall(r'\d+', some_string)
if len(page_nr) > 0:
... | 6d39314de89c8f4bf4d931f2dc329fe394a10091 | 9,404 |
def evaluate(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set of gold... | 5c3284a1647cfa336ec7170b35f7d702d1538c21 | 661,314 |
import csv
def parseList(string):
"""
Decomposes strings like '"val1,val2",val3,"val4,val5"'
into a list of strings:
[ 'val1,val2' ,'val3', 'val4,val5' ]
"""
for line in csv.reader([string],delimiter=","):
values = line
#for i,value in enumerate(values):
# values[i] = valu... | 66cd73e80b67621576f2571e99ac328672acc440 | 619,060 |
def get_cat_code_dict(df, col):
"""Returns a dict to pase a categorical column to another categorical but using integer codes in order to use it with shap functions.
Parameters
----------
df : pd.DataFrame
col : str
Column to transform
Returns
-------
dict
Original name... | 9b0cb51072133cf1896f1bd24313f9160c05fd37 | 76,222 |
import random
import string
def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | c90907ddd48386fcdf0008bea4426b203247e5dc | 261,801 |
import pickle
def load_obj(name, path):
"""
Parameters
----------
name : string
the named of the pkl file that will be loaded.
path : string
the full path of the intended file.
Returns
-------
type of the object within the file
the object in the specified file... | 26e28c6bbc9352535a2ce61bc4b420ca574236ca | 608,231 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
# Negative numbers don't have real square roots since a square is either positive or 0.
# source : https://www.... | d54fe92f7c79e77916a13485091060ae11c35c6b | 290,860 |
import random
import string
def _random_filename(filename, k=8):
"""Random Filename
:param filename: The original filename. Can be a path
:param k: Length of additional character
:returns: Original filename with additional random string of size k
"""
filename = filename.split(".", 1)
salt... | 7bdf31e39c85f29e8b7827443e8f98482f221e3f | 279,070 |
def slope(first_point, second_point):
"""
Returns the slope between 2 points
:param first_point: first point (x,y)
:param second_point: second point (x,y)
:return: the slope
"""
return 0. if first_point[0] == second_point[0] else\
((float(first_point[1]) - float(second_point[1])) / ... | 8b8738af96279a112cc0cf01591d8d7bf5de429b | 671,541 |
def aumentar(valor=0, porc=0):
"""
Função que aumenta o valor por uma porcentagem dada.
:param valor: valor que se quer aumentar
:param porc: porcentagem
:return: o valor acrescido da porcentagem
"""
num = valor + (porc/100)*valor
return num | d8ff1bb0091a3e979168979aa35f1674161e1f45 | 475,412 |
import time
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing | 5b3d01055ee06ff8a77a90514cb12070ac22cda1 | 97,440 |
import string
def normalize(token_list):
"""Removing punctuation, numbers and also lowercase conversion"""
# Building a translate table for punctuation and number removal
# token_list = [re.findall(r'[0-9]+|[a-z]+', s) for s in token_list]
# token_list = reduce(operator.add, token_list)
punctnum_... | e000456b57be0fd44e6c03c0162b39165fc48aa5 | 59,685 |
def ensure_string(x):
"""Returns a string if x is not a string, and x if it already is."""
return str(x) | 06a67f31706810694f263db52fd8fd144f38a966 | 560,599 |
def get_height(root):
"""Extracts the ash plume height - only valid for ash alerts!
Values returned are in this order:
1. Maximum ash height (kilometers)
2. Maximum ash height (feet)
3. Tropopause height (kilometers)
4. Tropopause height (feet)"""
hgt_km = root.alert.max_height.attrib.get('v... | 6203283f35a46cb6229a606b46e69cb78409624d | 394,558 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.