content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def get_copyright_strings(tested_strings):
"""
Checks input strings and returns them in list
:param tested_strings: The list of some stings
:return: The list of selected strings
"""
copyright_strings = []
for tested_string in tested_strings:
if re.search(r'.*[Cc]opyrigh... | 8a2a3d684eb81b930b3d7f6cc7420b3a5e95c499 | 632,530 |
def strip_unit(value, unit):
"""Strip off any units and return value in unit"""
if not unit.is_quantity(value):
return value
return value.value_in_unit(unit) | b6ec2ec827eebe5198702c321a49f71380c27232 | 632,532 |
import re
def is_valid(f: dict) -> bool:
""" Compare an f to the policy """
BYR_MIN = 1920
BYR_MAX = 2002
ECL_VAL = ("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
IYR_MIN = 2010
IYR_MAX = 2020
EYR_MIN = 2020
EYR_MAX = 2030
HCL_REG = r"^#[0-9a-f]{6}$"
HGT_CM_MIN = 150
HGT... | 2546eb292ad1b910d0c8b8258067994aa0ee9e07 | 632,533 |
from typing import Tuple
def _split_time_units_attr(units_attr: str) -> Tuple[str, str]:
"""Splits the time coordinates' units attr into units and reference date.
Parameters
----------
units_attr : str
The units attribute (e.g., "months since 1800-01-01").
Returns
-------
Tuple[s... | 95da70dadca4259cc3e536dc9802af40d1c5208f | 632,534 |
from typing import AsyncIterable
from typing import Set
async def contains_all(async_gen: AsyncIterable[str], keywords: Set[str]) -> bool:
"""
Check wether an ``AsyncIterable[str]`` contains all of the given keywords. The keywords
can be embedded in some larger string. Return ``True`` as soon as all keywo... | 77bea74eacd3f7f33d4ee5e52db2cc10d1e2dd27 | 632,536 |
def unit_test(test):
"""
Mark all test (suites) with this decorator that test isolated functions classes optionally
with mocked out dependencies.
Unit tests should live next to the file there testing with a *_test.py suffix,
e.g. `foo_test.py` next to `foo.py`.
"""
return test | ee2d198998d6edb7f0e6127d957eaac981504e14 | 632,537 |
import hashlib
def md5(filename):
"""Helper method to find the Md5 checksum of the file.
Args:
filename (str): Path to the file.
Returns:
str: Hexdigest of the file.
"""
try:
hash_md5 = hashlib.md5()
with open(filename, "rb") as in_file:
for chunk in... | b86d5e8a81e43c45a2a171b26d8d8914e031b95c | 632,538 |
def condicao_pontuacao(arq):
"""
-> função que define qual será o valor da pontuação do jogador segundo a dificuldade das questões.
:param arq: é o nome do arquivo txt.
:return: retorna o valor da pontuação.
"""
if arq == 'perguntas-faceis.txt':
return 1
elif arq == 'perguntas-medias... | 881b5414810c0e5bda1ed4e8e73586cd1d7744d8 | 632,539 |
def get_close_edges(edges, nids_close):
"""this seems like it could be a lot faster"""
#n1 = edges[:, 0]
#n2 = edges[:, 1]
close_edges = []
for edge in edges:
(n1, n2) = edge
if n1 not in nids_close and n2 not in nids_close:
continue
close_edges.append(edge)
... | e322e3fe74bfeb1a09c302e063b282ae2b132281 | 632,541 |
def convert_list_of_link_ids_to_network_nodes(network, link_ids: list):
"""
Extracts nodes corresponding to link ids in the order of given link_ids list. Useful for extracting network routes.
:param network:
:param link_ids:
:return:
"""
paths = []
connected_path = []
for link_id in ... | 25f0c2a6a20a902627bca79fb6ed76b274ed50df | 632,542 |
from typing import Tuple
def _merge_points(
player: Tuple[int, ...], opponent: Tuple[int, ...]
) -> Tuple[int, ...]:
"""Merge player and opponent board positions and return the combined points."""
return tuple(
i + j for i, j in zip(player, tuple(map(lambda n: -n, opponent[::-1])))
) | dcc10f5763f3f8cec115992a5f96faab77d8c1d4 | 632,543 |
import re
def natural_sort(key):
"""Sort numbers according to their value, not their first character"""
return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)] | af9de4e345a2b85fa27285d935a9312f0a3a086e | 632,544 |
def median(values):
"""Returns the central (median) value of a list.
If the list has an even amount of numbers,
then the average of the two
central numbers shall be returned.
Args:
values (list)
Returns:
float: The central value"""
if len(values) == 0:
return None
... | d0ec6bbf2642fbd00623bc53d00992cb306f917e | 632,546 |
import functools
import sys
from warnings import warn
def is_linux_command(f):
"""Decorator wrapper to check if GDB is running."""
@functools.wraps(f)
def wrapper(*args, **kwds):
if sys.platform.startswith("linux"):
return f(*args, **kwds)
else:
warn("This command o... | c05997a72d113493e7f8a5b3397847b25712524b | 632,547 |
def arm_architectures():
"""
:returns tuple: all available Android architectures.
"""
return "armv7", "arm64" | 54b4c010329201304db6a9a0af88bc55281f8c73 | 632,548 |
def not_(x):
"""Support `not x` syntax"""
if bool(x):
return False
return True | f30d1b8e5774e4fbaa0fcb419da7debb0658f29d | 632,549 |
def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.jo... | d6120f9500bb7be879929204938444341d3178e0 | 632,550 |
def batch_sum(x):
"""Sums a tensor long all non-batch dimensions"""
return x.sum(tuple(range(1, x.dim()))) | f62ae269a632b9b4ef95d8e9d0276e0fad16b203 | 632,551 |
import re
import json
def parse_json(filename):
""" Parse a JSON file
First remove comments and then use the json module package
Comments look like :
// ...
or
/*
...
*/
"""
# Regular expression for comments
comment_re = re.compil... | 68e159e33ae3c2001559e84e4bef4c10dbedfcdc | 632,552 |
def extract_tags(drupal):
"""
Extracts tags from Drupal database. While being extracted the tags will be
stripped of forward slashes ('/'), replacing them with hyphens ('-').
Tags do not exist in Zinnia as objects of their own, so no creation of tags
needs to take place there. This function will ma... | d5f8a1c95ebf66d1191711edb7431f396c18a9fe | 632,553 |
import MySQLdb
import sys
def searchFGSSUniqueObjects(conn, candidate):
"""searchFGSSUniqueObjects.
Args:
conn:
candidate:
"""
# MOTE: in this query we DON'T select the max warp ID. This could lead to problems if the data is
# reprocessed. The query would need to be redesigned t... | 6f571d7021f776c66d6106449eaeaaa8ddcc1b1b | 632,554 |
def sub_sum(nums, target, low=0, high=0, current_sum=0):
"""Finds the first subarray of nums that sum to target, and returns the weakness."""
if current_sum == target:
return min(nums[low : high + 1]) + max(nums[low : high + 1])
elif current_sum > target:
return sub_sum(nums, target, low + ... | 81ba8d20fcb2393ffaab41d3109da5e45bb18939 | 632,555 |
def field_type(field):
"""
Retrieves the type of a given field.
:param DjangoField field: A reference to the given field.
:rtype: str
:returns: The type of the field.
"""
return field.get_internal_type() | b10b657f11a857224784f88e17f021333288a567 | 632,556 |
def add_simple_repr(cls):
"""
A decorator to add a simple repr to the designated class.
:param cls:
a subclass of :class:`~neuralnet_pytorch.layers.Module`.
"""
def _repr(self):
return super(cls, self).__repr__() + ' -> {}'.format(self.output_shape)
setattr(cls, '__repr__', ... | 55e6ba801e51a7e4286f6826e3f6a7ab70123e6f | 632,559 |
def _get_command(rouge):
"""
Return the command to invoke the perl script from a Pythonrouge.
:param rouge:
:return:
"""
cmd = rouge.set_command()
return ' '.join(cmd) | aa953a36becb47bb9a9c1fdab8e41f84bb8a80fe | 632,560 |
def base4Encode(n, d):
""" Convert decimal notation to quaternary notation
We will use division and modulus recursively
n = decimal number
d = number of digits for quaternary representation
>>> base4Encode(22, 4)
[0, 1, 1, 2]
"""
alphabet = [0, 1, 2, 3]
quat = []
base = len(alp... | 93dab051aeafeea0301cf6842f8108a9f92f6453 | 632,561 |
def travelStatistics(averageSpeed, duration, kmPerLitre):
""" travelStatistics
Converts the distance and duration of a car journey
to the amount of fuel used in liters assuming a
fuel efficiency of 5km/litre.
passes:
averageSpeed:
Takes in average speed in kilometers per hour.... | ce14f081c6449974570a6f6fc1681f984e0e9975 | 632,563 |
def test(news, target, value):
"""Compare the given value against the existing value in target. If they match, the test
passes. If they do not match, the test fails and the ENTIRE patch should be cancelled. Any
changes in the earlier steps of the current patch must be rolled back."""
if target == "/titl... | a5f457086d7aa697f03bf19c42ba91aee4e8f40f | 632,564 |
def Appliquer(auto, char):
""" Applique une chaine a un automate et renvoie le dernier etat acceptant (ou -1 s'il n'y en a pas) """
etat = 0
i=0
final = -1
while i<len(char) and etat != -1:
#~ print char[i], etat, auto.delta[etat][ord(char[i])]
etat = auto.delta[etat][ord(char[i])]
if etat in auto.F:
fi... | bc7d28d2e2455164748440da87a496ffd1440c24 | 632,565 |
import torch
def numpify(func):
"""Wrapper so that the augmentation function always works on a numpy
array, but if the input `imgs` is a torch tensor, a torch tensor will be
returned. Assumes first input and first output of the function is the
images array/tensor, and only operates on that."""
de... | 7906a0f23ac90460123c807d414d53b5c915b00f | 632,566 |
def json_dict():
"""What CoreNLP would return for 'Belgian swimmers beat the United States. Really?'"""
return {u'sentences': [{u'index': 0,
u'parse': u'SENTENCE_SKIPPED_OR_UNPARSABLE',
u'tokens': [{u'after': u' ',
u'before':... | 8ed48c8118877d78b5ab66a3f35e3130a1a210d7 | 632,568 |
def normalize(df, data_params):
"""Apply data scales.
Applies data scaling factors to df using data_params.
Args:
df (pd.DataFrame): with columns 'ds', 'y', (and potentially more regressors)
data_params (OrderedDict): scaling values,as returned by init_data_params
with ShiftSca... | 3e84c8791317225e0225da744a32fe543d03b142 | 632,569 |
def get_phase_start_stop(data):
"""
Get start and stop for a phase or subphase from the input time series data where start is
indicated by a value of 1 and stop is indicated by a value of 0 in the time series data
:param data: the time series data list
:return: the indices in the data list for the s... | e27671bbff0b18e87f858bb304df33c6af94d0b4 | 632,570 |
def get_remote_files(dataset, filenames):
"""Fetches remote files from the datasets, in chunks of 100 filesnames at a time"""
remote_files = {}
for i in range(0, len(filenames), 100):
chunk = filenames[i : i + 100]
for remote_file in dataset.fetch_remote_files(
{"types": "image,p... | 19028332166594d23df8caa47d39146ba8d8b497 | 632,571 |
import pickle
def read_pickle(filename):
"""Read object from pickle format.
Parameters
----------
filename : str
Input file.
Returns
-------
obj : object
Python object.
"""
with open(filename, "rb") as f:
return pickle.load(f) | 6852366add1352af3953279baf7c8d95085d6ea7 | 632,573 |
def kernel_file_name(ns):
"""Given kernel info namespace, return reasonable file name."""
assert hasattr(ns, 'length')
length = ns.length
if isinstance(length, (tuple, list)):
length = 'x'.join(str(x) for x in length)
postfix = ''
if ns.scheme == 'CS_KERNEL_STOCKHAM_BLOCK_CC':
... | 5f8f9a491c1ee84ccc1cacf58d1d557ea59a8239 | 632,574 |
import time
import random
import requests
def _get_page(url, s=None):
"""
Utility function to play nice when scraping.
This will also fetch a page according to a session or a simple get.
"""
if not url:
# What's a proper null requests object?
return None
# Play nice
time.s... | dd3899c7844c608128b34ab7e9ece03f7b6ad95d | 632,575 |
from dill import pickles
def badtypes(obj, depth=0, exact=False, safe=False):
"""get types for objects that fail to pickle"""
if not depth:
if pickles(obj,exact,safe): return None
return type(obj)
return dict(((attr, badtypes(getattr(obj,attr),depth-1,exact,safe)) \
for attr in ... | e66ca1e8ebf344f23834d38372a0bfad81481687 | 632,576 |
def only_first_4_patches(tensor, n_imgs=4):
"""
Batch truncation function
:param tensor: batch
:param n_imgs: number of patches to keep
:return: truncated batch
"""
return tensor[0:n_imgs] | b2ce39bda459392a7251f1ff3659be8064f6a68b | 632,578 |
def params():
"""
Returns default values constant values for the model in a dictionary.
"""
c = 1e0 # constant tunes duration of infection
params = {
't_0':0, # h - Initial time value
't_f':5, # h - Final time value
't_den':1e-4, # h - Size of time step to e... | c074fb0265af11b13efa02fa2f8a9208962cd864 | 632,579 |
def dependencies(thing):
"""Dependencies which must be sampled before this value."""
return getattr(thing, '_dependencies', ()) | 285a08ff63dd266dfc3435fc5706480395ca17b8 | 632,580 |
def _dsuper_list_td(t, y, L_list):
"""
Auxiliary function for the integration.
Is called at every time step.
"""
L = L_list[0][0]
for n in range(1, len(L_list)):
L = L + L_list[n][0] * L_list[n][1](t)
return L * y | d8dfebdcfa3af600dd42c4a45e4229e75dfa0838 | 632,581 |
def _add_dates_to_sections(schedule):
"""
Adds term start/end dates to sections that do not have them (ie non-PCE)
"""
for section in schedule.sections:
if section.start_date is None:
if section.summer_term == "B-term":
section.start_date = schedule.term.bterm_first_... | f167b9a28795fa14f9432cfe1a63f4ea770e049b | 632,582 |
def GetSettingNames():
""" Return list of dictionary keys of selected settings and results. """
return ['board_ids', 'servo_version',
'ExecCycle', 'ExecStepSize'] | 85a3bca636edfaf2eda6ba0019e3cc5b933e39bc | 632,585 |
def truncate_after(d, n):
"""Truncate first timestamp dictionary D after N entries."""
sorted_lst = sorted(d.items(), key=lambda a: a[1][0])
return dict(sorted_lst[:n]) | 8fb7695c72c9df481a5b72fda77ed76e283338d4 | 632,586 |
def round_off(value, digits=2):
"""
Rounding off the value
:param float value: Value to be rounded
:param digits: Digit to kept as after point
:return float: Rounded value
"""
return float(("{0:.%sf}" % digits).format(value)) | 5958e158aed07ab66923b215d93403a59f11b718 | 632,587 |
def hamming_distance(str_1: str, str_2: str) -> int:
"""Return the hamming distance between two strings of equal length
Arguments:
str_1 {str} -- first string
str_2 {str} -- second string
Returns:
int -- hamming distance
Example:
>>> hamming_distance("ATATACATACGCG... | a7fe6f340242c77084eb9aa72be656fdc965cf23 | 632,588 |
import base64
def DecodeWithKey(key, string):
"""
Decode with Key
Takes your encoded string and decodes it with another string(key)
string = "w5PDisOlw5fDlA=="
key = "key"
>> "Hello"
"""
dec = []
enc = base64.urlsafe_b64decode(string).decode()
for i in range(len(enc)):
... | 0b3ea70824ddf832b270d719d4d420f7a8a8fdeb | 632,589 |
import pyarrow
def deserialize(data):
"""
Deserialize bytes into an object using pyarrow
Args:
bytes: a bytes object containing serialized with pyarrow data.
Returns:
Returns a value deserialized from the bytes-like object.
"""
return pyarrow.deserialize(data) | 9b347cf5b7208934167e13d05c2ed16e48e8f926 | 632,590 |
import os
import zipfile
def unzip_data(folder, zip_file_basename):
"""unzip data from folder data outside of foreanalyzer"""
# path
filename = os.path.join(folder, zip_file_basename + '.zip')
new_folder = os.path.join(os.path.dirname(__file__), 'data')
if not os.path.isdir(new_folder):
os... | bdc401a54e9d81e0639abbd7469b8695f6e6a6ff | 632,591 |
def createTwoDimensionBoard(height=3, width=3):
"""
Create a array in 2 dimensions fill with ' '
"""
return [[' ' for i in range(width)] for j in range(height)] | 091a71244c89e8b918e0eeea5142511b589673d4 | 632,592 |
def getSpellDamageType():
""" Returns the character attribute corresponding to spells """
return "_magic" | b9afd92efdd7de256bb536d71183e597e5f5db53 | 632,593 |
def apply(object, args=None, kwargs=None):
"""Call a callable object with positional arguments taken from the
tuple args, and keyword arguments taken from the optional dictionary
kwargs; return its results.
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
return ... | f80ff050e2d4ababf23d44bddb599e13bbc23353 | 632,595 |
import configparser
import os
import click
def get_config():
"""
Get the information about config file path
:return: ConfigParser object
"""
config = configparser.ConfigParser()
home_dir = os.path.expanduser('~')
paths = [
os.path.join(home_dir, '.config', 'transtats.conf'),
]
... | 05472bd79e214448857e0cfc477ec92c6785ab8f | 632,596 |
def particle_id(part):
"""Get the atoms of the particle"""
out = ""
for a in part.A:
out += str(a)
return out | d47b29ea804d855328d1faa7ef1c013efcd272e9 | 632,597 |
def given_geotransform_and_projection_string(geotransform, wkt_projection_string):
""" return dict with geotransform and projection_string loaded from WKT file """
return dict(geotransform=geotransform, wkt_projection_string=wkt_projection_string) | 742a1b7fc70c0cc494e697af8b33945946e0c09e | 632,598 |
def get_item_hrefs(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be... | 0fd2921c1799571eb015cfdec94d27ed3c34e14b | 632,599 |
import os
def filelist_exists(filelist):
"""Check that all file in the list exists
Parameters
----------
filelist : dict of paths
List containing paths to files
Returns
-------
bool
Returns True if all files exists, False if any of them does not
"""
return all({k... | 33512268593975e317a85580193801cdd4ac20bb | 632,600 |
def Sign(number):
"""
Sign(number)
Return the mathematical sign of the given number.
"""
return number and (-1, 1)[number > 0] | 7a7c4dae06df05715c4d4dd0680b000bccb924d4 | 632,601 |
def fillcompanyrow(table, companynumber, window):
"""
:param table:
:param companynumber:
:param window:
:return:
"""
sqlstring = 'SELECT * from Company WHERE ID = ? ; '
try:
# print('fillcompanyrow sqlstring, companynumber =>', sqlstring, companynumber)
companyrow = ta... | 27448a574eb036959fb0ee3af96a1bf8af528347 | 632,602 |
import torch
def clip(vals: torch.Tensor, minimum: float, maximum: float) -> torch.Tensor:
"""Clips values to fit within range."""
clipped = torch.max(vals, minimum * torch.ones(vals.shape))
return torch.min(clipped, maximum * torch.ones(vals.shape)) | 5bdd5aa02b029e4cb1f6c7c02ffd4330d5ed6fdd | 632,603 |
import argparse
def parse_args(args):
""" Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Evaluation script for a RetinaNet network.')
parser.add_argument('imgDir', help='Path to image folder.')
parser.add_argument('model', help='Path to RetinaNet... | 42d9222b74f676d0b02801bc79770483f18bd3c4 | 632,604 |
def secondLargest(a_list):
"""assumes a_list is a list of numbers
returns the second largest element of a_list
"""
largest = max(a_list)
a_list.remove(largest)
return max(a_list) | ab3090a50fbe44664f9049ea8276109c8062156a | 632,605 |
def get_img_url(img_src, url_base):
"""
Get an image url from the src attribute af an image, and the page base url
"""
if not img_src:
return None
if not "//" in img_src: ## it's not an absolute url
if img_src[0] == "/":
img_src = img_src[1:]
img_src = url_base + ... | 858222ab82e34615a6c57f175757b5708d7ded32 | 632,606 |
def fix_tab_spaces_for_keywords(instring, spaces=8):
"""
After the convert_tabs_to_spaces function converts tabs to spaces, this function checks the
First word in each line and adds enough spaces to bump it up to the total number of spaces
per tab (default is 8).
"""
lines = instring.split('\n')... | 22c7ee7924d7f5d4148ab8a9e856b43bd088d82b | 632,607 |
def c2hex(char):
"""Convert to HEX (2 bytes)."""
return "{:02x}".format(ord(char)) | fb6811e800ec3a8423b34007f793976ea10e8ecd | 632,608 |
def last_replace(s, old, new, number_of_occurrences):
"""
Replaces last n occurrences of the old string with the new one within the string provided
:param s: string to replace occurrences with
:param old: old string
:param new: new string
:param number_of_occurrences: how many occurrences shoul... | 0cfa60e46694cb28f731c4adb0d912af3bf6bd06 | 632,609 |
import array
def check_already_checked(is_ids, fs_ids, sorted_ids, process, model,
id_anti_id_dict = {}):
"""Check if process already checked, if so return True, otherwise add
process and antiprocess to sorted_ids."""
# Check if process is already checked
if id_anti_id_dict:... | b323c388f94fda9f91d089079b92a78fdb420d8c | 632,610 |
import json
def open_data_file():
""" Opens the saved_data.json returns the dic.
:return: dict()
"""
with open("saved_data.json", 'r') as glob:
data = json.load(glob)
return data | 44da0b77a9636ddc19525a7e6135c9412108600a | 632,611 |
import torch
def rgb_to_rgba(rgb: torch.Tensor, fill: float = 1.0):
"""
Converts tensor from 4 channels into 3.
Alpha layer will be filled with 1 by default, but can also be specified.
[... 3 H W] -> [... 4 H W]
"""
alpha_channel = torch.full_like(rgb[..., :1, :, :], fill_value=fill)
retur... | 89f7cdaca63194eaa1ec5fd61133448a8db1584a | 632,612 |
def keylen(key):
"""Return the length of the input, <key>"""
return len(key[1]) | 28acbcc307d89722e4f20794cd7fb77a24704a52 | 632,613 |
def ang_mom_rce_lh88_zero_large_r(lat_max, thermal_ro=None):
"""LH88 forcing abs. vort. zero cross approx; large thermal Ro."""
return lat_max | c344f02050307bf1806070b2884def6c5ac6715a | 632,614 |
def passes_filter_ensembl(segment):
"""Decide whether segment passes filters for ENSEMBL data."""
# Remove non-coding transcripts
if not segment.attrs["gene_biotype"] == "protein_coding":
return False
support_level = segment.attrs.get("transcript_support_level", "")
if not support_level.isd... | 3b524e1edd060b060fa4b72fa1b49dc685951cc3 | 632,615 |
def link(href, text):
"""Generate a link"""
return '<a href="' + href + '">' + text + '</a>' | 09348acd2eac36dbb1cb769533f11d5816724744 | 632,616 |
def rel_to_abs(vector, cell):
"""
converts interal coordinates to absolut coordinates in Angstroem.
"""
if len(vector) == 3:
postionR = vector
row1 = cell[0]
row2 = cell[1]
row3 = cell[2]
new_abs_pos = [
postionR[0] * row1[0] + postionR[1] * row2[0] + ... | 404dbc81a9993f147956cff2043ba368515482ea | 632,618 |
def getDuplicateElements(lst):
""" Return the elements that are duplicated in list """
if lst == None or type(lst) != list:
raise ValueError("lst must be a list.")
return list(set([x for x in lst if lst.count(x) > 1])) | b7a17120e2394094a0d94cbfa21434f0b66d40e8 | 632,619 |
def std(image):
"""The standard deviation of pixel intensities"""
return image.std() | 10bb9e0d2df7b5ba1821b5c8e2318ea30dd80249 | 632,621 |
def ok(message, data=None, http_status_code=200, **kwargs):
"""
used when no error
:param message: some message
:param data: data for return
:param http_status_code: http status code
:param kwargs: other data for return
:return:
"""
return {"message": message, "data": data, **kwargs}... | 6e7f40c8ce07a10b17ee7e2b9fcdba9f0348f1cd | 632,624 |
def copy_docstring(source):
"""Decorator function to copy a docstring from a `source` function to a `target` function.
The docstring is only copied if a docstring is present in `source`, and if none is present in `target`. Takes
inspiration from similar in `matplotlib`.
Parameters
----------
... | 0f78b2a04f1e4a082c88e4f89ee525d0d27ed6bc | 632,626 |
from typing import Mapping
from typing import Any
def update_analytics_params(stream_slice: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Produces the date range parameters from input stream_slice
"""
return {
# Start date range
"dateRange.start.day": stream_slice["dateRange"]["start.da... | ce3f4938dae50cae35f6f83c6e3f6e621e7db0cf | 632,627 |
def _mesh_to_surf_cards(mesh, divs):
"""Prepares the surface cards for mesh_to_geom."""
surf_cards = ""
count = 1
for i, dim in enumerate("xyz"):
for div in divs[i]:
surf_cards += "{0} p{1} {2}\n".format(count, dim, div)
count += 1
return surf_cards | 911e14db3e0b5fb6a1f8fec76cae9e6c20be50c0 | 632,628 |
from typing import Counter
def to_inttuple(bitstr):
"""Convert from bit string likes '01011' to int tuple likes (0, 1, 0, 1, 1)
Args:
bitstr (str, Counter, dict): String which is written in "0" or "1".
If all keys are bitstr, Counter or dict are also can be converted by this function.
... | d67417120c890ed1bc0f16066cb75d767b0c3e10 | 632,629 |
def getTransitions(p):
"""
Retreive transitions of a specific path/sequence
"""
transitions = []
for pos in range(len(p)):
if pos == 0:
transitions.append(str(pos) + "." + p[pos])
else:
insert = p[pos - 1] + p[pos]
transitions.append(str(pos) + ".... | 57771131bf184b688729aed99dc18023ba42287d | 632,630 |
import sys
def recover_old_swaps(text_file, swaps, source):
"""Add commands to recover old vim swap files"""
if len(swaps) > 1:
print('Too many swaps: %r' % ','.join(swaps), file=sys.stderr)
return False
swap = swaps[0]
source.add('pre_vimming "%s" "%s"' % (text_file, swap))
return... | eb72a7bd208a7810bc5442e32a599c5751d5534a | 632,631 |
def normalize_component(value):
"""Normalize component to be in the 0 - 255 range"""
if value < 0:
return 0
if value > 255:
return 255
return value | 3e09599ac2407c440f5e01f260dba762371ed195 | 632,632 |
def move_matrix(coef,mat_1,mat_2,add_mat):
"""
Do matrix calculations without messing with numpy.
Inputs:
coef: coefficient for the current matrix combination
centroid: the centroid matrix
point: the point by which to alter the centroid
Output: a single combined matrix, represe... | c84970db7cfda4fb7ecb94178df6efa4fd139262 | 632,633 |
def _constraint_lb_and_ub_to_cplex_sense_rhs_and_range_value(lb, ub):
"""Helper function used by Constraint and Model"""
if lb is None and ub is None:
raise Exception("Free constraint ...")
elif lb is None:
sense = 'L'
rhs = float(ub)
range_value = 0.
elif ub is None:
... | d3f33e5c208f9e596e843ff09f50b9358591f49c | 632,634 |
def remove_empty_fields(obj: dict) -> dict:
"""
Removes empty fields from NetBox objects.
This ensures NetBox objects do not return invalid None values in fields.
:param obj: A NetBox formatted object
"""
return {k: v for k, v in obj.items() if v is not None} | 984a02de6891bf8a73b9db60ca713db2641080c0 | 632,635 |
def is_whitespace_only(line):
"""
Checks if the given line contains only whitespace.
:param line: The line to check.
:return: True if the line contains only whitespace, False if not.
"""
return line.strip() == '' | 6f77dab7f8b5d501ca7d04f80f5974066352063d | 632,636 |
import logging
def dataset_factory(*args, **kwargs):
"""Factory to get correct dataset class based on name
Parameters
----------
dataset_class_name : str
Class name
Default value "None"
Raises
------
NameError
Class does not exists
Returns
-------
Dat... | 4374ea73fc3ea301506a00f0bf37937bdb975bc6 | 632,638 |
def _popcount(int):
"""Returns the number of 1 bits in the input."""
count = 0
for bit in range(0, 32):
count = count + ((int >> bit) & 1)
return count | ebb44b854796a2d764d0269c09bc5bf0670d5cc1 | 632,639 |
import torch
def try_gpu(i=0):
"""
Return gpu(i) if exists, otherwise return cpu().
Extracted from https://github.com/d2l-ai/d2l-en/blob/master/d2l/torch.py
"""
if torch.cuda.device_count() >= i + 1:
return torch.device(f'cuda:{i}')
return torch.device('cpu') | 6873cde1b824cfdea2687d821076bb8d450e49d8 | 632,640 |
def pad_arguments_np2cv(padding_mode):
"""
numpy's pad and OpenCVs copyMakeBorder can do the same thing, but the
function arguments are called differntly.
This function takes numpy padding_mode argument and returns the
corresponsing borderType for cv2.copyMakeBorder
Parameters
----------... | 1950f85194c44983e49cf22775475ddb6ee7968c | 632,641 |
from typing import Sequence
def array_to_sentence_string(
array: Sequence[str],
connector: str = "and",
) -> str:
"""Join an array of things into a string by separating with commas and the
word "and" for the last one.
Args:
array: The Array of Strings to join.
connector: Word used... | 52562b2c30968034ca83e77acdca516ef19909f4 | 632,642 |
import os
def _transform_node_source(source):
"""Transforms a source file into the same format node.js expects.
Args:
source: Source file contents.
Returns:
Transformed contents.
"""
wrapped = ('(function (exports, require, module, __filename, __dirname) {'
' %s });') % (source)
ret... | 6dbff569452c1289aad8f6f969516b61ff3f98e1 | 632,643 |
import io
def image_models_to_csv(images: list):
"""
Given a list of Image models, convert the result to an in-memory CSV. This allows faster transfers to the database
via COPY FROM.
"""
csv_images = io.StringIO()
for image in images:
row = '\t'.join(list(image.values())) + '\n'
... | dbb7a28e51196c4a2159f62a7afb41218ca44577 | 632,644 |
def sort_values(df, columns, order='asc'):
"""
Sort DataFrame
:param df: DataFrame
:param columns: name of the columns to sort
:param order: asc or desc
:return: DataFrame
"""
ascending = order != 'desc'
return df.sort_values(columns, ascending=ascending) | 0d9498ca04ac8730548c1e54de0fbb79f6a97889 | 632,645 |
def degrees_converter(celsius):
"""
Converts degrees to farenheit
"""
return celsius * 9/5 + 32 | 1b7bbe7ed4cc04f13d97b552138c6aec5ccd5fe8 | 632,646 |
def Umidi2Ubeats(tmidi, time_signature):
"""
Converts time in the MIDI's units (quarter note) to beat units.
"""
compass = time_signature.copy()
compass += [[1E99, "None"]] # for last compass to be taken in consideration
tbeat = 0
for i in range(len(compass)-1):
c = compass[i][1]
Y = int(c.split("/")[1]) #... | 6ce1cfe996d6a6c5685edefb9f1b0f5e6bbb5b2f | 632,647 |
import os
def _get_my_infos(cfg):
"""Put files in dicts of datasets and return them."""
info_dict = {}
for filename, attributes in cfg['input_data'].items():
base_file = os.path.basename(filename)
dataset = base_file.split('_')[1]
info_dict[dataset] = {}
info_dict[dataset][... | fdfda3b030fa3b95ad1137f4cab7a0c50cbeade8 | 632,648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.