content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def make_seqs(a, b):
""" Makes mutliple sequences of length b, from 0 to a. The sequences are represented
as tuples with start and stop numbers. Note that the stop number of one sequence is
the start number for the next one, meaning that the stop number is NOT included.
"""
seqs = []
x ... | 5a8963572f2ce0d0baf85a99b2614f2c25ce9bde | 230,954 |
def assume_in_vitro_based_enzyme_modification_assertions(ac):
""" write a JTMS assumption specifying that in vitro-based evidence is acceptable
@param ac:bool True if action is to assert!, False if action is to
retract!, None to get the representation of the assumption
@returns: a string r... | a6bd257c257220bb719a29dda43b93b127a2c75d | 452,856 |
def truncate(name: str, length: int = 50) -> str:
"""
Truncates a string and adds an elipsis if it exceeds the specified length. Otherwise, return the unmodified string.
"""
if len(name) > length:
name = name[0:length] + "..."
return name | 7d00f1ce67029cfabc5dfb95da3a2f97d0beb578 | 256,929 |
from typing import List
def extensions_to_glob_patterns(extensions: List) -> List[str]:
"""Generate a list of glob patterns from a list of extensions.
"""
patterns: List[str] = []
for ext in extensions:
pattern = ext.replace(".", "*.")
patterns.append(pattern)
return patterns | a04ed356bfa5db7c0210b86dff832d32bfef6dbf | 8,713 |
import itertools
def zip_longest(*collections, **kwargs):
""":yaql:zipLongest
Returns an iterator over collections, where the n-th iterable contains
the n-th element from each of collections. Iterates until all the
collections are not exhausted and fills lacking values with default value,
which i... | a618433c5b4d66127d0bdac4d6bfa53304a91a00 | 602,414 |
import types
def isfunc(x):
"""Returns True if x is a function."""
return isinstance(x, types.FunctionType) | 54597ccd7480da9e6fa602cdd764febfdc9cbba7 | 381,687 |
import re
def intcomma(value, ndigits=None):
"""Converts an integer to a string containing commas every three digits.
For example, 3000 becomes "3,000" and 45000 becomes "45,000". To maintain some
compatibility with Django's intcomma, this function also accepts floats.
Args:
value (int, floa... | e61569657989dedecc8c2f01d5f9ec960ed63073 | 373,182 |
def read_edge_list(path):
"""Read edge list in KONECT format."""
with open(path, 'r') as f:
edge_list = set()
for line in f:
if not line.lstrip().startswith("%"): # ignore comments
e = line.strip().split()
edge_list.add((int(e[0]) - 1, int(e[1]) - 1))... | 54af1afc7ff55cd768b890d72eed176b82e4de9b | 172,653 |
def filter_none_values(dict):
"""Return dictionary with values that are None filtered out"""
return {k: v for (k, v) in dict.items() if v is not None} | 3c14ad9a339f928be71e7ed88dfd93ff012d30d0 | 459,509 |
def inh2o2pascal(inh2o):
"""convert pressure in inches of water to Pascals"""
return (inh2o * 1.0) / 0.00401865 | a5ccacf016fd14cc826161e60ee8137404af5738 | 277,292 |
def velocity_transformation(frame_velocity: float, observed_velocity: float) -> float:
"""
Computes the velocity transformation for a given frame velocity and observed velocity.
The frame velocity is the velocity of the new frame relative to this frame.
The observed velocity is a velocity measured in th... | 970b3392ee658afef81451cd31a9d31330169d41 | 249,106 |
import random
def random_sequence( length ):
"""Return a random string of AGCT of size length."""
return ''.join([ random.choice( 'AGCT' ) for i in range(int( length ))]) | 288d09c4173fdafbdb8529f2318e38b306d4d552 | 358,427 |
def get_image_value(x, y, img):
"""Get pixel value at specified x-y coordinate of image.
Args:
x (int): horizontal pixel coordinate
y (int): vertical pixel coordinate
img (numpy.ndarray): image from which to get get pixel value
Returns:
float: pixel value at specified coord... | 466815a7d84ae76ece32f1da01d2a103086e1e67 | 670,311 |
def decode_int(pool_im, coord):
"""Helper function that returns uint8 that was encoded
in pool_im tile starting at pixel at coord.
"""
bin_cint = ''
for i in range(8):
bin_cint += str(pool_im[ coord[0], coord[1]+i, 0 ] - pool_im[ coord[0]+1, coord[1]+i, 0 ])
return int(bin_cint, 2) | 6aa7ea82ab151ba175c0817ac895278095e83f0f | 371,662 |
def fibonacci(n):
"""Given a positive int n, uses recursion to return the nth Fibonacci number."""
if n == 1 or n==2:
return 1
elif n <= 0:
return 0
else:
return (fibonacci(n-1) + fibonacci(n-2)) | 1071009c3209f4a1b518829b41b60f0ecaa4abd5 | 201,420 |
def cver_t(verstr):
"""Converts a version string into a tuple"""
if verstr.startswith("b"):
return tuple([0,0,0,0]+list(cver_t(verstr[1:])))
return tuple([int(x) for x in verstr.split(".")]) | 73b4abd456551e678f44c0f940ad8d055993a345 | 691,660 |
import io
def get_message_data(msg):
"""Returns ROS1 message as a serialized binary."""
buf = io.BytesIO()
msg.serialize(buf)
return buf.getvalue() | 7173cd596c0f0be3be31dfcf580260fe025ebcb0 | 477,021 |
from typing import Type
from typing import Any
import typing
def _is_list(field: Type[Any]) -> bool:
"""Returns True when the given type annotation is list[...]."""
return typing.get_origin(field) is list | 491b764a4255312f1cf89e740293650c89a8fd82 | 424,635 |
def get_actual_objname(full_object_name):
"""Given a object string full name (e.g 0&0&DEFINING_ORIGIN), returns
its name (e.g DEFINING_ORIGIN).
"""
return full_object_name.split('&')[2] | e0dd644a16a1c6865e2354b36d2466661939d131 | 558,286 |
def create_listing_date(data):
"""Create listing date feature."""
data['Data_annuncio'] = (data['Riferimento e data annuncio']
.str.split('-')
.str[-1]
.str.strip()
.astype('datetime64[D]'))
r... | 3d5698b948b7d16d87cc190114f5e6a887349821 | 143,817 |
def safe_compare_dataframes(first, second):
"""Compare two dataframes even if they have NaN values.
Args:
first (pandas.DataFrame): DataFrame to compare
second (pandas.DataFrame): DataFrame to compare
Returns:
bool
"""
if first.isnull().all().all():
return first.eq... | 1e0ce9c9de03973c7c0448ba0fafd25f399cda04 | 166,939 |
def merge_dicts(*dicts):
"""Merge two or more dicts, later ones replacing values of earlier ones.
Note that only shallow copies are made of the dicts.
@b Examples
```
a = dict(a=1, b=2, c=3)
b = dict(c=-3, d=-4)
c = merge_dicts(a, b)
# Result: dict(a=1, b=2, c=-3, d=-4... | ade27bf5279671ba16af8b1f8ca9dfe881ed9e4b | 166,310 |
import json
def load_transition_types(transitions_uri):
"""Loads a transition .json file and returns a dictionary mapping
transition ids to their types.
transitions_uri - path to a .json file with the format
{
"modify_landscape_structure": "restoration", ... }
... | 776f5dd548ac0bb7f4447a24623751f8faca7baf | 611,370 |
import math
def dist_calc(x, y):
"""Returns a distance calcultion fuction from a static (x, y)"""
def func(x1, y1):
return math.sqrt(math.pow(x1-x, 2) + math.pow(y1-y, 2))
return func | 7a55c4b00c2a72eb64f1468b650d6195a791b32a | 568,867 |
def add_value(attr_dict, key, value):
"""Add a value to the attribute dict if non-empty.
Args:
attr_dict (dict): The dictionary to add the values to
key (str): The key for the new value
value (str): The value to add
Returns:
The updated attribute dictionary
"""
if v... | 93728d08c8cbaacc34b62f0437a5c4d2d0cc6ddc | 521,527 |
def scilabel(value, precision=2):
"""Build scientific notation of some value.
This is dedicated to use in labels displaying scientific values.
Args:
value (float): numeric value to format.
precision (int): number of decimal digits.
Returns:
str: the scientific notation the spe... | f0f2dcdbdb4d24f594c75381e8daf6a947eac0aa | 367,094 |
def align16(address):
"""
Return the next 16 byte aligned address.
"""
return (address + 0x10) & 0xFFFFFFF0 | e330b3eca5ab0997ec3f8b743486237572033929 | 339,813 |
import textwrap
import html
def pretty_text(data):
"""Unsescape the html characters from the data & wrap it"""
if data is not None:
return textwrap.fill(html.unescape(html.unescape(data)), width=60)
else:
return "" | f5baf58394b8578b26ad3cb95aff26867bc5f748 | 31,692 |
def isB(ner_tag: str):
"""
We store NER tags as strings, but they contain two pieces: a coarse tag type (BIO) and a label (PER), e.g. B-PER
:param ner_tag:
:return:
"""
return ner_tag.startswith("B") | b24752ccb3a83936157fa7a7e73b5591bc64a625 | 79,980 |
from typing import Iterable
def flatten_iterable(its: Iterable, deep: bool = False) -> list:
"""
flatten instance of Iterable to list
Notes:
1. except of str, won't flatten 'abc' to 'a', 'b', 'c'
demo: [[[1], [2], [3]], 4]
if deep is True: flatten to [1, 2, 3, 4]
if deep is Fal... | 4c17d75a7dde4d0b9002dedea2938deacfef813f | 687,371 |
def canonicalShape(shape):
"""Calculates a *canonical* shape, how the given ``shape`` should
be presented. The shape is forced to be at least three dimensions,
with any other trailing dimensions of length 1 ignored.
"""
shape = list(shape)
# Squeeze out empty dimensions, as
# 3D image can ... | 0f11a7298253fe9655846a663f5761cd17ae2880 | 681,045 |
def path2linkTuple(pathString):
"""
Converts a path expressed as a sequence of nodes, e.g. [1,2,3,4] into a tuple
of link IDs for use with the Path object (see path.py), in this case
((1,2),(2,3),(3,4))
"""
# Remove braces
pathString = pathString[1:-1]
# Parse into node list
nodeList = pa... | e2a8cbe4f6a5918fa6acd1766618a6862190acce | 513,908 |
def emphasis(text):
"""Returns a text fragment (tuple) that will be emphasized when displayed."""
return ('emphasis', text) | de47483ea93d954af33eb5329090a1d0334c289a | 401,621 |
import math
def atan_deg(value):
""" returns atan as angle in degrees """
return math.degrees(math.atan(value) ) | ad7f79e4ebbfc364bddb5f20afd01b8cf70f9c08 | 30,400 |
import torch
def make_creep_tests(stress, temperature, rate, hold_times,
nsteps_load, nsteps_hold, logspace = False):
"""
Produce creep test input (time,stress,temperature) given tensor
inputs for the target stress, target temperature, loading rate
Args:
stress: 1D tensor of tar... | 9f252018c078158ffc7615aec5a194ced914f17f | 127,401 |
def find_layer_id(layers_range, router_id):
"""
Find layer id of the router.
Parameters
----------
layers_range : [type]
list of router id range
router_id : int
[description]
Returns
-------
int
layer id
"""
for itr, layer_range in enumerate(layers_r... | 49b800369f5c2b4c9854e5afb7e3d742875f9b46 | 179,083 |
def is_not_to_keep(is_under_a_day, index):
"""
Return if we should keep this based on if the duration is less than a day.
:param is_under_a_day:
:param index:
:return: to keep or not
"""
index += 1
return not is_under_a_day[index] | ba4e16dfd3fd2f7382f27a4692b45b5b729c4afc | 238,722 |
from typing import List
def open_uniform_knot_vector(n: int, order: int) -> List[float]:
"""
Returns an open uniform knot vector for a B-spline of `order` and `n` control points.
`order` = degree + 1
Args:
n: count of control points
order: spline order
"""
nplusc = n + order... | 9ab62ea4ca3264c29c7c413084887e8c06172a13 | 180,647 |
def _write_a_tikz_coordinate(name, xy, num_fmt):
"""Write a TikZ coordinate definition.
Parameters
----------
name : str
TikZ coordinate identified / name.
xy : list or tuple of floats
(x, y)-coordinates.
num_fmt : str
Specification of the numbers format, e.g. '.4f'.
... | 5917bbe0fd97ff632a3ff8376f20b43ebdccbd5b | 567,052 |
def abs2(src, target):
"""
compute the square absolute value of two number.
:param src: first value
:param target: second value
:return: square absolute value
"""
return abs(src - target) ** 2 | 275e015bca3cae2f737b284f40861b3136936109 | 690,527 |
def process_to_dict(process):
"""Return nested dicts for the nested namedtuples of a process."""
# These lines are sort of like a deep version of _asdict().
stages = [stage._asdict() for stage in process.stages]
for stage in stages:
stage['progress_items'] = [pi._asdict() for pi in stage['progress_items']]
... | 306e565fdaad76fa956e8706a9d2b605bce32a96 | 597,011 |
def parse_cfg(cfgfile):
"""
Takes a configuration file
Returns a list of blocks. Each block describes a layer (usually) in the neural
network to be built. Block is represented as a dictionary in the list
"""
file = open(cfgfile, 'r')
# store the lines in a list
lines = file.read().spl... | 63feb42367ba00ab9a14073d6f34761d73378206 | 190,384 |
def parse_org_members(members_json):
""" Extract what we need from Github orgs members listing response. """
return [{'login': member['login']} for member in members_json] | 038eadc48a01bf5579acf0e8d6fcd3bba66a3623 | 103,206 |
import six
def right_strip00(the_string):
"""Remove '\x00' bytes from the right end of a byte-string."""
assert isinstance(the_string, six.binary_type)
return the_string.rstrip(bytes(b'\x00')) | fa5cad2716d24c2a0a67e42e7f0e9db0bb12a2fa | 218,749 |
def overrides(interface_class):
"""
To be used as a decorator, it allows the explicit declaration you are
overriding the method of class from the one it has inherited. It checks that
the name you have used matches that in the parent class and returns an
assertion error if not
"""
def over... | e5264baf1c5a5d97b354a4db3b3a49ccb580c082 | 631,308 |
def calc_ineffdate(row, date_dict: dict):
"""Calculates the date a given SFHA was deemed ineffective based on
whether the SFHA resides inside 2+ different LOMRs.
Parameters
----------
row : Pandas Series
A row of a pandas DataFrame
date_dict : dict
A dictionary of FLD_AR_IDs an... | 3c0c6b44d4917fc1341e6e0f6247c50363980571 | 195,273 |
def get_header(context, header_name):
"""Return all response header values that've been set for header_name."""
return [header[1] for header in context.headers if header[0] == header_name] | cc2fba51f028aa76b8864376d8010099de56cc50 | 627,748 |
def format_error(error_code, message):
"""
Converts an error_code and message into a response body
"""
return {"errors": [{"code": error_code, "message": message}]} | 70319669a5504cf1b6c07cdc9ef1de5f04437f20 | 264,451 |
def get_location(local_dictionary:dict) -> str:
"""
Description:
Function which gets the local location from the returned local dictionary from covid_API_request
Arguments:
local_dictionary {dict} : dictionary containing 3 sub dictionary's: 'data' (containing all covid data requested),
... | eee208b97e1a8ac64e4bfe5eaa48f45600a67c34 | 383,774 |
def indent(string: str) -> int:
"""Count the indentation in whitespace characters.
Args:
string (str): text with indents
Returns:
int: Number of whitespace indentations
"""
return sum(4 if char == "\t" else 1 for char in string[: -len(string.lstrip())]) | 0a58beace80f6f3c5298ca2179f0fbbc40247362 | 363,108 |
import re
def clean_identifier(identifier: str) -> str:
"""Removes all whitespaces from the identifier."""
return re.sub(r'\s+', '', identifier) | 5a92edeab99e29c31752cfd452187793c88f444d | 407,576 |
def by_newlines(*parts):
"""return parts joined by newline characters - Unix style"""
return '\n'.join(parts) | 16945a617456a2b82e6e814c0e40a188c716b10d | 543,086 |
import re
def get_include_count(f):
"""Get number of #include statements in the file"""
include_count = 0
for line in f:
if re.match(r'\s*#\s*include', line):
include_count += 1
return include_count | b85b0c2c0c9d6ee1ec209ea2aef93fc62c296a02 | 112,218 |
def length_vector_sqrd_xy_numba(a):
""" Calculate the squared length of the vector, assuming it lies in the XY plane.
Parameters
----------
a : array
XY(Z) components of the vector.
Returns
-------
float: The squared length of the XY components.
"""
return a[0]**2 + a[1]... | e1dd9a5830e09318295ee79b2c5235e97059b05e | 319,547 |
def crop(image, x, y, w, h):
""" Crop image to given position and size """
image = image[y : y + h, x : x + w]
return image | 31c6cc695e632ee3c9ae58750e7ba3c5fe31ac7b | 207,799 |
def ts_to_ms(ts):
"""
Convert second timestamp to integer millisecond timestamp
"""
return int(ts * 1e3) | 2d4435eecc6eb68d3d4644195bc3eccdd212f970 | 316,862 |
def divide(x: float, y: float) -> float:
"""Divide :math:`x` by :math:`y`
Arguments
---------
x : float
First number
y : float
Second number.
Raises
------
ZeroDivisionError:
If the denominator is zero
Returns
-------
float
x / y
"""
... | 2279f1fe2063a7bcc8a9086eb800fe5f2c01db99 | 223,040 |
def shave_batch_LFs(inLFs, border=(3, 3)):
"""
Shave the input light field by a given border.
:param inLFs: a batch of input light fields of
size: [B, H, W, S, T, C]
:param border: border values
:return: shaved light field
"""
h_border, w_border = border
if (h... | dfd85adada5a6027224093c2a2f89bd950b4c711 | 394,743 |
def is_df(
df):
"""is_df
Test if ``df`` is a valid ``pandas.DataFrame``
:param df: ``pandas.DataFrame``
"""
return (
hasattr(df, 'to_json')) | fe5c111e8883ff64e3b63602e57aaa793ef710fa | 42,721 |
def detect_missing_leap_days(ts_data):
"""Detect if a time series has missing leap days.
Parameters:
-----------
ts_data (pandas DataFrame) : time series
"""
feb28_index = ts_data.index[(ts_data.index.year % 4 == 0)
& (ts_data.index.month == 2)
... | 34cd6fe34c48982ceb2f2a7cc8182cd175912080 | 317,774 |
from typing import List
from typing import Union
from typing import Dict
from typing import Any
def tweaks_for_actions(actions: List[Union[str, Dict]]) -> Dict[str, Any]:
"""
Converts a list of actions into a `tweaks` dict (which can then be passed to
the push gateway).
This function ignores all ... | 9b77b84bd007fe47fd63741f9662ae99d8c9695f | 444,232 |
def file2tuple(thing):
"""
Function that converts a filename to a tuple of the type: (filename,string containing file)
Input can be filename or tuple with filename and content in a string.
"""
if isinstance(thing,tuple): # it is a tuple with filename and content in a string
filename,st... | a62babbb2d2ebaf6e9cd845868fe707af09ff17c | 143,199 |
def normalize_stats(stats):
"""Normalize frequency statistics."""
return dict((chr(k) if k < 256 else k, v if v else 1) for k, v in stats.items()) | 15953d48f1a99c349096957235ec1986e66b6b11 | 383,577 |
def decode_test_run(test_run):
"""
Function to decode test_run name into sequence of training parameter values
:param test_run:
:return: patience, learning rate, minimal learning rate, anneal rate
"""
x = test_run.split("lr.")
patience = int(x[0][1:])
lr = float(f"0.{x[1][:-1]}")
y =... | e1f7028d8ab104e548ba6cd517763351d5b6ed48 | 261,872 |
import pickle
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f, encoding='latin1')
X = datadict['data']
Y = datadict['labels']
return X, Y | cab8293d1c38bd90ba03074d95c62d4fb96d8460 | 185,562 |
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
s = sum((9 - i) * int(n) for i, n in enumerate(number))
return str((11 - s) % 11 % 10) | 85a0b09e7777be767bc3787e185adbd3cc7ad6cc | 97,188 |
def example_func(param1, param2):
"""Example function with types documented in the docstring
Args:
param1 (int): The first parameter
param2 (str): The second parameter
Returns:
bool: The return value. True for success, False otherwise.
"""
print(param1)
print(p... | 2bc46e4cb686cc926383b145ae7b8a7b3ed948c8 | 96,949 |
def common_shape(arrays):
"""
Infers the common shape of an iterable of array-likes (assuming all are of
the same dimensionality). Inconsistent dimensions are replaced with `None`.
"""
arrays = iter(arrays)
shape = next(arrays).shape
for array in arrays:
shape = tuple(a if a == b els... | 49e2c4a1666ec0a821b9abeef3e1738eaeb22f5c | 457,518 |
from typing import List
def getLongestCommonPrefix(strs: List[str]) -> str:
"""
>>> getLongestCommonPrefix(["abc_aaa","abc_bb","abc_aaaa"])
'abc_'
>>> getLongestCommonPrefix(["b","abc_bb","abc_aaaa"])
''
>>> getLongestCommonPrefix([])
''
"""
l = len(strs)
if l == 0:
ret... | 23da396c3eb176b8aeb577eed73c5ccd7d1cbc1b | 127,750 |
def _escape_underscore(text):
"""
Internal utility to escape any TeX-related underscore ('_') characters in mpl strings
"""
return text.replace('_', '\_') | ca9d7b55d96d35983e03ccb3337aff810e66356b | 463,858 |
def lang(name, comment_symbol, multistart=None, multiend=None):
"""
Generate a language entry dictionary, given a name and comment symbol and
optional start/end strings for multiline comments.
"""
result = {
"name": name,
"comment_symbol": comment_symbol
}
if multistart is no... | e1e89caf4bb595e61a94df1ee70d33c39e75f486 | 688,778 |
import hashlib
def create_hash_id(input):
"""
Creates hash identifier.
Parameters
==========
input : str
Input to be hashed to form an identifier.
Returns
=======
hash_id : str
Identifier formed by hashing the inputs.
"""
input_bytes = bytes(input, encoding="u... | e9319728a58b9afc947bb2ddc6fc3701d7ec861a | 586,177 |
def generate_number_lines(number_of_lines=6, start=0, end=20):
"""
Generates number lines as a tool for practicing mathematics such as addition or subtraction.
:param number_of_lines: Specify the number of lines to have on the page
:param start: start value for the number line as an integer
:param e... | 173aae03162e5d5717078e872051bc11e1e56057 | 632,848 |
def union(list_a: list, list_b: list) -> list:
"""Return the union of two lists"""
if list_a is None:
list_a = [None]
if list_b is None:
list_b = [None]
return list(set(list_a) | set(list_b)) | 4cc4c7fd6214a281115def00ae52a80f6194fd69 | 103,420 |
import typing
import fnmatch
def get_s3_files_for_pattern(client, pattern: str) -> typing.List[str]:
"""Get a list of S3 keys given a potential wildcard pattern
(e.g., 's3://bucket/a/b/*/*.jpg')"""
segments = pattern.replace("s3://", "").split("/")
bucket = segments[0]
keypat = "/".join(segments[1... | 5a371aad8a512934f98911b2ff0ea2c3924645dc | 501,683 |
def convert_to_iris(dict_):
"""Change all appearances of ``short_name`` to ``var_name``.
Parameters
----------
dict_ : dict
Dictionary to convert.
Returns
-------
dict
Converted dictionary.
Raises
------
KeyError
:obj:`dict` contains keys``'short_name'`... | 79e915c95532440ea155adc78a9642375d388a5b | 437,367 |
def make_altaz_frame(location, time):
"""
Turns location and time into altaz frame
:param location: astroplan.observer object
:param time: astropy.Time object
:returns: Altaz frame
"""
return location.altaz(time) | 906f5f7735248341d33817b8dfb232740bc3246a | 264,255 |
import math
def filter_none(mongo_dict):
"""Function to filter out Nones and NaN from a dict."""
for key in list(mongo_dict.keys()):
val = mongo_dict[key]
try:
if val is None or math.isnan(val):
mongo_dict.pop(key)
except Exception:
continue
... | 6853a7153f98466dc00d262bfaf4a63db1b0cd5c | 11,581 |
def _options_choose_characters(player):
"""Return the options for choosing a character.
The first options must be the characters name (5 are allowed
by player). The other nodes must be reached through letters:
C to create, D to delete.
"""
options = list()
characters = player.db._playable... | d72c08bf9a2cb7ebfc7d4e6d13a94e1189d0d2f9 | 586,561 |
def feature_normalize(X, mean=None, sigma=None):
"""
returns a normalized version of X where
the mean value of each feature is 0 and the standard deviation
is 1. This is often a good preprocessing step to do when
working with learning algorithms.
the normalization is processed separately for ea... | 81342428799f5ac8d1815b54400e8eb4d7cc302b | 694,919 |
def _format_node(e):
"""
Internal function to format a node element into a dictionary.
"""
ignored_tags = [
"source",
"source_ref",
"source:ref",
"history",
"attribution",
"created_by",
"tiger:tlid",
"tiger:upload_uuid",
]
node = ... | 17885312c86fbe731976cd7866a3597d3b05de9e | 259,889 |
import logging
def __cmp_published__(x, y):
"""A custom ``cmp()`` which sorts descriptors by published date.
:rtype: int
:returns: Return negative if x<y, zero if x==y, positive if x>y.
"""
if x.published < y.published:
return -1
elif x.published == y.published:
# This *should... | 06c72dd0f914ba2d6fba38d17fffff554e523d90 | 315,935 |
def scriptable(fn):
"""Decorator to register operation for scripting."""
fn.scriptable = True
fn.script_args = fn.__annotations__
return fn | 6a4b62e6effa59941c24beac7fee4a1b34f0cb8d | 197,789 |
def is_reverse_related(field):
"""
Test if a given field is a reverse related field.
:param DjangoField field: A reference to the given field.
:rtype: boolean
:returns:
A boolean value that is true only if the field is reverse related.
"""
return 'django.db.models.fields.reverse_rel... | 025c6a4fec1c527ff0e081bee4c6372a9c5dfc74 | 202,642 |
def FlagBelongsToRequiredGroup(flag_dict, flag_groups):
"""Returns whether the passed flag belongs to a required flag group.
Args:
flag_dict: a specific flag's dictionary as found in the gcloud_tree
flag_groups: a dictionary of flag groups as found in the gcloud_tree
Returns:
True if the flag belong... | 79f36d76c78d7ac54d38954a4559a23b15e92b70 | 145,352 |
def get_table_4(air_type):
"""表4 外皮の内側にある空気層の熱抵抗
Args:
air_type(str): 空気層の種類
'AirTight'(面材で密閉された空気層)または'OnSiteNonConnected'(他の空間と連通していない空気層)または
'OnSiteConnected'(他の空間と連通している空気層)
Returns:
float: 外皮の内側にある空気層の熱抵抗
"""
R_dict = {'AirTight': 0.09, 'OnSiteNonConnected': 0, 'OnSiteCo... | 66f28b535f9ef69525cf1e74e0af4bbf155ec458 | 32,511 |
from typing import Collection
def iscollection(eo_object):
""" Helper to check whether an EOObject is a collection. """
return issubclass(eo_object.real_type, Collection) | 7f80f76fb0efdc9098eb324b729f41d753842668 | 359,175 |
import json
def to_json_string(obj):
"""Convert object as a JSON string."""
return json.JSONEncoder(indent=2).encode(obj) | 5e6377365ec5f5a2550533af733b3c5babbd81fa | 668,170 |
def forcerange(colval):
"""Caps a value at 0 and 255"""
if colval > 255:
return 255
elif colval < 0:
return 0
else:
return colval | d0895fcf53788eb3a09a400576f2f6fc472ec654 | 654,138 |
def ensure_pymongo(obj):
"""If obj is wrapped by motor, return the internal pymongo object
:param obj:
a pymongo or motor client, database, or collection
:returns:
pymongo client, database, or collection
"""
if obj.__class__.__module__.startswith("pymongo."):
return obj
... | d617b8db535cd3f8bf882da8a2c31f37dc922af6 | 70,470 |
from typing import Dict
from typing import List
def add_toggle_completion(
toggle_outcomes: Dict[str, Dict[str, bool]],
subtasks: List[str]):
"""Create toggled outcomes/completions mapping
for each toggle-able subtasks.
e.g.
>>> toggle({}, ['Click A', 'Click B', 'Click C'])
>>> {
... | 383ca79ee47cb6d095c74d5f88dc25f06cf60702 | 119,727 |
def get_crash_id(line):
"""
Takes a raw CSV line and returns a crash_id
:param str line: The raw CSV line
:return str: The Crash ID
"""
try:
return line.strip().split(",")[0]
except Exception as e:
print("Error: " + str(e))
return "" | 68188ff4290173deddd3608ceb0534ce6ca2df18 | 31,203 |
def has_isolated_transposition(source, image):
"""Check whether a, b exist, with a -> b and b -> a"""
f = dict(zip(source, image))
for s, i in zip(source, image):
if f[i] == s:
return True
return False | b856370161ff918bbbf679b1dd366aa2f563ff51 | 87,872 |
def airbnb_js_data() -> dict:
"""
Returns a fake JS data for the Airbnb classes
"""
return {
'layout-init': {
'api_config': {
'key': 'api_key',
}
},
'reduxData': {
'homePDP': {
'listingInfo': {
... | 387cc5fbc5d846036277372ab8fdf302c6adc37a | 439,556 |
def ensure_tz_UTC(df):
"""
Function to ensure that the tzinfo of a data frame is in UTC
:param df: a pandas data frame with datetime_index
:returns: the dataframe with df.index.tzinfo='UTC'
"""
# ensure tzinfo is in UTC
if (str(df.index.tzinfo)=='None'):
#print('The time... | 4e8fb68dc648b32138dda66a415c9c5e660665f1 | 637,473 |
def drop_titles(tree, titles_to_drop):
"""
Walk the tree and drop any nodes whose titles are in `titles_to_drop`.
"""
def _drop_titles(subtree):
new_children = []
for child in subtree["children"]:
if child["title"] in titles_to_drop:
continue
else... | 99a1abeca91751703de1626251e8aa4ca115d41e | 80,455 |
def dig2phys(signal, dmin, dmax, pmin, pmax):
"""
converts digital edf values to analogue values
:param signal: A numpy array with int values (digital values) or an int
:param dmin: digital minimum value of the edf file (eg -2048)
:param dmax: digital maximum value of the edf file (eg 2048)
... | 291199109b1318e4b8c24c90f456bd72cc21003b | 249,298 |
def guess_beta_parameters(guess, strength=5):
"""Given a `guess` of the mean of a beta distribution, calculate beta
distribution parameters such that the distribution is skewed by some
`strength` toward the `guess`.
:param guess: guess of the mean of the beta distribution
:type guess: float
:pa... | c29b7162a6613dfad326868831b862a00fdf08c4 | 247,640 |
def _get_branching(container, index):
""" Returns the nearest valid element from an interable container.
This helper function returns an element from an iterable container.
If the given `index` is not valid within the `container`,
the function returns the closest element instead.
Parameter
---... | 5bdb1d45ba5e91a767564a7bd246cda558e10882 | 148,226 |
import random
def get_imbalanced_data(training_data, img_num_per_cls):
"""Get a list of imbalanced training data, store it into im_data dict."""
im_data = {}
for cls_idx, img_id_list in training_data.items():
random.shuffle(img_id_list)
img_num = img_num_per_cls[int(cls_idx)]
im_da... | 42383dffc3f69b2a8620b010c73081ee4c64d3e3 | 206,925 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.