content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import AnyStr
import codecs
def auto_encode(string: AnyStr, encoding: str = "utf-8", errors: str = "strict") -> bytes:
"""Lookup a encoder and encode the string if it is bytes, else return it
untouched if it's already in bytes (for utf). If its an int, etc, it'll try
to wrap it in bytes for you.
:par... | ff5854e843f718adaec728ac11083cfa22604e9e | 73,544 |
def list_transit_times(t0, period, steps_or_num_transits=range(0, 10), return_string=False):
"""List the transit times based on the supplied transit parameters"""
if isinstance(steps_or_num_transits, int):
steps = range(0, steps_or_num_transits)
else:
steps = steps_or_num_transits
times ... | 9cc74861f02f05412ef4ac71202b210862087734 | 73,545 |
import re
def get_version(file_path):
"""
Return the project version tag.
Parameters
----------
file_path : str
The path to the project __init__.py file.
Returns
-------
version : str
The project version tag.
"""
with open(file_path, mode='r') as init_file:
... | 4ccfaadf78466f4124aa3fb2c3c6249257c03e93 | 73,546 |
def safe_unicode(obj):
"""Safe conversion to the Unicode string version of the object."""
try:
return str(obj)
except UnicodeDecodeError:
return obj.decode("utf-8") | f6a592f7ea0de5179f1b8a91e0bd75c9a5d522df | 73,547 |
import random
def e2e_slot_to_hotel_slot(slot):
"""Map an E2E slot onto a slot in the Hotel domain. If there are multiple tokens in the corresponding category
in the Hotel domain, randomly pick one from that category.
"""
slot_map = {
'food': ['address', 'phone', 'postcode'],
'custome... | b8fc7f83d8ce678ebb8df94732f2a1f2f49ceae1 | 73,555 |
def prepare_region_data(df, scale_by=1):
"""Prepare regional data so that it can be used in train_model_region."""
regions = df.region_name.unique()
x_region = {}
x_t_region = {}
y_region = {}
for i, region in enumerate(regions):
x_region[region] = (
df.loc[
... | b9fb87f344378bd1a0b34931ce278f00901d280c | 73,557 |
import functools
def cached(f):
"""
Decorator that creates a cached property.
"""
key = f.__name__
@property
@functools.wraps(f)
def decorated(self):
if key not in self._cache:
self._cache[key] = f(self)
return self._cache[key]
return decorated | 15246ae4c07d9f855c6830e5a60cf3cf3597effe | 73,559 |
import codecs
def to_hex(data):
"""Convert binary data to a hex string"""
return codecs.encode(data, 'hex') | 4685c0ef6f5a5cfe1b0027bac6d1a9421e86dda6 | 73,567 |
def get_unique_list(input_list):
"""
Return a new list of unique elemets only while preserving original order
"""
new_list = []
for element in input_list:
if element not in new_list:
new_list.append(element)
return new_list | 593bb0cc12f9c98a22490670d136f1a354d5cec0 | 73,571 |
import json
def parse_advice(json_response) -> str:
"""Get the advice from the JSON response."""
json_slip = json.loads(json_response)
advice = json_slip['slip']['advice']
return advice | d4a8680602917032ecd8a463fafe083851d0446c | 73,572 |
from typing import List
from typing import Union
from typing import Any
def reduce(values: List) -> Union[List[Any], Any]:
""" Reduce a list to a scalar if length == 1 """
while isinstance(values, list) and len(values) == 1:
values = values[0]
return values | 3922a86c462d265fd37736e9c9b56069ce4ab8d0 | 73,573 |
import requests
def get_sequence(UniprotID):
"""Get protein sequence from UniProt Fasta (using REST API).
"""
# collect UniProtID data
fasta_URL = 'https://www.uniprot.org/uniprot/'+UniprotID+'.fasta'
request = requests.post(fasta_URL)
request.raise_for_status()
fasta_string = request.tex... | ede837154bda738dc8e7e83c97c5f81b284db17c | 73,574 |
def modulus(x, y):
""" Modulus """
return x % y | ea2694f98133ddaf43da3f3eb702f5ba22dec597 | 73,576 |
def capitalized(piece_name: str) -> str:
"""Returns a capitalized version of a piece name
Args:
piece_name: Piece name
Returns:
Capitalized version
"""
return '%s%s' % (piece_name[0].upper(), piece_name[1:].lower()) | 98838f820e90f6b1540f537ed878324d02aefb87 | 73,579 |
def isDigit(char):
"""assumes char is a single character
returns a boolean, True is char is a digit, else False"""
digits = "0123456789"
return char in digits | f26193c9fff51cdaa87d76ac0e638cac09936b6e | 73,583 |
def first(predicate_or_None, iterable, default=None):
"""
Returns the first item of iterable for which predicate(item) is true.
If predicate is None, matches the first item that is true.
Returns value of default in case of no matching items.
"""
return next(
filter(predicate_or_None, ite... | e477073ab7c59f3650adc112f9dafd811661b32f | 73,587 |
from typing import Dict
import click
def prep_secrets(*, environment_mappings: Dict[str, str], secret_values: Dict[str, str]) -> Dict[str, str]:
"""Convert secrets from standardized name map to required environment variable map.
:param dict environment_mappings: Mapping from secret identifiers to environment... | cc73ac7052ff3b4476e64cee671e8501b7cb248e | 73,591 |
def percentageCalculator(x, y, case=1):
"""Calculate percentages
Case1: What is x% of y?
Case2: x is what percent of y?
Case3: What is the percentage increase/decrease from x to y?
"""
if case == 1:
#Case1: What is x% of y?
r = x/100*y
return r
elif case == 2... | 30443f29282cf06443a4276d3cbbe20b7c792382 | 73,594 |
def name_matches_object(name, *objects, **kwargs):
"""Determine if a resource name could have been created by given objects.
The object(s) must implement RandomNameGeneratorMixin.
It will often be more efficient to pass a list of classes to
name_matches_object() than to perform multiple
name_match... | f176c6681ea602e5d981a54bf7bb3fe5e2a31a40 | 73,595 |
def getRow(array, index):
"""
Returns the row of the given 2D array at the selected index
"""
column = []
for i in range(0,9):
column.append(array[index][i])
return column | b3ab69bba27f8fecc9d7c0dc5c686aa508e6a169 | 73,597 |
import random
def getRandomWord(wordList):
"""
Returns a random string from the passed list of strings.
"""
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex] | 1045614d50889c29626a0702a979a056c503b285 | 73,598 |
def create_time_callback(data):
"""Creates callback to get total times between locations."""
def service_time(node):
"""Gets the service time for the specified location."""
return data["demands"][node] * data["time_per_demand_unit"]
def travel_time(from_node, to_node):
"""Gets the travel times betwee... | 72633675e0f659bfebb5b30a3374818f2c5cedc7 | 73,599 |
def export_report(ss, report_id, export_format, export_path, sheet_name):
"""
Exports a report, given export filetype and location. Allows export format 'csv' or 'xlsx'.
:param ss: initialized smartsheet client instance
:param report_id: int, required; report id
:param export_form... | a2ec63fa85a7498043f5848404870a71059ffa9f | 73,604 |
def build_add_edge_query(source_label: str, target_label: str, edge_type: str, edge_props: str) -> str:
"""Build a standard edge insert query based on the given params"""
insert_query = 'UNWIND $props AS prop MERGE (n:Base {{objectid: prop.source}}) ON MATCH SET n:{0} ON CREATE SET n:{0} MERGE (m:Base {{objecti... | 645fe2edef12a2600aa22cdc2228ab7c22e301cc | 73,606 |
from pathlib import Path
def default_messages_path() -> Path:
"""
Get path of included messages.
"""
return Path(__file__).joinpath("..", "locale").resolve() | ce01a37d9b09000d46720325d79188702001e9c3 | 73,609 |
def get_filename(file_name_parts=None):
"""
This routine creates the filename to be used to store the record.
:param file_name_parts: file name parts
:return: File Name to store the record
"""
file_partial = ''
if file_name_parts is not None:
for part in file_name_parts:
... | d78a7c53b0db618dffdad3157989b81d699e0008 | 73,610 |
def getMetadataSizes(conn, showEmpty = True):
"""Get sizes of all InterMine metadata entries
Returns a dictionary of <name>:<size>
conn - open database connection
showEmpty - if true then 0 sizes are also shown"""
with conn.cursor() as cur:
cur.execute("select key, length(value), length(bl... | 9ae706eb3d0d45ca27f9551293b33b08b4ea2260 | 73,614 |
def merge_properties(previous_val, next_val):
"""
Function used in reduce for merging several xml properties to dict
Example:
Source: [
{"name": "name", "value": "cache_name"},
{"name": "groupName", "value": "group_name"}
]
Result: {
... | e91d0abba49e1f9bc1b628e25070d9d6e965b7d5 | 73,615 |
def correlation(x, y):
"""
Fill in this function to compute the correlation between the two
input variables. Each input is either a NumPy array or a Pandas
Series.
correlation = average of (x in standard units) times (y in standard units)
Remember to pass the argument "ddof=0" to the P... | 669f32eda3fa9508cefe0ea7e1b80c04523e6935 | 73,616 |
def dot(x, y):
"""Dot product of two lists of equal length"""
return sum(x_ * y_ for (x_, y_) in zip(x, y)) | 060c88268aa17d74d3544197110da94c89d755f6 | 73,619 |
def get_rank(s, i):
"""
get number of occurence of s[i] before i.
"""
c = s[i]
return s[:i].count(c) | 3b86e8e1678f98ae3a352238110e188732cd3fe5 | 73,620 |
def average_absolute_deviation(nums: list[int]) -> float:
"""
Return the average absolute deviation of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation
>>> average_absolute_deviation([0])
0.0
>>> average_absolute_deviation([4, 1, 3, 2])
1.0
>>> average_a... | a95b5e6fcc9c80ee28be367969959b8b977aeda9 | 73,625 |
def users_to_fullnames(users_df):
"""Returns a list a full names from users DataFrame"""
first_names = list(users_df["First name"])
surnames = list(users_df["Surname"])
full_names = [i + " " + j for i,j in zip(first_names, surnames)]
return full_names | 08b93e71d90b41723e0b219e86144df77a908bd2 | 73,626 |
def defuzzify(fired_rule_tuples: list) -> float:
"""
defuzzify consequent fuzzy values based on weighted average
:param fired_rule_tuples: list of tuples containing consequent values and matching rule weights
:return: The weighted average
"""
print(list(map(lambda x: x[0], fired_rule_tuples)))
... | c401319c6ea5d44ee880b76d28da2dacee24f305 | 73,630 |
def least_residue(a , m):
"""
Returns least residue of a (mod m)
Parameters
----------
a : int
denotes a in a (mod m)
m : int
denotes m in a (mod m)
return : int
returns integer least residue
"""
return a%m | a697656664fa11c64c32d8902ebce893b70f9203 | 73,633 |
import torch
def slerp(val, low, high):
"""Spherical interpolation. val has a range of 0 to 1."""
if val <= 0:
return low
elif val >= 1:
return high
elif torch.allclose(low, high):
return low
omega = torch.arccos(torch.dot(low/torch.norm(low), high/torch.norm(high)))
so... | fe0bfaab8db2bbff15b5f83077a47b60def1390f | 73,637 |
import hashlib
def md5sum(filename, blocksize=65536):
"""Generate md5 sum"""
hsh = hashlib.md5()
with open(filename, 'rb') as f_handle:
for block in iter(lambda: f_handle.read(blocksize), b''):
hsh.update(block)
return hsh.hexdigest() | b34f2fc913c3132094e04d5f347de8fc704a0dba | 73,638 |
def in_labelset(xmrs, nodeids, label=None):
"""
Test if all nodeids share a label.
Args:
nodeids: An iterable of nodeids.
label: If given, all nodeids must share this label.
Returns:
True if all nodeids share a label, otherwise False.
"""
nodeids = set(nodeids)
if la... | 1db07cd4f4a24a16ac5f06d09dbe65f9473da4b6 | 73,643 |
import itertools
def split_to_episodes(iterable, is_splitter):
"""
Split iterable into sub-lists with func is_splitter
:param iterable: The collection to operate on.
:param is_splitter: This func is to tell whether the current element is a splitter.
Splitter itself will ... | f5523a660a76af24e854c61635c47d4287667375 | 73,644 |
def get_prefrosh_and_adjacent(prefrosh_id, prefrosh_list):
"""Returns a prefrosh and the IDs of the neighboring two frosh in the provided list."""
idx, prefrosh = next(((idx, pf) for idx, pf in enumerate(prefrosh_list)
if pf['prefrosh_id'] == prefrosh_id))
prev_id = prefrosh_list[idx - 1]['prefrosh_... | b56199ad0bdb2ca532bdfcd456864ee59fdb90ba | 73,645 |
def get_bounding_straight_rectangle(points):
"""Given a list of points, determine the straight rectangle bounding all of them. Returns xywh."""
xs = [point[0] for point in points]
ys = [point[1] for point in points]
xmin, xmax = (min(xs), max(xs))
ymin, ymax = (min(ys), max(ys))
return xmin, ymin, xmax-xmin... | d498c96cef4d6d28648349077931e2f32d118564 | 73,649 |
import re
def _testname(filename):
"""Transform the file name into an ingestible test name."""
return re.sub(r'[^a-zA-Z0-9]', '_', filename) | af6acb345647eb78d40e3ef1c6b2750c8050b1ac | 73,651 |
def encode_bool(value):
"""Encode booleans to produce valid XML"""
if value:
return "true"
return "false" | 8079fc74cf184485f9cdeb02ea454265d5ed6d38 | 73,653 |
import hashlib
def _hash_key(k):
"""
Returns the input k (a large integer key) as a hashed byte array.
"""
return hashlib.sha256(str(k).encode()).digest() | 23b986478078a515f7ab711424fba2fad644bbd7 | 73,654 |
def _header2row_numbers(local_header, global_header):
"""Calculate local grid starting and ending rows in global grid
Return:
ind_top: the index of the top row
ind_bottom: the index of the bottom row
"""
y_bottom_gap = local_header['yllcorner']-global_header['yllcorner']
... | da198dc59e27cdc4eb862f7a47fe08d702eae856 | 73,656 |
def commission_low(q, p):
"""
ํ๊ตญํฌ์์ฆ๊ถ ์์๋ฃ(๋ฎ์ ๋)
:param q: (int) ๋งค์ ์ฃผ์ ์
:param p: (float) ๋งค์ ์ฃผ์ ๊ฐ๊ฒฉ
:return: (float) ์์๋ฃ + ์ธ๊ธ
"""
x = abs(q * p)
if q < 0:
tax = int(x * 0.003)
else:
tax = 0
return x * 0.00024164 // 10 * 10 + tax | ba14e427eef0f2c6e3b04b2bb525086bb3ceaad6 | 73,658 |
from typing import OrderedDict
def parse_re(input, target_re):
"""
Run re.findall with `target_re` regexp on given `input`
Return found targets as OrderedDict with float values.
parse_re("G0 S3 P0.1") = {'S': 3, 'P': 0.1}
"""
x = input.strip()
res = target_re.findall(x)
return Order... | f853f4355819a2d18e5f773817f32e3e83365dcc | 73,659 |
def _calc_rates(matrix, thresh):
"""Calculates true positive rate and false positive rate for a given threshold
Arguments:
matrix {np.ndarray} -- true labels and predicted probabilities
thresh {float} -- threshold for a round of ROC construction
Returns:
[float, float] -- true posi... | 5c94129cb5fb346d945adb76f0247edee75799cd | 73,660 |
def is_standardized(table, has_time=False, verbose=True):
""" Check if the table has the correct indices and the minimum required columns.
Args:
table: pandas DataFrame
Annotation table.
has_time: bool
Require time information for each annotation, i.... | 33f5ad6e774c93a2cf5f7a805486eba8e8964fdc | 73,664 |
def find_all_ind2(target, tokens):
"""
finds all appearances of a target phrase (could be multiple words, e.g. 'dark brown') within a list of tokens.
:param target: a String of the feature/country. E.g. 'dark brown', 'Italian wine', etc.
:param tokens: the List of tokens of the sentence to be looked at
... | 6e54a7e5706b0b3584d2ac46d34aa8fc4655e4e3 | 73,666 |
import six
def _to_reddit_list(arg):
"""Return an argument converted to a reddit-formatted list.
The returned format is a comma deliminated list. Each element is a string
representation of an object. Either given as a string or as an object that
is then converted to its string representation.
"""... | 7bc76a0142a1fb8fdcdb61f5b6f9947e83af9d43 | 73,671 |
def inRange(p,q,r):
"""
return true iff q is between p and r
"""
return ( (p <=q <= r) or (r<=q<=p) ) | 2243a41abab3c27c1c78062c6833296a11b2f9b7 | 73,673 |
import re
def clean_spaces(t):
"""Remove multiple spaces from a string"""
if t is None:
return t
return re.sub('\s+', ' ', t) | 3d57ea88d8a09ca3ca1afd910a67f6a297137c23 | 73,677 |
def mock_none(self, *args):
"""
For mocking various FTP methods that should return nothing for tests.
"""
return None | 8cbedd7396dfb123e2d620d4d8e6b478d22eeaff | 73,678 |
import itertools
def _powerset(iterable, minsize=0):
"""From the itertools recipes."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r in range(minsize, len(s) + 1)
) | 41c5576ae031288957d827d82231eab43f1ce70b | 73,679 |
def buffer_bbox(bbox_osm):
"""
Buffers a EPSG:4326 bounding box slightly to ensure covering the whole area of interest.
:param bbox_osm: array-like of four coordinates: miny, minx, maxy, maxx.
:return: array-like of four coordinates: miny, minx, maxy, maxx
"""
offset_lat, offset_lon = 0.02, 0.02... | e705351da7531a270ced4c504e4142388f99d59c | 73,684 |
def remove_chars(seq):
"""Remove all non digit characters from a string, but cleanly passthrough non strs.
Parameters
----------
seq : Any
Strings will be modified, any other type is directly returned
Returns
-------
Any
The original sequence, minus non-digit characters if ... | 6257da82d12f9f1b4a446b8ccc93436cbd24278a | 73,686 |
def time_warp(ts):
"""
>>> time_warp('1 2 3 4 5 5 2 3 3'.split(' '))
['1', '2', '3', '4', '5', '2', '3']
"""
ts = ts.split(' ')
result = []
most_recent_elem = None
for e in ts:
if e != most_recent_elem:
result.append(e)
most_recent_elem = e
retur... | d6d8471d017d13cee9b4e9e0f2bdf70c14bb314e | 73,687 |
def determinant(a, b, c, d, e, f, g, h, i):
"""Calculate the determinant of a three by three matrix.
Where the matrix contents match the parameters, like so:
|a b c|
|d e f|
|g h i|
"""
return a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g) | 2a923d076a2bd027905b1573215e15422ec791e6 | 73,689 |
def strip_prefix(s, prefix):
"""Remove prefix frm the beginning of s
is s = "some_something" and prefix = "some_", return "something"
if s is not a string return None
if prefix is not a string, return s
:param str s: string to modify
:param str prefix: prefix to remove
:rtype: Optional[str... | 747fa22d147cac883dd38b7a7d93a58191b5f2df | 73,694 |
def compute_finance_labels(df, shift=1):
"""
Computes labels of financial data.
Args:
df:
shift:
Returns: df with newly added label columns, nr. of labels
"""
n = len(df.columns)
df["label t"] = df["return"].apply(lambda x: 1. if x > 0 else 0.)
df["label t+1"] = df["r... | 631e20a329ad91661411e0f0216b830070e0970d | 73,705 |
import http
def build_status(code):
"""Transform a numeric code (200) in a HTTP status ('200 OK')."""
status = http.HTTPStatus(code)
return '{:3d} {}'.format(code, status.phrase) | 91b4eff1449756aa31d74d1cc63f230b1dcd6ea6 | 73,708 |
def read_config(filename):
"""Read the content of filename and put flags and values in a
dictionary. Each line in the file is either an empty line, a line starting
with '#' or an attribute-value pair separated by a '=' sign. Returns the
dictionary."""
file = open(filename, 'r')
config = {}
f... | 4659404f16a7b0d6f8a0f90c11df96c15c3e76d1 | 73,709 |
import logging
def _GetEffectiveVerbosity(verbosity):
"""Returns the effective verbosity for verbosity. Handles None => NOTSET."""
return verbosity or logging.NOTSET | 63825bc4c3e79412bb4d22c27108b17f0ac3e753 | 73,710 |
def get_value(testvalue):
"""Renders the correct value for the given TestValue."""
test = testvalue.test
return test.get_value(testvalue.value) | c6f57f5b468865196ff70c32d6c32cbfd6104ea1 | 73,714 |
import torch
def jitter_node_pos(pos_matrix, scale=1):
"""
Randomly jitter nodes in xyz-direction.
Args:
pos_matrix: matrix with xyz-node positions (N x 3).
scale: scale factor of jittering
"""
return pos_matrix + (torch.randn(*pos_matrix.shape).numpy() * scale) | 28234011a2f781569fab681d07d4ca6b9bec792b | 73,715 |
def setElements(data, inds, vals):
"""
Sets the elements in data specified by inds with the values in vals
Args:
data (ndarray): data to edit
inds (ndarray): indexes of data to access
vals (ndarray): new values to insert into the data
Returns:
ndarray: modified data
... | 5b8327ac3e95896988bd6626345a4726f36c921d | 73,717 |
def StrReverse(s):
"""Reverse a string"""
l = list(str(s))
l.reverse()
return "".join(l) | ec49f74ed9d526891e7d95cbdee249299972967d | 73,720 |
def get(obj, path, default=None):
"""Gets the value at path of object.
If the resolved value is undefined, the default value is returned
in its place.
Exampele:
>>> obj = { 'a': [{ 'b': { 'c': 3 } }] }
>>> get(obj, 'a.0.b.c')
3
Args:
obj (dict,list): The object to query.
... | 282d9ab669e11e032daebd8284a407aea5701781 | 73,721 |
def average(stats):
""" Compute the average of all values for the next structure:
{peer1: {block1: value11, block2: value2}, peer2: {...}, ...}
"""
total = 0
count = 0
for peer_stats in stats.itervalues():
total += sum(peer_stats.itervalues())
count += len(peer_stats)
ret... | 23645a0ebf9d61d68516ea88981012a28d18488b | 73,724 |
def parseInput(input):
"""
Converts an input string of integers into an array of integers.
"""
return [int(num) for num in input.split(',')] | 0d29a72c1c19b2703c6f736de5819cd58ab08d4d | 73,725 |
import re
def include_symbol(tablename, schema=None):
"""Exclude some tables from consideration by alembic's 'autogenerate'.
"""
# Exclude `*_alembic_version` tables
if re.match(r'.*_alembic_version$', tablename):
return False
# If the tablename didn't match any exclusion cases, return True
return Tr... | cb097a4b6a19c11bccc6dfc780a53431c505f36b | 73,727 |
def get_cve_context(cve_list):
"""
Prepare CVE context data as per the Demisto standard.
:param cve_list: cve list from response.
:return: List of cves dictionary representing the Demisto standard context.
"""
return [{
'ID': cve_dict.get('cve', ''),
'CVSS': cve_dict.get('baseSc... | 6122a666d42382acf845f819ceb58c1efe189b00 | 73,728 |
def reorder_correlator_inputs(input_map, corr_inputs):
"""Sort a list of correlator inputs into the order given in input map.
Parameters
----------
input_map : np.ndarray
Index map of correlator inputs.
corr_inputs : list
List of :class:`CorrInput` objects, e.g. the output from
... | 5d9ccacb60a8843f2a7a66e64ba474c8c9a31c65 | 73,730 |
def calculate_city_state_vol_delta(df):
"""
This function creates the specific market growth (city + state observation) rate using volume by doing the following:
1. Creates the city_state_growth_pop feature out of the total_mortgage_volume_pop
2. Creates the city_state_growth_nc feature out of the total... | 376bb79eef02fd9debba11cfb77380a11d245676 | 73,731 |
def factorial(n):
"""
calculate the factorial n!
"""
if (n>1):
return n*factorial(n-1)
return 1 | fa4194ba29d4193af6857caa4286d2ed45b7ba1c | 73,733 |
def capture_current_size(thread_list, recorded):
"""
Amount captured so far is the sum of the bytes recorded by warcprox,
and the bytes pending in our background threads.
"""
return recorded + sum(getattr(thread, 'pending_data', 0) for thread in thread_list) | 90d988c7bc37fb4cc5a7c357baf28f425e389cfe | 73,735 |
def join_uri_paths(prefix, suffix):
"""
Returns the uinion of two URI path strings without creating a double '/'
between them.
\param prefix The left side of the path,
\param suffix The sub-path,
\return Combination of the two strings sans '//' in the middle.
"""
... | 0be6cbe82b721f997d6a459c50e52238c740f191 | 73,736 |
def _decode_mask(mask):
"""splits a mask into its bottom_any and empty parts"""
empty = []
bottom_any = []
for i in range(32):
if (mask >> i) & 1 == 1:
empty.append(i)
if (mask >> (i + 32)) & 1 == 1:
bottom_any.append(i)
return bottom_any, empty | 6b93a30881ed526e801b4ad55c4a04af5562d8b6 | 73,741 |
def _get_content_type_header(request):
"""
Get the content type from the request. Return an empty dict if it is not set
Args:
request (HTTPRequest): The HTTP request
Return:
a dict containing the content type
"""
try:
return {'Content-Type':request.META['CONTENT_TYPE']... | 99aae9764a7afcd1b9c7446d8808d2029baa9a43 | 73,743 |
from typing import Iterable
def generate_dropdown_options(values: Iterable[str]):
"""
Generates Dropdown options from a list
Parameters
----------
values : Iterable[str]
Iterable with the option values
Returns
-------
Dict
Options for the Dropdown
"""
options ... | 9675e574c6139635cd97ebae7a50185fc8c47deb | 73,744 |
def shorten_name(name, max_length = 10):
"""
Makes a string shorter, leaving only certain quantity of the last characters, preceded by '...'.
@param name: The string to shorten.
@param max_length: Maximum length of the resulting string.
@return: A string with max_lenght characters plus '...'
"... | 77fc27581bf9324797d3ccfbf25edd94f4db0990 | 73,745 |
def decode_uint40(bb):
"""
Decode 5 bytes as an unsigned 40 bit integer
Specs:
* **uint40 len**: 5 bytes
* **Format string**: 'j'
"""
return int.from_bytes(bb, byteorder='little') | 8d241b5052751cfa39b1384c747f260583227fa5 | 73,748 |
def sum_right_most(x, ndim):
"""Sum along the right most `ndim` dimensions of `x`,
Parameters
----------
x : Tensor
Input tensor.
ndim : Int
Number of dimensions to be summed.
Returns
-------
Tensor
"""
if ndim == 0:
return x
axes = list(range(-ndim,... | c6d4eb6a2070e9806ba7e358cc8d08750515f369 | 73,762 |
def fill_dict(new_dict, mean, adj, degree):
"""
Create dictionary entry to store in .toml
Parameters
----------
new_dict : Dictionary object
mean : Mean vector
adj : Adjacency matrix
degree : Degree matrix
Returns
-------
new_dict : Filled up dictionary entry
"""
n... | 1b0202d28529ad9401c2059f35a666f5c0427983 | 73,765 |
def get_body(b2_world, index):
""" get the body in a given position
:param b2_world: an handler to a b2World object
:type b2_world: b2World reference
:param index: the index in the json list of joints
:type index: integer
:return: the body in the given position
:rtype: b2Body
"""
... | 5663138880efc7dc51e3cc65323eed7c88a03047 | 73,768 |
import re
from typing import Optional
def status_detector(
phrase: str,
stop_patt: re.Pattern,
ne_list: list
) -> Optional[str]:
"""Detects status based on given phrase
Args:
phrase: phrase string
stop_patt: Regex pattern for stop words
ne_list: list of named entities
... | 87690f4fe9b88d5eca4d454e0fb13c790a409b6b | 73,775 |
def sub2ind(shape, row_sub, col_sub):
"""
Return the linear index equivalents to the row and column subscripts for
given matrix shape.
:param shape: Preferred matrix shape for subscripts conversion.
:type shape: `tuple`
:param row_sub: Row subscripts.
:type row_sub: `list`
:param col_su... | bd3e640171f23f80c21a66c92e4d5e3292cddea7 | 73,776 |
def parse_command_line_parameters(parser):
"""
@brief Parses the command line parameters provided by the user and makes
sure that mandatory parameters are present.
@param[in] parser argparse.ArgumentParser
@returns an object with the parsed arguments.
"""
msg = {
'... | f79b016118cb818893e484c6902c45f817a3d58a | 73,777 |
def get_user_choice(message, options):
"""User Interaction: Input string message and list of options, returns user choice"""
choice = input(message + " ("+"/".join(map(str, options))+") :").lower()
while choice.lower() not in options:
choice = get_user_choice(message, options)
return choice | 3ac387443ff006b47182bba8a64cd582e6732f77 | 73,785 |
def are_multisets_equal(x, y):
"""Return True if both vectors create equal multisets.
input:
x, y -- 1-d numpy arrays
output:
True if multisets are equal, False otherwise -- boolean
Not vectorized implementation.
"""
x.sort()
y.sort()
n = len(x)
m = len(y)
... | ee911bfacb805ca132d48492d46c12eb558e7f9d | 73,789 |
def _sort_tag_version(release_data: dict) -> tuple:
"""Sort a list of releases by tag version."""
return tuple(int(x) for x in release_data["tag_name"].lstrip("v").split(".")) | 709466a10071a3513ebc431b8b1906bf84caf791 | 73,791 |
def _parse_header_row(row, **options):
"""Parse the header row of a table.
If a column spans multiple cells, then duplicate values are returned
for each. Duplicated columns are appended with ``suffix`` and index
for each repeat.
Parameters
----------
row : BeautifulSoup Tag object
... | 7cf011da337443d7501ecb4cf8fee68b4c3dca70 | 73,792 |
def get_api_url(account):
"""construct the tumblr API URL"""
global blog_name
blog_name = account
if '.' not in account:
blog_name += '.tumblr.com'
return 'http://api.tumblr.com/v2/blog/' + blog_name + '/posts' | 10efd015940e7afee6173a5cd37560b0e1f4d8da | 73,793 |
def xml_elements_equal(first, second):
"""
Tests two XML elements for equality.
Parameters
----------
first : _Element
The first element.
second : _Element
The second element.
Returns
-------
bool
Whether the two elements are equal.
"""
if first.tag ... | 7dd500c7d0ff795aa6c7dd2ab0c1078738089235 | 73,794 |
import yaml
def get_config(path: str) -> dict:
"""Open a yaml file and return the contents."""
with open(path) as input_file:
return yaml.safe_load(input_file) | 3ba743e2a699aafa972a2dfcde0c9257408cd0fd | 73,795 |
def find_smallest_positive(items) -> int:
"""
Returns the smallest positive integer that does not exist in the given int array.
:param items: array of ints
:return: the smallest positive int not in the array
"""
# Create boolean array to hold if an integer is found
# Maps index of array to the integer in items
... | 3a8fb34314303a4828af170741f8e9ba58deac49 | 73,801 |
from typing import Type
import pydantic
def get_pydantic_base_orm_config() -> Type[pydantic.BaseConfig]:
"""
Returns empty pydantic Config with orm_mode set to True.
:return: empty default config with orm_mode set.
:rtype: pydantic Config
"""
class Config(pydantic.BaseConfig):
orm_mo... | ef3927339cbccf1ccaa88c9422d1004f0f3ffac3 | 73,803 |
def INK(n):
"""
Returns control codes to set the ink colour (0-7).
Use this in a ``PRINT`` or ``SET`` command. Example:
``PRINT("normal",INK(1),"blue",INK(2),"red")``
Args:
- n - integer - the ink colour (0-7)
"""
return "".join((chr(16),chr(int(n)))) | 6cc3962ec4a6906668c4e2a703c41e99d1e4a175 | 73,805 |
def create_window(name, title, message, options=None, required=None, active=True, window_type="FORM"):
"""
Returns a window `dict` to be used by lottus
:param name `str`: name of the window
:param title `str`: title of the window
:param message `str`: message of the window
:p... | 3bdb6614541b787c2999ce529433ee207aaa5b87 | 73,808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.