content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import pickle
def get_scale_and_offset(env_name: str):
"""
Returns the values that were used to normalize to derive the saved PPO/TRPO models.
Parameters:
env_name (string): Name of the environment whose normalization values are to be fetched
Returns: The scale and the offset values
"""... | cc7739e8d05fe4b3f27bb4d444de7e7dbd166f2a | 604,876 |
def dec_to_bin(decimal_number: int) -> str:
"""Convert decimal number to binary.
Examples:
>>> dec_to_bin(5)
'101'
>>> dec_to_bin("Q")
Traceback (most recent call last):
...
ValueError: Integer value expected!
"""
# Check for correct argument type.
if not isi... | bdb53301ef0f1a833630667dc6d477143b44e426 | 604,878 |
def is_private_field_name(name: str) -> bool:
"""
A private field is any Python class member that starts with an underscore eg: _hello
"""
return name.startswith("_") | 6e5564fc476cfb336724b76ecf00b33ff13f4ca9 | 604,879 |
def yes_or_no(question):
""" Get a y/n answer from the user
"""
while "the answer is invalid":
reply = str(input(question+' (y/n): ')).lower().strip()
if reply[:1] == 'y':
return True
if reply[:1] == 'n':
return False | 31990e3e6eb6274a0786583ae3ece8c57dfce7b1 | 604,880 |
def calc_storage_percentage(storage, total_storage):
"""
Calcualates the percentage for the amount of storage provided to the network.
Params:
- storage: Amount provided to the network
- total_storage: total storage in the network
Returns:
The percentage of contribution
"""
... | 5d152a0200e02a7e3830c844e650513439fa056e | 604,885 |
def find_value_after_0(steps, target):
"""Find value after 0 when target is inserted, with number steps each."""
position = 0
cur_value = 0
for number in range(1, target + 1):
position = (position + steps + 1) % number
if position == 0:
cur_value = number
return cur_value | 63d2c684f4d4d0d1277b6d5cd75dc7e5b37632ae | 604,886 |
def _page_arg(p):
# type: (int) -> str
"""Create a page argument from int."""
return 'page=' + str(p) | 1c9d02800d108870ca7c9e210428f70a87082f58 | 604,888 |
def matrix_times_first_dim(A, X):
"""Take matrix A times vector X[:, i1, i2, i3, ... , in] separately
for each i1, i2, i3, ..., in. Same output as A @ X if X is 1D or 2D"""
# flatten all dimensions of X except first, then multiply, then restore shape
return (A @ X.reshape(X.shape[0], -1)).reshape(X.shap... | 46e04e8b532ab2a6e2c3e47a7e5cd5e910647288 | 604,889 |
from typing import List
def flatten(inp: List[list]) -> list:
"""
Creates a single list out of a list of lists
Parameters
----------
inp : `list`
The list of lists
"""
return [i for sub in inp for i in sub] | 9b863c7027f39463c188bc98337dd0eac542f962 | 604,890 |
def eat_comment(s):
"""Eat comment string after # char."""
n = s.find('#')
if n >= 0:
return s[:n]
else:
return s | 848d140fd17e87b3f12064a676770af7a0437aca | 604,893 |
def content_type(model):
"""
Return the model name/"content type" as a string e.g BlogPage, NewsListingPage.
Can be used with "slugify" to create CSS-friendly classnames
Usage: {{ self|content_type|slugify }}
"""
return model.__class__.__name__ | 5421dfa736df0a85edf89fcb2a0021bb0b018086 | 604,895 |
def _udev(udev_info, key):
"""
Return the value for a udev key.
The `key` parameter is a lower case text joined by dots. For
example, 'e.id_bus' will represent the key for
`udev_info['E']['ID_BUS']`.
"""
k, _, r = key.partition(".")
if not k:
return udev_info
if not isinsta... | 54129c5379a256d5f30c68c2ccf2a6a61b6dc4d3 | 604,899 |
def kv_iter(ds):
""" Iterator for key-value structure, list and dict """
if isinstance(ds, list):
return enumerate(ds)
elif isinstance(ds, dict):
return iter(ds.items())
else:
raise ValueError(type(ds)) | b93c4891c0cf6e967feb4881046d8530ca9faaba | 604,907 |
def beam_area_pix(head):
"""
Computes the beam area in pixels.
It uses an approximation accurate to
within 5%.
K. Rohlfs and T.L. Wilson, 'Tools of Radio Astronomy', third revised and enlarged edition, 1996, Springer, page 190-191.
:param head: Image header.
:type head: Fits header... | c92f72a7d06e113ec3377757ff9dec734d106e33 | 604,911 |
def compute_durations(df_samples):
"""Compute the time durations of periods, peaks, and troughs.
Parameters
---------
df_samples : pandas.DataFrame
Dataframe containing sample indices of cyclepoints.
Returns
-------
period : 1d array
The period of each cycle.
time_peak ... | 1b90f3c05dc221b7c0093a0af733823b807bddc3 | 604,912 |
def parse_attributes( fields ):
"""Parse list of key=value strings into a dict"""
attributes = {}
for field in fields:
pair = field.split( '=' )
attributes[ pair[0] ] = pair[1]
return attributes | 8ae4bf22a941718566cf034f5b03f8d783afc5a3 | 604,918 |
def PpapiDispatchFunctionHeader(scope, type_defn, variable, npp, success):
"""Gets a header for PPAPI glue dispatch functions.
This function creates a string containing a C++ code snippet that should be
included at the beginning of PPAPI glue dispatch functions like Call or
GetProperty. This code snippet will ... | 8aebf2010dc69ba33dc74a1b3babe60aec8e2eb8 | 604,921 |
import re
def _EndsWithTerminalQuote(s, quote_char):
"""Returns whether a string ends with a valid terminal quote."""
endm = re.search(r'(\\*)%s$' % quote_char, s)
if not endm:
return False
backslashes = endm.group(1)
if len(backslashes) % 2 == 0:
# Even number of backslashes preceding the quote mea... | 6533d82b26219fa23e965392e12b41c9b1cb432e | 604,926 |
def inverso_cuadrado(distancia: float) -> float:
"""
Realiza el cálculo del inverso al cuadrado de una distancia
"""
return 1 / (distancia ** 2) | 3d681739068950e7e0140dd22cfd692589227c0a | 604,930 |
import dataclasses
def build_dataclass_from_dict(data_class, dict_value):
"""
Convenience method building specified dataclass from a dictionary
Args:
data_class:
dict_value:
Returns: dataclass of specified type
"""
field_names = set(f.name for f in dataclasses.fields(data_cl... | da7850ec2795fe580f4878ef05d3f32b5dcb4c69 | 604,931 |
def controls_into_dic(how_many_parallel, parallel_processing,
output_type, outpfad, datpfad, indata, preddata,
outfiletext, with_output, screen_covariates,
check_perfectcorr, clean_data_flag, min_dummy_obs,
ft_no_of_evalupoints, max... | 46a8ed588eb6944a3d9a260d20ea3c67dcfa07cb | 604,932 |
def blend_normal(cb: float, cs: float) -> float:
"""Blend mode 'normal'."""
return cs | 19bc60e046b537050b02184a9c6cf05c4acb74e4 | 604,934 |
def _LinInterp(a, b, t):
"""Return the point that is t of the way from a to b.
Args:
a: tuple - coords of start point
b: tuple - coords of end point
t: float - interpolation parameter
Returns:
tuple (coordinates)
"""
n = len(a) # dimension of coordinates
ans = [0.0] * ... | 3d7b838ff530197c165abec7ee25f2751a69c722 | 604,939 |
def z_function(text):
"""
Z Algorithm in O(n)
:param text: text string to process
:return: the z_array, where z_array[i] = length of the longest common prefix of text[i:] and text
"""
n = len(text)
z_array = [0] * n
l = r = 0
for i in range(1, n):
z = z_array[i - l]
... | ed0552ca771865644b2df59c80bc3b785578fab5 | 604,940 |
def create_version(version, commit_id):
"""Create a version based on the version provided and the commit id"""
return "%s_%s" % (version, commit_id) | 0431b7e79f1b53943f1b51409dcf94ec45d03753 | 604,944 |
def convert_string_to_list_of_ints(string, sep):
"""Converts string to list of ints.
Args:
string: str, string to convert.
sep: str, separator string.
Returns:
List of ints conversion of string.
"""
if not string:
return []
return [int(x) for x in string.split(s... | 8de6b1ae913705527af0298227b90da1efdff1ad | 604,945 |
def check_object_no_parent_and_child(object_to_check):
"""Check if an object has not parent and not child"""
check = False
if not object_to_check.child_list and object_to_check.parent is None:
check = True
return check | bd3213190c1f7f9fda67fb6b4115a80958acc6c3 | 604,949 |
def get_flattened_tasks(tasks):
"""Return a set of all tasks and their ancestors in `tasks`."""
return set(t for task in tasks for t in task.flatten()) | 6b3b7f96113a868ae31340eb16e69c5e6d397049 | 604,952 |
import re
def meetDigitLength(exp, totalDigits):
"""
Check expression to see if it meets requirement for total digits
:param exp: math expression
:param lenRequired:
:return: True if requirement is met; False otherwise
"""
total_digits_list = re.findall('\d+', exp)
return all([len(i)==... | 300aa22b3ab3e104ff98568828584130efc0bcfb | 604,953 |
def reverse_domain_names(domains):
"""Return a list of reversed domain names."""
return [".".join(reversed(domain.split("."))) for domain in domains] | 0ad66d54d8bd51eae4fd0aab0b1a7e110ffb7cff | 604,955 |
import uuid
def get_cache_version() -> str:
"""Return a cache version that is regenerate after each cache invalidation."""
return uuid.uuid4().hex | 51cafc543b39f8d91c4706785d92e89d252d4d7d | 604,956 |
def display_warnings(_warnings):
"""
Return a string that displays a list of unexpected warnings
Parameters
----------
_warnings : iterable
List of warnings to be displayed
Returns
-------
msg : str
String containing the warning messages to be displayed
"""
if l... | 855f31ce6297b22ab15e5046adf991e261e74224 | 604,957 |
from typing import Tuple
import math
def reduce_to_coprime(number1: int, number2: int) -> Tuple[int, int]:
"""Divides given numbers by their greatest common divisor, thus making them coprime."""
gcd = math.gcd(number1, number2)
return number1 // gcd, number2 // gcd | 3ba0296ed9f62fda33a7d8dfd735692fb76e6317 | 604,959 |
import hashlib
def string_to_md5(string):
"""
Calculate the MD5 hash (message digest) of a given string.
Args:
string (string): An arbitrary string.
Returns (string): The MD5 hash (message digest) of the provided string.
"""
return hashlib.md5(string.encode('UTF-8')).hexdigest() | 8cf4517ae39bd9f705ee92fab61d832b80381d8d | 604,963 |
def split(string, divider):
"""Splits a string according at the first instance of a divider."""
pieces = string.split(divider)
return [pieces[0].strip(), divider.join(pieces[1:])] | 8d4f617aaa72b7faebf02d224dfa01b477004005 | 604,964 |
import json
def make_xheader(lms_callback_url, lms_key, queue_name):
"""
Generate header for delivery and reply of queue request.
Xqueue header is a JSON-serialized dict:
{ 'lms_callback_url': url to which xqueue will return the request (string),
'lms_key': secret key used by LMS to pro... | a9b30048f3d008a4f4219794e6d3f86c557e266e | 604,965 |
def get_assigned_team(participant, hackathon):
""" Return the team for the current hackathon for a participant """
participant_team = None
if not hackathon.teams:
return
teams = hackathon.teams.all()
participant_team = [team for team in teams
if participant in team.p... | 6e6f51d0b4f89e3c0caf9d1b1c60a7047dac8ab4 | 604,966 |
import random
def random_crop(img):
"""
Crop 54*54 from the resized img at random location.
Input:
img: np.array
Return:
random_croped_img: np.array
"""
left = random.randint(0, 10)
top = random.randint(0, 10)
return img[top:(top+54), left:(left+54)] | 177c6a8d7efde5b8f5542e2225ac83252c92bada | 604,967 |
def compute_school_holiday_lead(df, shift=-1):
"""Compute leading indicator for school_holiday."""
school_holiday_lead = df.groupby("store")["school_holiday"].shift(shift)
return school_holiday_lead.fillna(0).astype("double") | 8e916e6b27c064c1ec2aa9e0c4db095f38744081 | 604,968 |
from math import floor
def get_fixes_frames(n_frame, max_gap):
"""
等比例抽帧
:param n_frame: 总帧数
:param max_gap: 抽帧数量
:return: 帧索引
"""
idx_list = []
if n_frame > max_gap:
v_gap = float(n_frame) / float(max_gap) # 只使用100帧
for gap_idx in range(max_gap):
idx = i... | 1148e0307abb062bb14d24890bcf8d7996a155e6 | 604,969 |
def decode_cigar(cigar):
"""Return a list of 2-tuples, integer count and operator char."""
count = ""
answer = []
for letter in cigar:
if letter.isdigit():
count += letter # string addition
elif letter in "MIDNSHP=X":
answer.append((int(count), letter))
... | eba2027596a79511510fa6048bf8b8d963c13e13 | 604,972 |
def convert_frequency(frequency, units, line_number, errors, error_type):
"""
Converts the given frequency string to a Quantity containing a float
value and the given units
:param frequency: frequency value in string format
:type frequency: String
:param units: units of frequency for supplied m... | 2d7acc692a48dc84472b04815dfb118ddea06f84 | 604,973 |
import yaml
def load_yaml_configuration(yaml_path):
"""
Loads the structure learning method from the yaml file configuration.
:param yaml_path: the path of the yaml file
:type yaml_path: str
:return: the structure learning method
:rtype: StructureLearningMethod
"""
stream = open(yaml_... | 47e7c289742bbe802b1b69130030a1fba7bfbac6 | 604,975 |
def format_tag(something):
"""
if *something* is None, return "!None". Otherwise,
return *something*.
"""
if something is None:
return '!None'
else:
return something | 85ca9ddd6c6006c0e7f107fa1650c90322662425 | 604,981 |
def _PruneGitFiles(git_files, paths):
"""Prunes the list of files from git to include only those that are either in
|paths| or start with one item in |paths|.
Args:
git_files: List of all repository files.
paths: Prefix filter for the returned paths. May contain multiple entries,
and the contents... | 2adcc3276b57989155853599f2e0798d9f447713 | 604,984 |
from typing import List
import fnmatch
def match(filename: str, patterns: List[str]) -> bool:
"""
Checks if filename matches ANY of 'patterns'.
:param filename: A path of a file.
:param patterns: A list of standard UNIX file patterns.
:return: True if filename matches ANY of 'patterns', False othe... | bcd605aebb8fae34f1077352bc24dad33329b3a6 | 604,988 |
import random
def random_digit() -> int:
"""Generate a random digit (0 to 9)."""
return random.randint(0, 9) | 611270a004a495b3790b263cc8505c0e53e776cf | 604,989 |
def check_cgal_params(max_facet_distance, max_cell_circumradius, voxelsize):
"""Check CGAL mesher parameters.
# https://github.com/nschloe/pygalmesh#volume-meshes-from-surface-meshes
Parameters
----------
max_facet_distance
max_cell_circumradius
voxelsize : float
Image voxel size.
... | 077fe714be7eb5f68ed73336240be9422a5c894e | 604,991 |
def title(message, underline='='):
"""Return a string formated as a Markdown title.
underline argument will be printed on the line below the message.
"""
return '{}\n{}\n\n'.format(message, underline * len(message)) | 6010535755ff63d015731da7fbd1336f08fdc423 | 604,993 |
import string
import re
def normalize_answer(s, remove_articles=True, keep_punc=None):
"""Lower text and remove punctuation, articles and extra whitespace."""
def white_space_fix(text):
return ' '.join(text.split())
s = s.replace('_', ' ').lower()
exclude = set(string.punctuation + "".join([u"‘", u"’", ... | 7f8125cb14451f8b15047e1a060c08e1e05d5623 | 604,995 |
def line_at_index(string, index):
""" Returns the line at the given index of the given string.
"""
if index < 0:
index = index % len(string)
start = string.rfind('\n', 0, index)+1
end = string.find('\n', index)
suffix = '\\n' if end >= 0 else '\\0'
if end < 0:
end = len(stri... | 9234fe0b56c2e30c5c51458e47d370f36e08be3d | 604,996 |
def add_tab(title: str, htmlcode: str, comment_cell: bool = True) -> str:
"""Add new tab section for the report. By default adds an opinion editable box at the start.
Parameters
----------
title : str
Title associated with this tab / section
htmlcode : str
All HTML code contain with... | 4095a5e519c9ded04a67444a4b31bd5f023fb255 | 604,997 |
def extract_datapoint(program_output):
"""
Extract the 6 numbers from the program's output string.
"""
program_output = program_output.split()
ix = program_output.index("Found") + 1
pathsFound = float(program_output[ix])
ix = program_output.index("length:", ix) + 1
shortest = float(... | 73f24340d1822e3a8b11e02feb50c5d33b580acb | 604,998 |
import requests
def get_file_lines(url):
"""Returns the lines contained in the file at the given URL"""
# Download the file over the internet
response = requests.get(url, stream=True)
# Decode all lines into strings
lines = []
for line in response.iter_lines():
lines.append(line.deco... | bfbe583cd160e18998e8b2acd2911bd4a301e244 | 605,004 |
from typing import List
def to_str(lines: List[List[str]]) -> str:
"""Converts a parsed songsheet back into a string.
Args:
lines: A list of parsed songsheet lines
Returns:
A songsheet string.
"""
ret = ''
for i, line in enumerate(lines):
ret += ''.join(line)
... | 0157e2241be6b8a6c68a710546a18ce9844225e8 | 605,006 |
from typing import List
def _merge(indices1: List[int], indices2: List[int]) -> List[int]:
"""Merge the two list of the indices. Each list must be sorted.
--------------------
Args:
'indices1': A sorted list of the indices.
'indices2': A sorted list of the indices.
------------------... | fc755ccd036759fbea3f5a695341f5c8f0a9e7e0 | 605,009 |
import torch
def to(*args, dtype=None, device=None):
"""Move/convert to a common dtype or device.
Parameters
----------
*args : tensor_like
Input tensors or tensor-like objects
dtype : str or torch.dtype, optional
Target data type
device : str or torch.device, optional
... | b877532b71c70fd5c1485b9eeb2153682e2c75ab | 605,010 |
def check_fname_format_for_tag(fname_format: str, tag: str, fname_split: str = '_') -> bool:
"""
Checks if given tag is in a given fname_format string.
Parameters
----------
fname_format: str
The format of a fname with parameter names separated
by the deliminator specified by fname_... | a8afbae120e330a72012d3799205d235eb9516d5 | 605,013 |
def time_to_float(datetimeobject, totalturn=24, minimum=0.0, maximum=1.0):
"""
Function that returns a float between minimum
and maximum for a moment within totalturn hours (default: 24)
00:00 (Midnight) returns a value of 0, 12:00 (Midday) a value of 0.5
"""
micro = datetimeobject.microsecond /... | fd455af50baea9dee56cb9feb0c4e51cf1b59355 | 605,016 |
def calculate_shrinked_size(width, height, max_length):
"""Calculate shrinked size in proportion
The larger of width and height should be equal to max_length.
For exanple, width=500px, height=400px
width : height = max_length : new_height
i.e. new_height = max_length * height / width
if you s... | 0a3844a5381ff6b3f5dd09f6555303b34ac85041 | 605,024 |
def get_trans_prob(df, date, label, label_plus_one):
"""get probability of transition from one label to another,
given a dataframe where rows are transitions
Parameters
----------
df : pandas.Dataframe
returned by the make_df_trans_probs function
date : datetime.date
date to use... | a11153d7fe9e466bb0da4af381c4654a3b92574c | 605,026 |
import json
def load_jsonl(input_path) -> list:
"""
Read list of objects from a JSON lines file.
"""
data = []
with open(input_path, 'r', encoding='utf-8') as f:
for line in f:
data.append(json.loads(line.rstrip('\n|\r')))
return data | d276f22c801ee247844545fbe510d7a99fb96cf0 | 605,027 |
from typing import List
def string_to_int_list(value:str) -> List[int]:
"""
Returns a int list of a comma separate string of numbers.
Args:
value (str): a string that is a comma separate list of integers.
Returns:
List[int]: a list of int values
"""
result = [int(a) for a in ... | 6ccde0f771094f7eb3b38a39ab60c9bfe9abbf8e | 605,028 |
def _datastore_match(fs, fields):
"""
return True if existing datastore column fields include fields
defined in fs.
"""
# XXX: does not check types or extra columns at this time
existing = set(c['id'] for c in fields)
return all(f['datastore_id'] in existing for f in fs) | d628f6d3a06c98d415252602a948067cdb4ae202 | 605,030 |
def is_in_container(device, container="undefined_container"):
"""
Check if device is attached to given container.
Parameters
----------
device : dict
Device information from cv_facts
container : str, optional
Container name to check if device is attached to, by default 'undefine... | 73e6f5c543fcd4fae25d0b535ef07ed647faebb9 | 605,031 |
def split_mime_type(mime_type):
"""
>>> split_mime_type('text/xml; charset=utf-8')
('text', 'xml', 'charset=utf-8')
"""
options = None
mime_class = None
if '/' in mime_type:
mime_class, mime_type = mime_type.split('/', 1)
if ';' in mime_type:
mime_type, options = [part.st... | 73a7f502f9bc5af5a374c09ed2557f328fdc6ecb | 605,033 |
def num_length(num):
"""
Returns the length in digits of num
:param num: Num
:return: Length in digits
"""
return len(str(num)) | d05b254d8cc15175f7fde4b3e7f60e6a4356d2f2 | 605,037 |
def linear_approximation_real(x, x1, y1, x2, y2):
"""Linear approximation for float arguments"""
return (y1 - y2) / (x1 - x2) * x + (y2 * x1 - x2 * y1) / (x1 - x2) | fe2c514a6504b2777f6139cc11c573ae518ae302 | 605,040 |
def format_segment(seg):
"""
Formats a segment assuming it's an instance of class segment with elements
audiofile, channel, speaker, start and stop times, label, and text
"""
return " ".join(seg.__dict__[_] for _ in ('audiofile', 'channel', 'speaker', 'start', 'stop', 'label', 'text')) | f0650cda22f4f5950ce5c6aa03ef1b9546675d1d | 605,043 |
def dot_esc(str):
"""Escape str for use in DOT"""
return str.replace('"', '\\"') | ad82f29d9f02523b344f8ed81e73e372913bba0d | 605,047 |
def currency_display(value, currency='AUD', show_complete=False, include_sign=True):
"""
Create a human readable string to display a currency from some number of smallest units (e.g. cents).
:param value: value of currency in smallest units (cents)
:param currency: e.g. 'AUD'
:param show_complete... | e4be557adab06a6ab10c9270bacc4bebdc56251b | 605,051 |
from datetime import datetime
def _get_datetime(date):
"""String to date time conversion"""
return datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.000%z') | 36b12efec86cf48a11f6fdcdd09812a8d9e51624 | 605,055 |
def init_lambda_segment(G, lambda_function_doc):
"""Returns the Initialization subsegment id of a lambda function or None if warm start."""
lambda_subsegments = G.successors(lambda_function_doc['id'])
init_subsegments = (s for s in lambda_subsegments if G.nodes[s]['doc']['name'] == 'Initialization') # noqa... | 76bae6d4a6174b3890c4e84a376d631240da3910 | 605,056 |
def first(collection):
"""Start iterating over collection, and return the first element
"""
return next(iter(collection)) | 0faf56bb21a0692dc2cf5e5842facf3df2a55f81 | 605,057 |
import torch
def gaussian_KL_loss(mus, logvars, eps=1e-8):
"""Calculates KL distance of mus and logvars from unit normal.
Args:
mus: Tensor of means predicted by the encoder.
logvars: Tensor of log vars predicted by the encoder.
Returns:
KL loss between mus and logvars and the no... | a3d3d0bc0e7d2382b2870dab9aa0b759cda900de | 605,058 |
import requests
def geturl(url):
"""Get the content of a web page"""
r = requests.get(url)
return r.content | 8b3702860331d43253f915d9b68843d79dad95cd | 605,069 |
import inspect
def log(*args, **kwargs):
"""
Simply does this:
print(" " * depth, "|->", *args)
"""
return None
depth = len(inspect.stack()) + kwargs.pop("increase_depth", 0)
print(" " * depth, "|->", *args, **kwargs) | acfd665e59520e24b2dd9bf127cd14cc4a37de7f | 605,070 |
def render_tags(project):
"""
Render project's tags.
"""
data = {'tags': []}
if not project.tags:
return data
data['tags'] = project.tags.split(',')
return data | 7096e1545a7ac2d60fa7e031764a8bb0d31da17f | 605,077 |
def validate_reposlug(reposlug):
""" Validates reposlug. """
parts = reposlug.split('/')
if len(parts) != 2:
raise Exception(f'Reposlug {reposlug} is not correct!')
return reposlug | 288e52b7a4e4a66a9a2880c2822a4acda6a8eb04 | 605,078 |
def _to_image(data, width):
"""Convert data to an image.
Parameters
----------
data : array_like
Values of the pixels
width : int
Width of the image in pixels
Returns
-------
ndarray
Data reshaped into an ndarray with width `width`
"""
return data.reshap... | 7359a848cc82bbc6ce43bca3625b4b22a0e8342f | 605,081 |
def rec_pts_wdefault(rec=0, yds=0, tds=0):
"""
this function takes number of recieving: yards, receptions and touchdowns
and returns fantasy points scored (ppr scoring)
"""
return yds*0.1 + rec*1 + tds*6 | 8408d21849180f9148c3a245e661839633353827 | 605,084 |
def detect_file_format(data):
""" Determine format of a file
Parameters
----------
data : string
string containing file data.
Returns
-------
format : string
File format. 'excellon' or 'rs274x' or 'unknown'
"""
lines = data.split('\n')
for line in lines:
... | 040a76e57493db25d3d55695cb8ec015e048936a | 605,087 |
def stripTag(chunk):
"""Strips the tag and returns the rest of the chunk. Only useful in password-protected uploads.
Arguments:
chunk {bytes} -- Everything inside the message field of an IOTA tx, except for the signature.
Returns:
[bytes] -- Chunk without the tag.
"""
#tag = chunk[-16:]
chunkAndNonce = c... | 3b56916a798b261b282ef35c1c5613f9404da327 | 605,088 |
def t(x):
"""Transpose a tensor, i.e. "b i j -> b j i"."""
return x.transpose(1, -1) | b9d235b072597e102e320f74f865f686ff0130c6 | 605,094 |
def sorted_smartly(to_sort):
"""
Sorts the given list of strings alphabetically, but with
extra smarts to handle simple numbers. It effectly sorts them
as if they had been 0 padded so all numbers were the same
length; this makes them sort numerically.
"""
def split_digits(text):
"""
... | 666ad2bf8750087b1ec878e5c2d26eb0f12350cb | 605,096 |
import itertools
def group_on_delimiter(iterable, delimiter):
"""Group elements separated by delimiter into chunks.
group(['a', 'b', '', 'c', 'd', '', 'e'], '') => [['a', 'b'], ['c', 'd'], ['e']]
"""
return [list(g) for is_delimiter, g in itertools.groupby(iterable, lambda el: el == delimiter) if not... | 1d4c89b33c8e6ff7b682acddbd05218a44323de1 | 605,099 |
def grayTo2D(np_image):
"""
Reshaping np_image grayscale image to 2 dimension
e.g np_image with shape(x,y,1) will be reshaping to (x,y)
"""
return np_image.reshape((np_image.shape[0], np_image.shape[1])) | 436d0f4515f2728548af4134d721d7c51b840abb | 605,101 |
from typing import SupportsInt
def positive_int(value: SupportsInt) -> int:
"""
Check that an integer value is positive.
Args:
value: A value that can be cast to an integer.
Returns:
'value' as an integer, if it is positive.
Raises:
ValueError: If 'value' does not cast... | b68b1d8e347a1bd6de1c3e638a7905536803760f | 605,105 |
def can_slice(input_shape, output_shape):
"""Check if the input_shape can be sliced down to match the output_shape."""
if len(input_shape) != len(output_shape):
print("Slice dimensions differ:", input_shape, output_shape)
return False
for in_size, out_size in zip(input_shape, output_shape):... | 0c775f1ba1bff78047708bdd94c88d16096d2023 | 605,115 |
def convert_dt_timezone(dt, tz):
"""Convert datetime timezone."""
return dt.astimezone(tz=tz) | 5c3411fc94f52482617a40c49cd92642e730ad0d | 605,116 |
def systemCallComms(systemCall):
"""
Return the system output and errors of a subprocess.
Parameters
----------
systemCall : subprocess
The subprocess from which the output and errors are
extracted from.
Returns
-------
subprocessOutput : tuple (output, ... | 60eb94a7a293d4c9d408dab5a3bc7595790ec589 | 605,118 |
import torch
def convert_to_torch_tensor(data_list, use_cuda):
"""Convert lists into (cuda) Tensors.
:param data_list: 2-level lists
:param use_cuda: bool, whether to use GPU or not
:return data_list: PyTorch Tensor of shape [batch_size, max_seq_len]
"""
data_list = torch.Tensor(data_list).lo... | 1035336cd885de0dcb3ee6de730f243e5ad3ff0a | 605,122 |
def set_project_args(args, name=None):
"""Return project arguments dict
"""
if name is None:
name = args.name
project_args = {
"name": name,
"description": args.description_,
"category": args.category,
"tags": args.tag
}
return project_args | 111bd27eca59205f5f3183ac61febb914f57fb83 | 605,123 |
def convert_citation_text_lines_to_info(text):
"""Convert lines of format [N] author name place other year' to Info object
If it is an invalid format, it should return "Incomplete".
Default: Recognizes 3 patterns:
- Citation: [N] > varname
- Site: [N] SiteName http://
- Work: [N] author n... | f89864f656de80fc910b4a27d42aa91194faf3eb | 605,124 |
def getObjectCounts(meshes):
"""
Count the total number of vertex groups and shapes required for all
specified meshes.
"""
nVertexGroups = 0
for mesh in meshes:
if mesh.vertexWeights is None:
continue
for weights in mesh.vertexWeights.data:
if weights:
... | d4e50868044326cd8af583165dc7d3274a897187 | 605,125 |
from typing import Callable
from typing import Any
from typing import List
def single_to_multiple(processor: Callable[[Any], List[Any]])->Callable[[List[Any]], List[Any]]:
"""
Creates a processor that accepts a list of elements.
Converts a processor that handles one element and returns a list of elements... | 8b9f2e4f62619fa5e06f0c85adf906b67fef39e8 | 605,127 |
def convert_from_timedelta(timedelta_val):
"""
given a *timedelta_val* (datetime.timedelta), return a string representing the
inverse of convert_to_timedelta, eg. "5m".
"""
if timedelta_val.days:
return "{days}d".format(days=timedelta_val.days)
if timedelta_val.seconds:
return "{... | 19e8f2f5c12ed016599a2c6e35d10cae49c203a5 | 605,128 |
def _cmp_perm_lists(first, second):
"""
Compare two lists of permutations as sets.
This is used for testing purposes. Since the array form of a
permutation is currently a list, Permutation is not hashable
and cannot be put into a set.
Examples
========
>>> from sympy.combinatorics.per... | cbaa495853f1b4c9dbe0732d1da5cc005e69a359 | 605,130 |
def rotated_binary_search(sorted_collection: list[int], item: int, low: int, high: int) -> int:
"""
:param sorted_collection: the rotated list we would like to find the item within
:param item: the item to be found within the sorted_collection
:param low: for the binary search, the lowest index on the c... | 229a1da0ae096cdd5ad550a2dd1fbf08fdf202d5 | 605,134 |
async def body(message):
"""Extract body from message."""
return b"".join([b async for b in message.body]) | ac929c8cebe8c1799acfe64317a1c92d35d55c0f | 605,137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.