content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import string
def base_encode(number, alphabet=string.ascii_lowercase, fill=None):
"""Encode a number in an arbitrary base, by default, base 26. """
b = ''
while number:
number, i = divmod(number, len(alphabet))
b = alphabet[i] + b
v = b or alphabet[0]
if fill:
return ... | 6194e6730f2022f8f9e2feffea8d51997ac2e93f | 677,610 |
def aXbXa(v1, v2):
"""
Performs v1 X v2 X v1 where X is the cross product. The
input vectors are (x, y) and the cross products are
performed in 3D with z=0. The output is the (x, y)
component of the 3D cross product.
"""
x0 = v1[0]
x1 = v1[1]
x1y0 = x1 * v2[0]
x0y1 = x0 * v2[1]
... | fb59030dc3cd0a8073dc17f34b4185ec4ca2e437 | 677,611 |
def epoch_init(M, i, j, w):
"""
Initialize epoch index from daily period, day of week and week of cycle.
:param M: Model
:param i: period of day
:param j: day of week
:param w: week of cycle
:return: period of cycle in 1..n_prds_per_cycle
"""
return (w - 1) * M.n_days_per_week() * M... | 4d97b93c18131f06635f636c94ecc79a12e43f1e | 677,613 |
def expose( func ):
"""
Decorator: mark a function as 'exposed' and thus web accessible
"""
func.exposed = True
return func | 076f168d0a78092c427e544374b221c885f99959 | 677,617 |
def GetEndOfBlock(code, end_op):
"""Get the last line of block."""
"""It returns -1 if it can't find."""
for i in code:
if end_op in i:
return code.index(i)
else:
return -1 | 4edfa1ece719fb0d7b90913bed88b03b6ffb7ad0 | 677,622 |
def response(context):
"""Shortcut to the response in context"""
return context.response | 63fd6b29602183f2d4f88a4f6f5eb30bc37e8a10 | 677,625 |
def street_address(anon, obj, field, val):
"""
Generates a random street address - the first line of a full address
"""
return anon.faker.street_address(field=field) | 78c801c813e2245c64b3902e03c09baac3429255 | 677,632 |
def ABCD_eq(b,c,d):
"""
Basic estimator formula for count in 'A' (signal domain)
DEFINITION: A = B x C / D
^
|C | A
|-----
|D | B
0------>
"""
return b * c / d | 1d74b935ac7e406eb52b23e07af2eb5623f84790 | 677,633 |
def decode_text_from_webwx(text):
"""
解码从 Web 微信获得到的中文乱码
:param text: 从 Web 微信获得到的中文乱码
"""
if isinstance(text, str):
try:
text = text.encode('raw_unicode_escape').decode()
except UnicodeDecodeError:
pass
return text | 3e433086fafbaa712e194d2a294dbf3e218549db | 677,634 |
def nested(path, query, *args, **kwargs):
"""
Creates a nested query for use with nested documents
Keyword arguments such as score_mode and others can be added.
"""
nested = {
"path": path,
"query": query
}
nested.update(kwargs)
return {
"nested": nested
} | a0dcdc8df4d765c494b05d9b112cf3f58779145f | 677,635 |
def __get_service_names(scenario_config):
"""
Gets the list of services from the scenario config.
If no services are given, an empty list is returned.
:param scenario_config: The scenario config.
:return: A list of services. [] if no service names are found.
"""
if 'services' in scenario_con... | ff266e479153478cf548ada8e2a862bf74e2cbc1 | 677,636 |
def float_range(start, stop=None, step=None):
"""Return a list containing an arithmetic progression of floats.
Return a list of floats between 0.0 (or start) and stop with an
increment of step.
This is in functionality to python's range() built-in function
but can accept float increments.
A... | 0d6299284ebd29f57e7b400305cc06874fd93119 | 677,638 |
def attendance_numbers(brother, events, accepted_excuses):
""" Returns the a of the row of the attendance csv containing information about the brother and his
attendance at events
:param Brother brother:
the brother whose information you need the count for
:param list[Event] events:
th... | dfdd5e233a1d1ec996061c11b8d999a5118a5316 | 677,642 |
from typing import Optional
def _find_month_number(name: str) -> Optional[int]:
"""Find a month number from its name.
Name can be the full name (January) or its three letter abbreviation (jan).
The casing does not matter.
"""
names = ['january', 'february', 'march', 'april',
'may', '... | df3e932badb9140e6c6a22c3be897ca9da978b7e | 677,643 |
def move_down(rows, t):
""" A method that takes number of rows in the matrix
and coordinates of bomb's position and returns
coordinates of neighbour located bellow the bomb.
It returns None if there isn't such a neighbour """
x, y = t
if x == rows:
return None
else:
return (... | 486f19fd235cd506cca7dbdca64e32a25b7939c7 | 677,647 |
def get_domain(domain_table):
"""
A helper function to get the domain for the corresponding cdm domain table
:param domain_table: the cdm domain table
:return: the domains
"""
domain = domain_table.split('_')[0].capitalize()
return domain | 97e447af7fdf842086d54d93931c6ed45ddf4b0e | 677,651 |
def _particular_antigen_comp(donor: int, recipient: int) -> tuple:
"""Returns a particalar antigen compatibility, where each tuple member
marks a compatibility for a particular antigen (A, B, Rh-D).
If tuple member is non-negative there is a compatibility.
For red blood cell compatibility is required t... | 90d3b07823998126c64e03350bbf6453ef0e6e70 | 677,658 |
def fmt_price(amt):
""" Format price as string with 2 decimals """
return '{:,.2f}'.format(amt) | 03c36c1d297f26d173bb5d325e9be45c406ac8c7 | 677,659 |
def adjust_data(code_list, noun=12, verb=2):
"""Set the computer to a desired state by adjusting the noun and verb
parameters.
Parameters
----------
code_list : list
opcode as provided by advent of code
noun : int, optional
the first parameter (in position 1), by default 12
... | 56af12bd7c6c3a9e8b0da6c04db8f74604be9c72 | 677,660 |
def computeblocksize(expectedrows, compoundsize, lowercompoundsize):
"""Calculate the optimum number of superblocks made from compounds blocks.
This is useful for computing the sizes of both blocks and
superblocks (using the PyTables terminology for blocks in indexes).
"""
nlowerblocks = (expecte... | 8d6db73e30fe3659be5e5073fffc374ce8292631 | 677,662 |
def is_mirrored(rot):
"""
Return True if an eaglexml rotation is mirrored.
"""
return rot and rot.startswith('M') | 9673e58397604f4faa148e65cf6507d17d131ed1 | 677,664 |
def WritePacketRaw(header, data):
"""
Given two raw bytearrays, return a bytearray representing the entire packet
"""
return header + data | 476749834ac680505863c2876f991f6f0e46385b | 677,666 |
def total_velocity(vel_l, vel_r):
"""
calculate total velocity
- given left and right velocity
"""
return (vel_l + vel_r) / 2 | 86cec75ef2b5fc32fe57952bde8bce82ffd9fe25 | 677,670 |
def get_role(obj, role_name):
"""Return a Role if the specified object has the specified role."""
for role in obj.roles:
if role.name == role_name:
return role
return None | 4a93748625e51b11e66311f420efe888fd4e6f14 | 677,671 |
def parse_operand_subscripts(subscript, shape, op_label_dict):
"""Parse the subscripts for one operand into an output of 'ndim' labels
Parameters
----------
subscript : string
the subscript of the operand to be parsed.
shape : tuple of int
the shape of the input operand
op_label... | 05cb74d6fe8b6f8583ba87da4fadaeddd4571eea | 677,673 |
from typing import Union
def atoi(text: str) -> Union[int, str]:
"""
Converts strings to integers if they're composed of digits; otherwise
returns the strings unchanged. One way of sorting strings with numbers;
it will mean that ``"11"`` is more than ``"2"``.
"""
return int(text) if text.isdig... | 7fdea41e41d4a6140e69f21f6d83ffc8ff757f7e | 677,679 |
def word_to_list(rw):
"""Convert the ran_word string into a list of letters"""
word = list(rw)
return word | 9a7f9ba1a5715b6f490d257e8225ccecd24c43ed | 677,680 |
import pickle
def load_pickle(byte_file):
"""Loads a pickled object"""
with open(byte_file, "rb") as f:
return pickle.load(f) | 932f376bcd3a79398c600056fd327d5b54951e43 | 677,683 |
def package(qualified_name):
"""Return the enclosing package name where qualified_name is located.
`qualified_name` can be a module inside the package or even an object
inside the module. If a package name itself is provided it is returned.
"""
try:
module = __import__(qualified_name, from... | 91740fa2adfa37868c42144b47bf79617d23d3b9 | 677,689 |
def indent(text, chars=" ", first=None):
"""Return text string indented with the given chars
>>> string = 'This is first line.\\nThis is second line\\n'
>>> print(indent(string, chars="| ")) # doctest: +NORMALIZE_WHITESPACE
| This is first line.
| This is second line
|
>>> print(indent(... | a33fb6ca99b916ec4fe2899434fe31589fd98f6a | 677,690 |
def users_from_passwd(raw):
""" Extracts a list of users from a passwd type file. """
users = list()
for line in raw.split('\n'):
tmp = line.split(':')[0]
if len(tmp) > 0:
users.append(tmp)
return sorted(users) | 7d061146666ff75e1800285a6e3d153848c79312 | 677,691 |
def product(l1, l2):
"""returns the dot product of l1 and l2"""
return sum([i1 * i2 for (i1, i2) in zip(l1, l2)]) | 64c11575b4bfa50c035ebf965e6edfe9f07cd1a1 | 677,693 |
import requests
def analyzeImg(imgResp, apiKey):
"""
Sends encoded image through Microsoft computer vision API to get tags and categories.
Args:
imgResp: image response from urlopening webcam image
apiKey: Computer Vision API key
Returns:
json object with 'categories' and 'tags' as keys
"""
headers = {
... | a0f020e4af9e6cabe8015bb03f0fad05966dbfaf | 677,695 |
def sum_items(a_list):
"""
@purpose Returns the sum of all items in a_list, and return 0 if empty list
@param
a_list: a list of items passed to this function to sum
@complexity:
Worst Case - O(N): When summing all values of a list with N items
Best Case - O(1): when passing empty... | 25f86f92ca0eedf29b9b7e8a1d8bcf4b4c024370 | 677,697 |
def parse_distance(distance):
"""parse comma delimited string returning (latitude, longitude, meters)"""
latitude, longitude, meters = [float(n) for n in distance.split(',')]
return (latitude, longitude, meters) | 954ef035e5aa5fa7965285622b5916ac1d51ac99 | 677,698 |
def find_pivot(array, high, low):
"""
Find the index of the pivot element
"""
if high < low:
return -1
if high == low:
return low
mid = (high + low)/2
if mid < high and array[mid] > array[mid + 1]:
return mid
if mid > low and array[mid] < array[mid - 1]:
return mid - 1
if array[low] >= array[mid]... | 8c55a377d1b518d0f9b85259088756ec2c67b172 | 677,699 |
import requests
import shutil
def download_file(url, local_file, *, allow_redirects=True, decode=True):
"""
Download a file.
Arguments:
url (str): URL to download
local_file (str): Local filename to store the downloaded
... | 173976c4581c2c437a4efec682abc0e4bb9dcda4 | 677,703 |
def pdf2cte(terms_table, table_name):
"""Generate SQL code to represent Pandas DataFrame as a Common Table Expression"""
quotify = lambda c: c # '[' + c + ']'
row2tuple_str = lambda row: '(' + ', '.join([ f"'{x}'" if (isinstance(x, str) or isinstance(x, bool)) else str(x)
... | 8dcd636a7b87712e48691d71f2798f82b071203f | 677,704 |
def always_roll(n):
""" Возвращает стратегию, по которой всегда происходит N бросков.
>>> strategy = always_roll(5)
>>> strategy(0, 0)
5
>>> strategy(99, 99)
5
"""
def strategy(score, opponent_score):
return n
return strategy | 7f6489a64dcb525a1467763cb68521bb37fefb35 | 677,705 |
def _get_stream_timestamps(stream: dict):
"""Retrieve the LSL timestamp array."""
return stream["time_stamps"] | 95dca853abfcd01e2baca49d3328a9414e102d3c | 677,710 |
def newline_space_fix(text):
"""Replace "newline-space" with "newline".
This function was particularly useful when converting between Google
Sheets and .xlsx format.
Args:
text (str): The string to work with
Returns:
The text with the appropriate fix.
"""
newline_space = '... | ed98677531545f869a649605f205bad6c862f453 | 677,711 |
def is_checkpoint_epoch(cfg, cur_epoch):
"""Determines if a checkpoint should be saved on current epoch."""
return (cur_epoch + 1) % cfg.TRAIN.CHECKPOINT_PERIOD == 0 | 64a05257bc616ef9fe2c53078c0607134923f868 | 677,712 |
def getCommand(gameCounter: int):
"""Allows the gamer to enter a command from the console."""
return input("Dynasty (" + str(gameCounter) + ") > ") | 8eedb7a631055b4efe28e08e399c44d87467bd97 | 677,714 |
def hide_axis(ax, axis='x', axislabel=True, ticklabels=True, ticks=False,
hide_everything=False):
""" Hide axis features on an axes instance, including axis label, tick
labels, tick marks themselves and everything. Careful: hiding the ticks
will also hide grid lines if a grid is on!
Para... | 11160c6f928a8b5befd4a20cbd04f97a5f6dfae0 | 677,715 |
import math
def roundup(x, to):
"""Rounding up to sertain value
>>> roundup(7, 8)
>>> 8
>>> roundup(8, 8)
>>> 8
>>> roundup(9, 8)
>>> 16
:param x: value to round
:param to: value x will be rounded to
:returns: rounded value of x
:rtype: int
"""
return int(math.cei... | c15e4a5a751a428ee395fc96ee4845a95b3432f4 | 677,722 |
def getWaterYear(date):
""" Returns the water year of a given date
Parameters
----------
date : datetime-like
A datetime or Timestamp object
Returns
-------
wateryear : string
The water year of `date`
Example
-------
>>> import datetime
>>> import wqio
... | 5d81878833325337a652d4178ad22b5b566ef296 | 677,723 |
def find_collNames(output_list):
"""
Return list of collection names collected from refs in output_list.
"""
colls = []
for out in output_list:
if out.kind in {"STEP", "ITEM"}:
colls.append(out.collName)
elif out.kind == "IF":
colls.append(out.refs[0].collName... | cfcd9a8d8343009b09758a075b6b98a98a3ac0ea | 677,724 |
def session_new_user_fixture(session_base):
"""Load the new user session payload and return it."""
return session_base.format(user_id=1001) | 12202eb76eb05b840f2c20197978bf009a1eab4e | 677,725 |
def collator(batch_list):
"""
Collate a bunch of multichannel signals based
on the size of the longest sample. The samples are cut at the center
"""
max_len = max([s[0].shape[-1] for s in batch_list])
n_batch = len(batch_list)
n_channels_data = batch_list[0][0].shape[0]
n_channels_targe... | 17015efa3acede877d88a53ce24e6812997e17c1 | 677,729 |
def _rel_approx_equal(x, y, rel=1e-7):
"""Relative test for equality.
Example
>>> _rel_approx_equal(1.23456, 1.23457)
False
>>> _rel_approx_equal(1.2345678, 1.2345679)
True
>>> _rel_approx_equal(0.0, 0.0)
True
>>> _rel_approx_equal(0.0, 0.1)
False
>>> _rel_approx_equal(... | d25520d23cd3ace60d668dd41a12a3c0f09b697c | 677,732 |
def get(obj: dict, path, default=None):
"""Gets the deep nested value from a dictionary
Arguments:
obj {dict} -- Dictionary to retrieve the value from
path {list|str} -- List or . delimited string of path describing path.
Keyword Arguments:
default {mixed} -- default value to retur... | ff1a3e9548af68046864b79c8afd839d7cd99907 | 677,738 |
def dict_is_song(info_dict):
"""Determine if a dictionary returned by youtube_dl is from a song (and not an album for example)."""
if "full album" in info_dict["title"].lower():
return False
if int(info_dict["duration"]) > 7200:
return False
return True | b4792a850be39d4e9dc48c57d28d8e4f50751a75 | 677,740 |
import socket
import ipaddress
def forward_lookup(hostname):
"""Perform a forward lookup of a hostname."""
ip_addresses = {}
addresses = list(
set(str(ip[4][0]) for ip in socket.getaddrinfo(hostname, None))
)
if addresses is None:
return ip_addresses
for address in addresses... | 1184ed5894c660efff88c9cf5910ce7864af30ed | 677,749 |
def pots_to_volts(calibration_data):
"""Convert the potentiometer data units to volts.
Parameters
----------
calibration_data : dict
All of the digital (DIO) and analog data corresponding to the trodes
files for the a calibration recording. For example, as returned by
read_data... | b33bc729032797cbc04545dd0faa1584329ebba0 | 677,754 |
import re
def walltime_seconds(walltime):
"""Given a walltime string, return the number of seconds it represents.
Args:
walltime (str): Walltime, eg. '01:00:00'.
Returns:
int: Number of seconds represented by the walltime.
Raises:
ValueError: If an unsupported walltime forma... | 96b4ecda6231ae50948f44fdc99f8adced391e30 | 677,756 |
def arange(start, end, step=1):
"""
arange behaves just like np.arange(start, end, step).
You only need to support positive values for step.
>>> arange(1, 3)
[1, 2]
>>> arange(0, 25, 2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
>>> arange(0, 1231, 34)
[0, 34, 68, 102, 136, 170... | a7278e1773a25db638662f6572b0fd6e3fcfef31 | 677,763 |
def get_domain_id(ks_client, domain_name):
"""Return domain ID.
:param ks_client: Authenticated keystoneclient
:type ks_client: keystoneclient.v3.Client object
:param domain_name: Name of the domain
:type domain_name: string
:returns: Domain ID
:rtype: string or None
"""
all_domains... | df07d3a957cc520d180131b1475fadec8e5fa6cf | 677,767 |
def clean_aliases(aliases):
"""
Removes unwanted characters from the alias name.
This function replaces:
-both '/' and '\\\\' with '_'.
-# with "", as it is not allowed according to the schema.
Can be called prior to registering a new alias if you know it may contain such unwanted
char... | 57fe5734b8912e17139e09d54d8ab7a45d121539 | 677,770 |
import click
def validate_fragment_type(ctx, param, value):
"""
Validate that a given fragment type exists.
"""
config = ctx.obj.config
if value and not config.has_fragment_type(value):
raise click.BadParameter(
'Missing or unknown fragment type: {}'.format(value))
return v... | 71b206c629037a6d6fa4a0441401803fd8ff6c46 | 677,771 |
def _key_in_string(string, string_formatting_dict):
"""Checks which formatting keys are present in a given string"""
key_in_string = False
if isinstance(string, str):
for key, value in string_formatting_dict.items():
if "{" + key + "}" in string:
key_in_string = True
... | 706beaa06973b5071ecdbf255be83ee505202668 | 677,773 |
def compare_two_model_index(index_1, index_2):
"""
If the two input index's row and column and their parent is equal, then they are equal for test.
"""
return (index_1.row() == index_2.row()) \
and (index_1.column() == index_2.column()) \
and (index_1.parent() == index_2.parent()) | 5f199812456ae74d2a65528610ca752a2771aad1 | 677,775 |
import json
def get_json_from_file_path(path):
"""
Get the content of the json file and convert it into an object
"""
f = None
result = None
# noinspection PyBroadException
try:
f = open(path, "r", encoding="utf-8")
json_str = f.read().strip()
result = json.loads(js... | 7cd67f4ffd9d583f203e46499ab45ac0667eab67 | 677,777 |
from typing import List
def connect(
graph: List[List[int]], next_ver: int, current_ind: int, path: List[int]
) -> bool:
"""
Memeriksa apakah mungkin untuk menambahkan
berikutnya ke jalur dengan memvalidasi 2 pernyataan
1. Harus ada jalan antara titik saat ini dan berikutnya
2. Vertex berikutn... | 7b80205496c99ea86b2f83fd7efa6be81eb2784e | 677,785 |
def addr_alignment(addr):
"""Compute the maximum alignment of a specified address, up to 4."""
return addr & 1 or addr & 2 or 4 | 407c937e97807fa6a4f4c3ad7f966145606de15c | 677,788 |
def get_entry_ids(entry):
"""Creates a trakt ids dict from id fields on an entry. Prefers already populated info over lazy lookups."""
ids = {}
for lazy in [False, True]:
if entry.get('trakt_movie_id', eval_lazy=lazy):
ids['trakt'] = entry['trakt_movie_id']
elif entry.get('trakt_... | a86116cdb84154ae80938f854ccc049be5c928f2 | 677,790 |
def add(number_x: int, number_y: int):
"""Adds two numbers."""
return number_x + number_y | 70a8f017e84fa1d49afdbc793f34f3b61d63a64a | 677,791 |
def get_instances_for_service(service_id: str, client) -> list:
""" Returns list of registered instance for service with id <service_id>"""
return client.list_instances(ServiceId=service_id).get('Instances', []) | 7e19bd2c85a51671eebb7e31a211f453c2bf2823 | 677,792 |
def check_insertion_order(metadict_inst, expected):
"""
Ensure that the keys of `metadict_inst` are in the same order as the keys
in `expected`.
The keys case is ignored.
"""
def normalise_keys(lst_pairs):
return [key.lower() for key, _ in lst_pairs]
assert normalise_keys(metadict_... | a6ec3e30b2c743ae8c03441884325a8c1d22346b | 677,793 |
def diagonal(matrix, reverse=False):
""" Return matrix' diagonal (count from the the back if reverse = True). """
diag = 0
if not reverse:
for i in range(len(matrix)):
diag += matrix[i][i]
else:
for i in range(len(matrix)):
diag += matrix[i][(len(matrix) - 1) - i]... | c67f8a3698e82a15dba2316891a0783d72a279e0 | 677,795 |
def flatten_whois(whois_record):
"""
Flattens a whois record result
Args:
whois_record (dict): A WHOIS record
Returns:
dict: A flattened WHOIS result
"""
flat_whois = dict()
flat_whois["domainName"] = whois_record["domainName"]
if "createdDate" in whois_record:
f... | de5c1f480646bcbfc7e409b995c18baaadbe0ef3 | 677,797 |
def rc_prescription_from_pm_and_imc(efl, f_pm, pm_vertex_to_focus):
"""Design a Ritchey-Chrétien telescope from information about its primary mirror.
Parameters
----------
efl : float
system effective focal length
f_pm : float
focal length of the primary mirror (should be negative)
... | 3f4f1b4b02a5b5d9f1105f446c51df79de02bf67 | 677,801 |
from typing import Union
from pathlib import Path
import csv
def _preprocess_csv(file_path: Union[str, Path], delimiter: str):
"""Validates a CSV file and returns the data as a list of lists"""
if isinstance(file_path, str):
file_path = Path(file_path)
if not file_path.exists():
raise Val... | fe06f35872ae2e139d3fdef5ad6b5d1345c54e5b | 677,802 |
def remove_comment(line):
"""
与えられた文字列の"::"以降(右)を除去する
Args:
line: コメントを取り除きたい文字列
Return:
先頭がコメントだった場合(コメントのみの行だった場合): 空文字
それ以外: コメント部分を取り除いた文字列
"""
return "" if line.index("::") == 0 else line.split("::")[0] | 36e2e86b25e5c35162eeb6ac1e4bcb3ada7faa68 | 677,803 |
def _getitem_from_frame(f_locals, key, default=None):
"""
f_locals is not guaranteed to have .get(), but it will always
support __getitem__. Even if it doesnt, we return ``default``.
"""
try:
return f_locals[key]
except Exception:
return default | 1a6e3b55d553e9febc3bf4a28e2fd34c9fb193c5 | 677,809 |
def get_edges(graph: dict) -> set:
"""
Return a set of couples that represents all of the edges.
@input: graph (graph stored in an adjacency list where each vertex is
represented as an integer)
@example:
>>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]}
>>> get_edges(graph)... | 233503494ef8778affc50c99394643d518184944 | 677,812 |
import random
def SampleNegativeEdges(graph, num_edges):
"""Samples `num_edges` edges from compliment of `graph`."""
random_negatives = set()
nodes = list(graph.nodes())
while len(random_negatives) < num_edges:
i1 = random.randint(0, len(nodes) - 1)
i2 = random.randint(0, len(nodes) - 1)
if i1 == ... | d8676927708b2fc5b7bd70948502573272766319 | 677,813 |
def split_train_test(data, test_data_size: int):
"""Splits data into train and test.
Args:
data: All data.
test_data_size: Size of the `test` data.
Size of the `train` will be `len(data) - test_data_size`.
"""
train_data = data[:-test_data_size]
test_data = d... | 1217d69d365ba170090a79427ebf96da6922feeb | 677,814 |
def _is_dictionary(arg):
"""Check if argument is an dictionary (or 'object' in JS)."""
return isinstance(arg, dict) | fce225835c14d56206ed88d77abf3cd09bcda5f3 | 677,819 |
def _weight(entry):
"""
Sum a power of frequency.
Word frequencies have a skew with a long tail toward infrequent.
"""
weight = 500 * entry[0] ** 0.25
for i in range(3, len(entry), 2):
weight -= (entry[i] / 100.0) ** 4 * 100
return weight | ed47a0aee91c3ef444a1805083411397b8fc7ec3 | 677,821 |
def split_nums_chars(str_: str) -> tuple[str, str]:
"""Splits the numbers and characters from a string
Args:
str_: The string to split
Returns:
A tuple containing the characters and the numbers
"""
nums = "".join([i for i in str_ if i.isnumeric()])
chars = "".join([i for i in s... | 0907953184aabef7d3052af27385482ac087fb7d | 677,822 |
def capitalize(text: str) -> str:
"""
Capitalize the first letter only.
>>> capitalize("")
''
>>> capitalize("alice")
'Alice'
>>> capitalize("BOB")
'BOB'
>>> capitalize("alice and bob")
'Alice and bob'
"""
if not text:
return ""
... | cfd13ed974538f8d44b654ca087735fbae3e1c40 | 677,824 |
def TestSuiteName(test_key):
"""Returns the test suite name for a given TestMetadata key."""
assert test_key.kind() == 'TestMetadata'
parts = test_key.id().split('/')
return parts[2] | dded191605b6e3738b3e314a0b744d02995ceb85 | 677,827 |
from typing import Any
import pickle
def deserialize(input_file: str) -> Any:
"""
Load data stored by ``serialize()``.
:param input_file: path to file when data was stored by serialize()
:return: list of objects
"""
with open(input_file, "rb") as f:
return pickle.load(f) | 18a65ea672abb54ca54e28bd09cd6b6e5ccdf6f7 | 677,829 |
def _make_compound_key(table, key):
"""Returns a list of columns from `column_key` for `table` representing
potentially a compound key. The `column_key` can be a name of a single
column or list of column names."""
if not isinstance(key, (list, tuple)):
key = [key]
return [table.columns[nam... | 5f75c40f79a94bef9fca1a5a2bb2e5d5100b44e6 | 677,831 |
def get_region(regions, cluster):
""" Gets the region name from the cluster ID
Args:
regions (dictionary): dictionary of regions where shortname is the key to the long name value.
cluster (str): the OCI ID of the cluster in question.
Returns a string of the region long name.
"""
re... | 88498615c4f5a1b5a16e7be64d0aec57278889c5 | 677,832 |
def convert_lanes_to_edges(lanes):
"""
Convert lanes (iterable) to edges (iterable).
Remove lane index from the end and then remove duplicates while retaining order.
Also works with single lane str.
>>> lanes
>>> ['1175109_0', '1175109_1', '1175109_2', '1183934_0', '1183934_1', '1183934_2']... | 3e37b7847d3519dfaf8f07e5ced090151a6f6944 | 677,834 |
def load_blob(reader):
"""Given a reader object, such as returned by ExtBoar.get_blob(),
fetches all the blocks and returns the reconstructed
data. Warning: this means the whole blob will be loaded into
RAM."""
return "".join(reader) | 5267971fb731d3c86de93d88482633dbbaf55127 | 677,835 |
def window_landmark(region, flank_upstream=50, flank_downstream=50, ref_delta=0, landmark=0):
"""Define a window surrounding a landmark in a region, if the region has such a landmark,
(e.g. a start codon in a transcript), accounting for splicing of the region,
if the region is discontinuous
Paramet... | be361c4625f4bc99612db3c3ebc3a1eb87fa70b8 | 677,836 |
def hex2rgb(hexstring):
""" convert #RRGGBB to an (R, G, B) tuple """
hexstring = hexstring.strip()
if hexstring[0] == '#': hexstring = hexstring[1:]
if len(hexstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % hexstring)
r, g, b = hexstring[:2], hexstring[2:4], hexstring[... | 3850a65cc0a8fdcd3239d564e0b2578a412f9285 | 677,840 |
def error(msg, value=None) -> str:
"""Formats msg as the message for an argument that failed to parse."""
if value is None:
return '<[{}]>'.format(msg)
return '<[{} ({})]>'.format(msg, value) | f8ec6b3b0b1b9f6e1196a91da58ab2f8fc962f98 | 677,843 |
def get_python_module_names(file_list, file_suffix='.py'):
""" Return a list of module names from a filename list. """
module_names = [m[:m.rfind(file_suffix)] for m in file_list
if m.endswith(file_suffix)]
return module_names | fa3ed8504304363e061953fb816eabd5852851c0 | 677,847 |
def _symplectic_euler_step(state, force, dt):
"""Compute one step of the symplectic euler approximation.
Parameters
----------
state : array-like, shape=[2, dim]
variables a time t
force : callable
dt : float
time-step
Returns
-------
point_new : array-like, shape=[... | 786eb9122823338dcf875a87b40488a0dbce1fff | 677,851 |
def early_stop(patience, max_factor, vae_loss_val, em_loss_val):
"""
Manual implementation of https://keras.io/api/callbacks/early_stopping/.
:param patience: max number of epochs loss has not decreased
:param max_factor: max_factor * current loss is the max acceptable loss
:param vae_loss_val: list... | 766dd335a2129a39957972e3f2c92c6650360880 | 677,853 |
def combinations(n, k):
"""
Given two integers n and k, return all possible combinations of k numbers
out of 1 2 3 ... n.
n = 4
k = 2
[
[1,2],
[1,3],
[1,4],
[2,3],
[2,4],
[3,4],
]
"""
def find_c... | 4f1b7944257b7609ab230f24c270d50d343f7020 | 677,854 |
import re
def humansort(l):
"""Sort in place a given list the way humans expect.
NB: input list is modified
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
d... | a3ef9cddc0d4db3814d3f50dcb6c662a6404edcb | 677,858 |
def fix_ecm_move_conflicts(conflict_ecm_list, move_order_text):
"""Get user input to sort out ECMs moved in both directions
It is possible that with a given set of active and inactive
ECMs and some sets of keywords given by the user to move ECMs
in bulk from one list to the other, there wil... | e4a779789f6359dbb4604bc02c5d70ee84039bfd | 677,868 |
def extract_value_other_gdf(x,gdf,col_name):
"""
Function to extract value from column from other GeoDataFrame
Arguments:
*x* : row of main GeoDataFrame.
*gdf* : geopandas GeoDataFrame from which we want to extract values.
*col_name* : the column name from whic... | 2af4e2ebacf50d7c35203ee365d51806aba2a2e9 | 677,872 |
def get_dimensions6(o_dim, ri_dim):
""" Get the orientation, real/imag, height and width dimensions
for the full tensor (6 dimensions)."""
# Calculate which dimension to put the real and imaginary parts and the
# orientations. Also work out where the rows and columns in the original
# image were
... | 4d163a9ff26a8c1e7675ce9f251c5fc942fc6760 | 677,876 |
import torch
def voxel_box_decode(box_encodings, anchors):
"""
box decode for pillar-net in lidar
:param box_encodings: [N, 7] Tensor, normal boxes: x, y, z, w, l, h, r
:param anchors: [N, 7] Tensor, anchors
:param encode_angle_to_vector: whether encoding angle to vector
:param smooth_dim: whe... | 83f6c6cf1b79de144ba3b8d79c3c23ee8b24bd97 | 677,879 |
def bboxes_to_pixels(bbox, im_width, im_height):
"""
Convert bounding box coordinates to pixels.
(It is common that bboxes are parametrized as percentage of image size
instead of pixels.)
Args:
bboxes (tuple): (xmin, xmax, ymin, ymax)
im_width (int): image width in pixels
im_heigh... | add33d059d9ba7a9b65688cd27ff0630d4debaf9 | 677,883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.