content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def calculate_error_rates(point_to_weight, classifier_to_misclassified):
"""Given a dictionary mapping training points to their weights, and another
dictionary mapping classifiers to the training points they misclassify,
returns a dictionary mapping classifiers to their error rates."""
error_dict = dict... | fad9b2ce0a1811536de4c085be0a56ab1eb253c6 | 159,525 |
from datetime import datetime
def make_message(name: str) -> str:
"""
Takes a name and returns a message with the name and the time
:param name: str Which is the name for the message to refer to
:returns: str The message containing the name and the time
"""
time = datetime.now().strftime("%H:%... | ec59e113dc4ecce62ddb7948d99ec3a8a2f51a1a | 214,499 |
from pathlib import Path
def cookiecutter_cache_path(template):
"""
Determine the cookiecutter template cache directory given a template URL.
This will return a valid path, regardless of whether `template`
:param template: The template to use. This can be a filesystem path or
a URL.
:ret... | cbdc72195bf47fb1bb91368ac2bbca3890775a60 | 7,807 |
def calc_get_item(func, in_data, **kwargs):
"""[GetItem](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.get_item.html)
Extract part of an array. This operation is zero FLOPs.
Most of tensor libraries have view feature, which doesn't actually create
a new array unless necessary... | b83eaaab84871099f03982b37c763239b7d6ecb6 | 119,738 |
def period(freq):
"""
Convert array of frequencies to periods.
"""
return 1./freq | dcaa701006e3c517696771927e327bf5b94f6d4d | 163,512 |
def is_prepositional_tag(nltk_pos_tag):
"""
Returns True iff the given nltk tag
is a preposition
"""
return nltk_pos_tag == "IN" | 746a1439613a2203e6247924fe480792e171eb7b | 20,798 |
def rename_clusters(name_dict, df, column_name):
"""
Takes in a dataframe, column name of the cluster, dictionary in the format: {'original_cluster_name' : 'new_cluster_name'}.
Returns a dataframe with the new cluster names.
"""
df = df.copy()
keys = list(name_dict.keys())
for k... | 327fc288bf4cab3e5de28bdef32d8dd3a02b403a | 346,858 |
from pathlib import Path
from typing import List
def read_csv_to_list(path: Path) -> List[str]:
"""Takes in a csv file path and splits the strings
and puts them into a list
Args:
path (Path): CSV file path
Returns:
List[str]: List of strings from the file
"""
list_of_strings ... | 1bb6a4ff1dca94451970df96275d40f52672f4cf | 385,731 |
def expand(path:list, conc_var:list) -> list:
"""
expand( path=[1, 2, 3], conc_var=[['a', 'c'], ['b', 'c']] )
---> [[1, 'a', 2, 'c', 3], [1, 'b', 2, 'c', 3]]
gives the detailed path!
Parameters
----------
path : list
The ids of formulas that form a path.
conc_var... | 33be48c324570d50ac62db2f25004f3ab8385fef | 83,240 |
def get_interface_state_from_api(data, index=-1, name="_"):
"""Process data from sw_interface_dump API and return state
of the interface specified by name or index.
:param data: Output of interface dump API call.
:param index: Index of the interface to find.
:param name: Name of the interface to fi... | acc8ff81fa177be0229aca8bd5ee71ebb36dd3a7 | 404,183 |
def preboil_grav(target_og: float,
preboil_vol: float = 7,
postboil_vol: float = 6):
"""Computes preboil gravity to to verify before concluding mash
Args:
preboil_vol: Pre-boil volume in gal
target_og: Target original gravity for primary fermentation e.g. 1.040
pos... | aab73da4e2c7060851db9dad9420c08a10b25ca0 | 622,305 |
def parse_size(size):
"""
Converts a size specified as '800x600-fit' to a list like [800, 600]
and a string 'fit'. The strings in the error messages are really for the
developer so they don't need to be translated.
"""
first_split = size.split('-')
if len(first_split) != 2:
raise Att... | 7a3ee86a48e320df70dec8f2a8fcb72bbaf377fe | 44,062 |
def prepare_deck(deck, number_of_cards):
"""Prepare sub_deck, from deck leaving starting number_of_cards cards."""
sub_deck = deck.copy()
while len(sub_deck) != number_of_cards:
sub_deck.pop()
return sub_deck | ee6c8b3c63d1e4ee1befe6384245ef692ba351e1 | 316,628 |
def get_catalog_record_preferred_identifier(cr):
"""Get preferred identifier for a catalog record.
Args:
cr (dict): A catalog record.
Returns:
str: The preferred identifier of e dataset. If not found then ''.
"""
return cr.get('research_dataset', {}).get('preferred_identifier', ''... | c3ab1fe64c07b63760829124769fb3e39519c083 | 96,615 |
import pickle
def encode_message(topic, data):
"""Encode a message for sending via 0MQ
Given a string topic name and a pickle-able data object, encode and prep
the data for sending via `send_multipart`
Returns a list of the form:
[
Bytes object of String (UTF-8),
Pick... | 73a083cc0edc574baf9843f245b3ee3a42ab35a0 | 569,679 |
import pathlib
from typing import List
def find_all_detectors(rootdir: pathlib.Path,
prefix: str = 'SingleCell') -> List[str]:
""" Find all the detectors under the root directory
If your directories look like this:
* ``/data/Experiments/2017-01-30/SingleCell-foo``
* ``/data/Ex... | 72e9deb8ae931373b80c4feb7c465ac3d10c60ed | 168,169 |
from typing import Iterable
import functools
import operator
def product(iterable: Iterable):
"""
Multiplies all elements of iterable and returns result
ATTRIBUTION: code provided by Raymond Hettinger on SO
https://stackoverflow.com/questions/595374/whats-the-function-like-sum-but-for-multiplication-... | 9662680401fb63c96cef271959964039d08aa20c | 638,967 |
def remove_spawning_profile(intersection, spawning_profile):
"""
Removes a spawning profile to an intersection
:param intersection: intersection
:param spawning_profile: spawning profile to be removed from intersection
:type intersection: Intersection
:type spawning_profile: SpawningProfile
... | 60d47e6eef993cd5cdab8e19a911b12874776c1e | 531,720 |
import io
def formatted_text_to_markdown(ft):
"""
Simple method to convert formatted text to markdown. Does not escape special characters.
"""
s = io.StringIO()
for f, t in ft:
if f == "":
s.write(t)
elif f == "underline":
s.write(f"__{t}__")
elif f ... | c6d653e6b3617eef7995860826f17fd815f29f80 | 278,330 |
import math
def transform(anchor_coords, reg_targets):
"""
Applies the bounding box regression transformation to an anchor box.
:param anchor_coords: numpy array of the anchor coordinates: [x1, y1, x2, y2]
:param reg_targets: numpy array of the bounding box regression parameters: [tx, ty, tw, th]
... | cf9834ccb55abeeef403b85bcd74d8a9705072e6 | 391,949 |
def preloader(align="center"):
"""
Returns a quick preloader html snippet.
:param align: string equal to "left", "center" (default), or "right"
"""
return {
'align': align,
} | 94fe0fa80ba85155d367f4402731e189b01a84c8 | 435,132 |
def parse_labels_voc(label_file):
"""
Definition: Parses label file to extract label and bounding box
coordintates.
Parameters: label_file - list of labels in images
Returns: all_labels - contains a list of labels for objects in the image
all_coords - contains a list of coordinates for objects in image
"""
... | a5ed15d8896a76e143cf106ca22c472131185fde | 205,083 |
def finish(response):
"""
Transitions the execution to completion.
Args:
response: The object to return to the execution's invoker.
"""
def action(state):
return state.finish(response)
return action | 5410fa6d5318acb238f9b91c885ec99b697997de | 349,477 |
def get_location_string(
feature_text: str) -> str:
"""
Args:
feature_text: endswith '\n'
For example:
' CDS complement(join(<360626..360849,360919..360948,
' 361067..361220,361292..361470,361523..>361555))
' ... | 46b0cd0176f57e764143a9d8114250185108e9e5 | 226,739 |
def squareMean3( array, centerPixel ):
"""
Kernel neighborhood function for focal map algebra. Reutrns mean of a 3x3 square array.
@param array - array from which to retrieve the neighborhood kernel
@param centerPixel - (i,j) corrdinates of center pixel of kernel in the array
@return - mean of 3x3 s... | e017f38483fdc72163adcd65ef9ef4900fa8b350 | 19,802 |
def _get_provisioning_state(instance):
"""Return the provisioning state from the instance result if present."""
if instance.get('provisioning_state'):
return instance.get('provisioning_state')
elif instance.get('properties'):
return instance.get('properties').get('provisioning_state')
el... | df98a713cb03afa76a0327c52949710641778c94 | 491,565 |
import re
def get_master_names(desired_master_state, name_regex):
"""Returns masters found in <desired_master_state> that match <name_regex>.
Args:
desired_master_state: A "desired_master_state" object, e.g. as returned by
desired_state_parser
Returns:
[str1, str2, ...] All masters found in <d... | 9343964103d1e93ff0d6de7d019c1fd206e84d3b | 696,323 |
import re
def is_passport_valid(p):
"""
byr (Birth Year) - four digits; at least 1920 and at most 2002.
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
eyr (Expiration Year) - four digits; at least 2020 and at most 2030.
hgt (Height) - a number followed by either cm or in:
If c... | 3c2889b416db3f6344a3c5767673e5b3581dda85 | 312,223 |
import math
def slopeAngle(p1,p2):
"""Returns the minimum angle the line connecting two points makes with the x-axis.
Args:
p1 ([tuple]): point p1
p2 ([tuple]): point p2
Returns:
[float]: minimum angle between x-axis and line segment joining p1 and p2
"""
try :
m... | 12252bfb196aefcf50f38a7459a5e50009b26817 | 152,613 |
def get_usrid_from_league(league):
"""
get user id from a league and put them into a list
:param league: LeagueDto: an object contains league information
:return: usrid
"""
entries = league['entries']
usrid = []
for entry in entries:
usrid.append(entry['playerOrTeamId'])
usri... | ce91f7f1f0afcc064b8f59c90721b60be47ab4b9 | 13,016 |
def _event_QSlider(self):
"""
Return value change signal for QSlider
"""
return self.valueChanged | f7fce1b98d0814fa90144df8356a0ea4e76c89b3 | 151,886 |
def vertical_strip_gridmap(height, alternating=True):
"""
Returns a function that determines the pixel number for a grid with strips arranged vertically.
:param height: grid height in pixels
:param alternating: Whether or not the lines in the grid run alternate directions in a zigzag
:return: mappe... | 9042071bfb440db663a3a0c123b79706cb051823 | 122,612 |
def parse_port_range(port_range_or_num):
"""Parses a port range formatted as 'N', 'N-M', or 'all', where
N and M are integers, into a minimum and maximum port tuple."""
if port_range_or_num.lower() == 'all':
return 0, 65535
try:
port = int(port_range_or_num)
return port, port
... | e2ed5d239e5961a8ddce1c19b8705391788315a1 | 369,178 |
from typing import List
from typing import Counter
def get_base_freq(reads: List[str]):
"""
Returns the aggregate frequency of bases in the sequencing reads
>>> get_base_freq(["NAACGTTA"])
Counter({'A': 3, 'T': 2, 'N': 1, 'C': 1, 'G': 1})
>>> get_base_freq(["AACGTTA", "CGCGTTT"])
Counter({'T':... | 60b5dc85e50ad6ea6a99ea949322bd4828a12cc3 | 571,900 |
from typing import Dict
from typing import Any
def default_style() -> Dict[str, Any]:
"""Define default values of the pulse stylesheet."""
return {
'formatter.general.fig_width': 13,
'formatter.general.fig_chart_height': 1.5,
'formatter.general.vertical_resolution': 1e-6,
'form... | cfd9219608e22a5f14a0b823d095beb752e6e8ff | 556,689 |
def get_intervention_label(method_name, base_intervention_name):
"""
Maps raw method name to a readable name.
Args:
method_name (str): name of the folder in the experiments.
base_intervention_name (str): filename in `configs/simulation/intervention/` folder.
Returns:
(str): a r... | ef4c349b0f0127ecf44d8b592846dd634ad3ebb2 | 284,662 |
def fen_to_board_pieces(fen, piece, n=8):
"""
:param str fen: The FEN string describing a position (state) in a Racing Kings Chess board.
:param str piece: Which piece type we want to find the positions. E.g. 'K', 'k', 'B', 'b'
:param int n: Chess game dimension (should always be 8).
:retu... | 2fe1126e571312a543e36fe19ae306f01e1d423f | 122,161 |
def is_title_case(line):
"""Determine if a line is title-case (i.e. the first letter of every
word is upper-case. More readable than the equivalent all([]) form."""
for word in line.split(u' '):
if len(word) > 0 and len(word) > 3 and word[0] != word[0].upper():
return False
return Tr... | e769d589d0f84030768c901a5b5b2285788bdc97 | 11,718 |
def sum_digits(n : int) -> int:
"""
Given a non-negative integer n, return the sum of its digits.
Parameters
----------
n : int
number to return the sum of
Returns
-------
int
sum of numbers digits
"""
if n == 0:
return 0
x = sum_digits(n // 10) + (... | ae8cd8b64d15548b2e5ede1feb40e564d01a1239 | 627,191 |
from typing import Dict
from typing import Any
def replace_module_prefix(
state_dict: Dict[str, Any], prefix: str, replace_with: str = "", ignore_prefix: str = ""
):
"""
Remove prefixes in a state_dict needed when loading models that are not VISSL
trained models.
Specify the prefix in the keys th... | b8499c818053e7798e9549fbe546bab7d5fbfa84 | 709,520 |
def dict_to_str(d):
"""Pretty print contents of a dict, with fixed width as [KEY] : [VALUE]"""
return "\n".join(["{0: <25}: {1}".format(k,v) for k,v in d.items()]) | b60162c923a0df2ab528f97608d348eeea4438a1 | 608,205 |
import requests
def catfact(context) -> str:
"""Get a random cat fact"""
return requests.get("https://catfact.ninja/fact").json()["fact"] | 3195dfe01a2e58f27e654e6b0723389d785ab13f | 398,034 |
import torch
def kullback_leibner(p, q, batch=False):
"""Calculates Kullback-Leibner Divergence of two probability densities
Args:
p, q: density values (must be all in range [0..1])
batch: if True, will return summed KL, divided by batch shape
Returns:
KL divergence, summed and divi... | 8d89ff5a01ee56d0d65e75ba8e8e0f0bdfcad4b5 | 213,884 |
import re
def _is_ignored(filename, ignored_paths):
""" Check if the file should be ignored
:type filename: str
:param filename: Name of file check
:type ignored_paths: list
:param ignored_paths:
List of regular expressions we should validate against
:returns: bool -- True if the file... | 4e5512248627306d9bc7d04157a25fc569130f04 | 574,422 |
def numpy(tensor):
"""Convert a torch.tensor to a 1D numpy.ndarray."""
return tensor.cpu().detach().numpy().ravel() | cdea8e80a6129ba846d9f69dc4825bf574e688ac | 41,383 |
import json
def get_tissue_mappings(mapping_filename):
"""Return a dictionary that maps tissue names to anatomical systems and organs"""
with open(mapping_filename, 'r') as mappings_file:
mapping_dict = json.load(mappings_file)
return mapping_dict['tissues'] | a049481bcb618bf275d42065897bd997d2629632 | 433,023 |
def calc_damped_vs_kramer_1996(vs, xi):
"""
Calculates the damped shear wave velocity
Ref: Eq 7.9 from Kramer (1996)
:param vs:
:param xi:
:return:
"""
return vs * (1.0 + 1j * xi) | a67a3c33e4c6b4d900cf126ee2cd53e682dc97c3 | 259,445 |
def _get_period_from_imt(imtstr):
"""
Return a float representing the period of the SA IMT in the input.
Args:
imtstr (str): A string representing an SA IMT.
Returns:
float: The period of the SA IMT as a float.
"""
return float(imtstr.replace('SA(', '').replace(')', '')) | 1cc4cbd1e46f04c56ac1b45155123353e4cbcbd9 | 279,544 |
def valid_interface_number(request):
"""
Fixture that yields valid interface numbers.
"""
return request.param | 9fccfb9bc07270eca6ec2ee093ed7b83cda018bf | 251,851 |
from datetime import datetime
def parse_time(value: str) -> datetime:
"""Parse and convert JSON encoded string to a datetime object
Parses a ``str`` and converts it to a ``datetime`` object. If the string is
not a valid JSON (JavaScript) encoded datetime object, this function will
return the minimum ... | 1dbf8768ea67553f8ef060fc670a4428a5f17367 | 551,433 |
import json
def get_user_parameters(job):
"""
Returns the user parameters that were defined in CodePipeline.
"""
return json.loads(
job["data"]["actionConfiguration"]["configuration"]["UserParameters"]
) | 6e74c5fb59930cf1bdd7ac0c882fe15275d70135 | 132,336 |
import random
def wait_for_small_enough_number(small_number=10, max_number=50, print_it=True):
"""
What comes in: Two optional positive integers,
with the second greater than the first,
and an optional indicator for whether to print intermediate results.
What goes out:
Returns the numbe... | 41d6f74be2abe448ce39961a5fa2c4563cd73511 | 320,677 |
def get_method_identifier(qualified_name):
"""Takes com.some.thing.Class:method and returns Class_method."""
parts = qualified_name.split(".")
method_identifier = parts[-1]
return method_identifier.replace(":", "_") | 2539a5160ff288225ab62f82596188e671e953ad | 467,269 |
def _make_emm_plugin_finalizer(handle, allocations):
"""
Factory to make the finalizer function.
We need to bind *handle* and *allocations* into the actual finalizer, which
takes no args.
"""
def finalizer():
"""
Invoked when the MemoryPointer is freed
"""
# At e... | 682378d6963bf924b77872c2ddf68105c90384b0 | 690,235 |
import re
def helper(filename):
"""
Reads file and build dictionary with words and their quantities in k,v
:param filename: the file to be read
:return: a dict with word: quantity
"""
# get words from file (split by space)
words = [w for line in open(filename).readlines() for w in line.sp... | 80db4bc50843bd09d3272171d3ee96e92f9cf908 | 540,282 |
import re
def FileExtension(file_name):
"""Return the file extension of file
'file' should be a string. It can be either the full path of
the file or just its name (or any string as long it contains
the file extension.)
Example #1:
input (file) --> 'abc.tar.gz'
return value --> 'tar.gz... | 53cff85d1b9c8faa0bb062fa459205ee8dad0b6d | 62,835 |
import random
def gen_fake_cpu_work(num_cpus: int = 1) -> tuple:
"""Generates a fake CPU times.
:param num_cpus: number of CPU to simulate, defaults to 1
:type num_cpus: int, optional
:return: work statistics -> number of CPUs, wall time, CPU time, single CPU time and io time
:rtype: tuple
""... | 62ae485c41f4f4f9d279e729ec4c2630150956d5 | 401,775 |
def literal_unicode_representer(dumper, data):
"""
Use |- literal syntax for long strings
"""
if '\n' in data:
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
else:
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data) | 28cd9b63eb9fbbd95b95c014c53d23bca81bb255 | 430,133 |
def get_integer(request, key):
"""Returns the first value in the request args for the given key, if that
value is an integer. Otherwise returns None.
"""
if not request.args or key not in request.args:
return None
value = request.args[key][0]
if not value.isdigit():
return None
... | 961d0737911df0665b30f210907740466aedb62b | 250,039 |
import ast
def _non_kw_only_args_of(args: ast.arguments) -> list[ast.arg]:
"""Return a list containing the pos-only args and pos-or-kwd args of `args`"""
# pos-only args don't exist on 3.7
pos_only_args: list[ast.arg] = getattr(args, "posonlyargs", [])
return pos_only_args + args.args | a6db7f28275bc8764b0f495f17d9c0e15a3e620a | 537,307 |
import string
from datetime import datetime
def make_temp_dirname(name=None):
"""Return a temp directory name."""
if name is not None:
chars = string.ascii_lowercase + "_"
name = name.lower().replace(" ", "_")
name = "".join((c for c in name if c in chars))
now = datetime.now().st... | ad62f5b5120afc71fd1605e2b477ea9b2fd31db3 | 470,841 |
def get_nice_str_list(items, *, item_glue=', ', quoter='`'):
"""
Get a nice English phrase listing the items.
:param sequence items: individual items to put into a phrase.
:param str quoter: default is backtick because it is expected that the most
common items will be names (variables).
:retur... | caa4b581b1d9e5a2bacae974f28a300bd4cc5811 | 202,418 |
def generate_traffic_directions(nodes):
"""
This function returns all possible traffic directions on the network topology.
If the network is made up of only three nodes (e.g. A, B and C), the possible traffic directions are: AB, AC, BA, BC, CA, CB.
If the number of nodes is N, the number of traffic... | c0d5a09e3a0d72039733a3e74fc1601c76fe26fa | 225,688 |
def checksum(message):
"""
Calculate the GDB server protocol checksum of the message.
The GDB server protocol uses a simple modulo 256 sum.
"""
check = 0
for c in message:
check += ord(c)
return check % 256 | bfba144414f26d3b65dc0c102cb7eaa903de780a | 9,832 |
def repeat_str(s, num):
"""
Repeat string
:param s: string
:param num: repeat number
:return: string
"""
output = ''
for i in range(0, num):
output += s
if len(output) > 0:
output += ' '
return output | 71c097459a299e591fe8ff8b045ca80a233bd24d | 94,363 |
def skip(x,n):
"""
Reduces precision of the numeric value
:type x: floating point value
:param x: number to reduce precision
:type n: int
:param n: number of values after dot
"""
return int(x*(10**n))/10**n | 65a416196e4055beb5876bcd79684f843ff76887 | 399,398 |
def xstr(this_string):
"""Return an empty string if the type is NoneType
This avoids error when we're looking for a string throughout the script
:param s: an object to be checked if it is NoneType
"""
if this_string is None:
return ''
return str(this_string) | 98e88c6d081e8f36943d20e66f0c2c6d8ff6acae | 264,931 |
def remove_keys(doc, keys):
"""Return a new document with keys in keys removed
>>> doc = {'a':1, 'b':2}
>>> remove_keys(doc, ['a'])
{'b': 2}
>>> # Show that the original document is not affected
>>> doc['a']
1
"""
return dict(
(k, v) for k, v in doc.items() if k not in keys) | dbee370982d6f3884dc2f4d137ba6b3e38791398 | 608,997 |
import re
def uncamel(val):
"""Return the snake case version of :attr:`str`
>>> uncamel('deviceId')
'device_id'
>>> uncamel('dataCenterName')
'data_center_name'
"""
s = lambda val: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', val).lower().strip('_')
return s(val) | 27c6b5338d8da39a6b45d420749457147738e416 | 626,468 |
def score(touching_power_pellet, touching_dot):
"""Verify that Pac-Man has scored when a power pellet or dot has been eaten.
:param touching_power_pellet: bool - does the player have an active power pellet?
:param touching_dot: bool - is the player touching a dot?
:return: bool - has the player scored ... | c34cd1a1c3cc5a331e39004ba34ab373281cb68b | 183,267 |
def dataset2metadataset_key(dataset_key):
"""Return the metadataset name corresponding to a dataset name
Args:
dataset_name (str): Name of a dataset
Returns:
str: Name of corresponding metadataset name
"""
return dataset_key.replace('/', '/_num_', 1) | a11a78ebcbc3deab6bba3e513e63584a2368e82f | 489,804 |
def areas(ip):
"""Returns the area per triangle of the triangulation inside
a `LinearNDInterpolator` instance.
Is useful when defining custom loss functions.
Parameters
----------
ip : `scipy.interpolate.LinearNDInterpolator` instance
Returns
-------
numpy array
The area p... | 07033b45d273f23d4c68f0382a9ffa0e0c8aaab4 | 454,967 |
import encodings
def _c18n_encoding(encoding: str) -> str:
"""Canonicalize an encoding name
This performs normalization and translates aliases using python's
encoding aliases
"""
normed = encodings.normalize_encoding(encoding).lower()
return encodings.aliases.aliases.get(normed, normed) | 8ccb52e06f361ba8492d9efa708ca7b30a7a9ae6 | 438,448 |
def _get_id_given_url(original_url: str) -> str:
""" Parse id from original URL """
return original_url.replace('https://', 'http://').replace('http://vocab.getty.edu/page/ia/', '') | c30f9ef1a6dde54c3a0f0e6fe6124a336b2e0e21 | 248,165 |
from typing import Any
def length(x: Any) -> int:
"""A length function we can bind to in gin."""
return len(x) | ac4abd25537d3aba3a1b5d73e9e766108465fe80 | 545,776 |
def parentheses_to_snake(x):
"""
Convert a string formatted as
"{a} ({b})" to "{a}_{b}"
Args:
x: input string
Returns:
Formatted string
"""
x_split = x.split(" (")
return f"{x_split[0]}_{x_split[1][:-1]}" | b82a734e409a110e7c8e776e6b110aa653d29a45 | 259,841 |
from typing import Optional
from typing import Tuple
def expandCommand(command: str, currentBranch: str, prevBranch: Optional[str]) -> Tuple[str, bool]:
"""
Replaces
%P with prevBranch,
%B with currentBranch.
If couldn't replace e.g. due to prevBranch being None, then does
no replacement.
... | c5166fb870752703ae96bc368487c0c87f55d795 | 564,790 |
from typing import Union
from typing import Dict
from typing import List
def to_tags(values: Union[Dict, List, str], sep: str = ",") -> List[str]:
""" Coerce the passed values into a list of colon separated key-value pairs.
dict example:
{"tag1": "value1", "tag2": "value2", ...}
... | fe6e2c0c25aa1bdb0e7c24ad10df124427fd3669 | 350,321 |
def slope(x_val, y_val):
"""
This function returns the slope of a line segment.
Parameters
----------
x_val, y_vals : coordinates of the two points of the line segments(x_val = [x1, x2], y_val = [y1, y2]).
Return
----------
slope of line segment.
"""
return ((y_val[1]-y_val[0])/(x_val[1]-x_val[... | 85dc05238c3a8d302f5534fea6aff25831553f80 | 265,459 |
def dot(vect1, vect2):
""" Calculate dot product of vect1 and vect2 """
return sum(v1_i * v2_i
for v1_i, v2_i in zip(vect1, vect2)) | 2a4c186838bac4392426e04a9efc4bd43e513dda | 214,949 |
def a_au(ms, p):
"""
ms : stellar mass [Solar]
p : period [days]
returns : semi-major axis [AU]
"""
return (ms * (p / 365.25) ** 2) ** (1.0 / 3.0) | 8d3dbde383a52be7a95d429ca7b3c2d6999daf7e | 233,640 |
def is_viv_ord_impname(impname):
"""
return if import name matches vivisect's ordinal naming scheme `'ord%d' % ord`
"""
if not impname.startswith("ord"):
return False
try:
int(impname[len("ord") :])
except ValueError:
return False
else:
return True | b8c1aa6f209000e04107cdff254a8fb3322a1921 | 178,266 |
def compare_user_with_lexicon(user_tokens, lexicon_tokens):
"""Function that compares input tokens with the resource tokens
from 1000 most common words with the help of two for-loop:
Input:
1. user_tokens (list): Liste der Benutzer-Tokens
2. lexicon_tokens (list): Liste der Lexicon-Tokens
O... | 6ab582acd3a12bed4b56be4199b84d02ae27fd27 | 289,557 |
def paint(width, height, performance):
"""Calculates how many paint does one need
for given area
@param width: area's width
@param height: area's height
@param performance: paint performance/m^2"""
area = width * height
return area / performance | 02243f92ab5b3f714bb94f489b2b8e6e49f6c4f0 | 42,925 |
def _eval_feature_fn(fn, xs, classes):
"""_eval_feature_fn(fn, xs, classes) -> dict of values
Evaluate a feature function on every instance of the training set
and class. fn is a callback function that takes two parameters: a
training instance and a class. Return a dictionary of (training
set ind... | 11e300b2896197a16a0faa46961d348683aa143f | 62,666 |
def disintegrate(obr):
"""Break image to RGB color representations, return list."""
r, g, b = obr.split()
return [r, g, b] | a7ec300d7089f2bde7a09f798252cdb1ca2b3443 | 54,925 |
import sqlite3
def _sqlite_json_enabled() -> bool:
"""Return True if this Python installation supports SQLite3 JSON1."""
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
try:
cursor.execute('SELECT JSON(\'{"a": "b"}\')')
except sqlite3.OperationalError:
return ... | 960c04887acad16885f12ed18dc9d0c8f583849b | 292,206 |
import pathlib
import json
def json_data(request, name: str):
"""Loads a json file."""
path = pathlib.Path(request.fspath, "fixtures", name)
with path.open("r") as fp:
return json.load(fp) | ccc7fb361a25ebf3d0f97b832f2e6ba104a30c1d | 123,942 |
def expect_z(zp_po):
"""Compute the expectation of z"""
return zp_po | c85be63b0d8c0f36cabace4032aecf920fc36f34 | 597,960 |
import ast
def black_repr(text):
"""Format some Chars as Source Chars, in the Black Style of Python"""
if text is None:
return None
assert text == str(text), repr(text)
# Glance over the oneline Repr from Python
repped = repr(text)
q1 = repped[0]
q2 = repped[-1]
middle_re... | 6b5c7abbbd5664a53bfe60604287b6d5fa0e3337 | 400,918 |
def select_bin(bin_list, values):
""" Select a bin from a list of bins based on an array of values.
Args:
bin_list (arr): List of Bin objects
values (arr): Array of parameters.
Not that the parameters need to be in the same order that the bins were generated from.
Returns:
... | 5ec77d2cddcf596e786467d96ce79ed3687515fc | 693,917 |
import re
def create_div_id(key):
"""
One method to take course name and do the following:
1) make lower case
2) remove white space
3) remove non-alphanumeric charachters
"""
return re.sub(r'\W+', '', key.lower().replace(' ', '')) | 530afc002473a07a7e8d5bdcbc9e7f27757b3079 | 296,437 |
def calculated_stat(base_stat, level, iv, effort, nature=None):
"""Returns the calculated stat -- i.e. the value actually shown in the game
on a Pokémon's status tab.
"""
# Remember: this is from C; use floor division!
stat = (base_stat * 2 + iv + effort // 4) * level // 100 + 5
if nature:
... | 904213a03fea0e8d350e3a4d364632bcbda1ebb8 | 125,716 |
import math
def forward_kinematics(length1, length2, theta1, theta2):
"""
:param length1: length of link 1
:param length2: length of link 2
:param theta1: absolute angle made by link 1 and positive x axis (assumed to be right)
:param theta2: absolute angle made by link 2 and positive x axis (ass... | 7eba6ef15fc98561da4aab4143bd778dbccb6bed | 379,869 |
def gen_header( program_name, start_address, program_length ):
""" Generate a Header Record """
#specify the size of each column
col2_size, col3_size, col4_size = 6,6,6
col1 = "H"
col2 = program_name[:col2_size].ljust(col2_size).upper()
col3 = hex(start_address)[2:].zfill(col3_size).upper()
col4 = hex(progra... | 0d978f46a985ff2e94b195cefdb8fe9ecd1b1cb9 | 445,640 |
def make_pair(img_paths, label_paths):
"""Take a list of image paths and the list of corresponding label paths and
return a list of tuples, each containing one image path and the
corresponding label path.
Arguments:
img_paths (list of `Path`): list of paths to images.
labels_paths (list of ... | 3bb3b0de71443618a9afbe19b6e13953480c6eb3 | 357,766 |
def is_authenticated(user):
"""
Check if a user is authenticated
In Django 1.10 User.is_authenticated was changed to a property and
backwards compatible support for is_authenticated being callable was
finally removed in Django 2.0. This function can be removed once support
Django versions earli... | 8fc279e5dc8182d634c3cc33fd451e402efe79b5 | 256,338 |
from typing import Callable
from typing import Any
import time
def _pytimed(callback: Callable[..., None], *args: Any, **kwargs: Any):
"""Call the given callback and return time in nanoseconds as result."""
start_time = time.monotonic_ns()
results = callback(*args, **kwargs)
end_time = time.monotonic_ns()
d... | 1d7ece3d4da8fdb4305d96e1a7623bd2e3a9a89e | 597,742 |
import time
def compute(n=26):
""" Computes 2 to the power of n and returns elapsed time"""
start = time.time()
res = 0
for i in range(2**n):
res += 1
end = time.time()
dt = end - start
print(f'Result {res} in {dt} seconds!')
return dt | d816c587302830f0acd20a59905c8634fcf20b49 | 706,148 |
def get_minibatch_blob_names(is_training=True):
"""Return blob names in the order in which they are read by the data loader.
"""
# data blob: holds a batch of N images, each with 3 channels
blob_names = ['data', 'labels']
return blob_names | 9963dbb80c7b79860a40871260fa1459fb518f6d | 134,383 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.