content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def milesToKilometers(miles):
"""assumes miles in a number
returns a float, the amount of kilometers equivalent to miles
"""
return 1.609344*miles | 52e16b88c8f0409ff8e11b5aab2307ae4fef020d | 630,916 |
import collections
def tail(n, seq):
""" The last n elements of a sequence
>>> tail(2, [10, 20, 30, 40, 50])
[40, 50]
See Also:
drop
take
"""
try:
return seq[-n:]
except (TypeError, KeyError):
return tuple(collections.deque(seq, n)) | 4cf7fa4301f1989ea16a9d653d083fd4edb6bc76 | 630,917 |
def parse_out_file(path):
"""
Parses an out file, which is based on ``ini`` files. They have pretty
basic syntax. The difference from what configparser is that indentation
is preserved in multiline values. We don't support comments and a number
of other features, but who needs 'em.
Args:
... | adafb4bfb77275a355a4148db2d9ba4593eebc95 | 630,918 |
from pathlib import Path
def html():
"""
Returns HTML of an event detail page.
The data in this file should match what's in the tests below.
"""
this_filename = globals()["__file__"]
path = Path(this_filename).parents[0] / Path("test_data/event.html")
return path.read_text() | 8df7797f7c7ebb0e7e05be2b509631703ff6d03a | 630,920 |
def calculate_areas(geometries, unity='km2'):
"""Calculate the area for a list of ogr geometries"""
# Part 1
conversion_factor = {
'sqmi': 2589988.11,
'km2': 1000000,
'm': 1}
# Part 2
if unity not in conversion_factor:
raise ValueError("This unity is not defined: {}".format(unity)... | 3a4ca22340cda3c7d6500024a622abc357ae121b | 630,922 |
def compare_time(left, right):
"""compares two time string"""
if left is None:
return False
if right is None:
return True
return left < right | ca35fbac628c4c56a5581f1c28fd5d915941ec63 | 630,923 |
import re
def delete_whitespace(text: str) -> str:
"""
Removes whitespaces from text.
"""
return re.sub(r'\s+', '', text).strip() | a4aacdc74ba16fb5072c6fa1a4e2a924fedcdd1b | 630,925 |
def notas(*nota, sit=False):
"""
-> Funcao para analisar notas e situacoes de varios alunos.
:param nota: uma ou mais notas dos alunos (aceita varias)
:param sit: valor opcional, indicando se deve ou nao adicionar a situcao
:return: dicionario com varias informacoes sobre a situacao da turma
"""... | fd0bebda43b3f349ae12e06f25d9486e15418df5 | 630,926 |
def dictzip(keys, values):
"""
>>> dictzip(["x", "y", "z"], [1, 2,3])
{'y': 2, 'x': 1, 'z': 3}
"""
return dict(list(zip(keys, values))) | f10fc65bf7d8af8c471cce5523475ef2e4942f23 | 630,927 |
def score_to_quality(qval, offset: int=32, maxval: int=126):
"""Convert a score to quality value."""
cval = int(qval) + offset
if cval > maxval:
cval = maxval
return chr(cval) | c4684d15d5cea820cccc91e26b814647896279fb | 630,928 |
from typing import Iterable
def can_sum_rec(target_sum: int, numbers: Iterable[int]) -> bool:
"""Find if it's possible to generate 'target_sum' using elements of numbers.
Args:
target_sum: The integer to be sumed up to.
numbers : A collection of numbers.
Returns:
True if it is ... | f0f28947dca3d4f269b291a84def641282797bcd | 630,929 |
def get_min_max_t(track):
"""Get track stat and end times"""
m = min(t for t, _, _ in track)
M = max(t for t, _, _ in track)
return (m, M) | c5e1407f187327be8ee3e192809a5fca72cc636a | 630,930 |
import sys
def max_profit(prices: list) -> int:
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
min_price = sys.maxsize
for price in prices:
min_price = min(price, min_price)
profit = max(profit, price - min_price)
return profit | a2996df120f610f764c4623feb533afab06560ef | 630,931 |
import string
import json
def getPELEControlFileDict(templetizedControlFile):
"""
Parse a PELE control file into a python dictionary
"""
with open(templetizedControlFile) as fc:
peleControlFile = fc.read()
templateNames = {ele[1]: '"$%s"' % ele[1] for ele in string.Template.pattern.f... | 235b65dfa215a32b7ee2124cd0710845a361e61e | 630,932 |
def record_variant_id(record):
"""Get variant ID from pyvcf.model._Record"""
if record.ID:
return record.ID
else:
return record.CHROM + ':' + str(record.POS) | 105b5f27095d0cad5e89e54788ab48bb296690f8 | 630,933 |
from typing import List
def chargement_fichier(nom_fichier : str) -> List[str]:
"""Précondition : nom_fichier est le nom d'un fichier texte existant
Retourne le contenu du fichier texte identifié par nom_fichier
sous la forme d'une liste de lignes de texte.
"""
# Lignes contenues dans le fichier
... | ba9589d66801482083433b5403b72d9f13d91400 | 630,934 |
def parse(resp):
"""
Parse response into status line, headers and body.
"""
pos = resp.find(b'\r\n\r\n')
assert pos != -1, 'response is %s' % repr(resp)
head = resp[:pos]
body = resp[pos+4:]
status,head = head.split(b'\r\n', 1)
hdrs = {}
for line in head.split(b'\r\n'):
k... | 483da7c03b3ceb2dcb45f6beb68040e61247794b | 630,935 |
def flatten_board(board):
""" Turns the 3x3 board into a 1x9 board """
return [cell for row in board for cell in row] | 3729070643f0f5409f977181d2d38dfb358c7a15 | 630,936 |
def format_hash(hash_alg, hash_):
"""
format the hash including version and algorithm
"""
return '-'.join(('v0', hash_alg, hash_)) | 870a87d695b9d1bd5c625aa1d82c3a702474b529 | 630,937 |
import typing
def get_path_from_list(to_parse: typing.List[str], path_prefix: str) -> str:
"""Parse a path from a list of path parts."""
ret = path_prefix
for i in to_parse:
ret += f"/{i}"
return ret.lstrip("/").rstrip("/") | 90ccb309751d3bff6d816422b50e23bcf799927b | 630,938 |
import os
def remove_banned_users(search_keys: list) -> list:
"""Remove banned users from search keys."""
banned_users = os.environ.get('BAN_LIST')
if not banned_users:
return search_keys
else:
banned_users = banned_users.split(',') # type: ignore
for key in search_keys.copy():
... | 08dc413a727f4f8f4caad410848379bea7f3babb | 630,939 |
def _filter_labels(labels, start_datetime, end_datetime, verbose=True):
""" Select the labels whose date in the provided datetime range """
mask = (labels.Date >= start_datetime) & (labels.Date <= end_datetime)
if verbose:
print("Selecting {} out of {} labels".format(mask.sum(), len(labels)))
re... | f794855b779375361ab423bb57ff41ecd0074360 | 630,940 |
import random
def random_float(min=1.0, max=100.0, decimals=None):
"""Generate a random float between min and max.
`decimals` is the maximum amount of decimal places
the generated float should have.
"""
randomfloat = random.uniform(min, max)
if decimals is not None:
randomfloat = roun... | 38a6f76a223d3dec821dd1db9258eedcc7e4984a | 630,941 |
def ip_to_int(ip):
"""
>>> ip_to_int(None)
0
>>> ip_to_int('0.0.0.0')
0
>>> ip_to_int('1.2.3.4')
16909060
"""
if ip is None:
return 0
result = 0
for part in ip.split('.'):
result = (result << 8) + int(part)
return result | 030fad68684cde8a132df6f5e5891f11a6bf6eb5 | 630,942 |
def get_child_queryset_u(check_queryset, obj, has_parent=True):
"""
获取所有子集
查的范围checkQueryset
父obj
是否包含父默认True
"""
cls = type(obj)
queryset = cls.objects.none()
father_queryset = cls.objects.filter(pk=obj.id, is_deleted=False)
if has_parent:
queryset = queryset | father_qu... | 8b3435b64b444b02964995e171942422b9159f56 | 630,943 |
import html
def build_spans(s,blocks):
"""s:string, blocks are pairs of (idx,len) of perfect matches"""
if not blocks:
return [], 0, 0
#allright, this is pretty dumb alg!
matched_indices=[0]*len(s)
for i,l in blocks:
for idx in range(i,i+l):
matched_indices[idx]=max(mat... | 07f205a67e83ef4875d4e88d75d354e95a666ba2 | 630,944 |
import os
import json
def get_org_details(*, cci, org_name, project_path):
"""Obtain details needed to create a scratch org.
Returns scratch_org_config
(from the project's cumulusci.yml)
and scratch_org_definition
(the sfdx *.org file with JSON specifying what kind of org to create)
"""
s... | 4c64a6773b68bb90034f4333cb1b633aff245178 | 630,945 |
def task_mypy():
"""Run mypy check."""
return {
'actions': ['mypy pyppeteer'],
} | 8a5f354fee8020ed1c9a5f356211580e4d5f4a38 | 630,946 |
def is_valid(value, mode):
"""Return True if value is in range of map size.
Mode: WIDTH or HEIGHT, depending what value is checked."""
return False if value < 0 or value > mode-1 else True | 28a027bc96c4ead1b79dec1a895c04a902f31869 | 630,947 |
def get_docs_changed(diffs: str) -> int:
"""Processes diffs from a Pull Request to extract number of doc-type files changed in the PR
Parameters
----------
diffs : str
A string denoting the diffs in the PR
Returns
-------
int
number of files of documentation type that have ... | 8b69cefa16ad216fbf674c9ec7a59b217d109757 | 630,948 |
def gitlab_cli(script_runner, gitlab_config):
"""Wrapper fixture to help make test cases less verbose."""
def _gitlab_cli(subcommands):
"""
Return a script_runner.run method that takes a default gitlab
command, and subcommands passed as arguments inside test cases.
"""
c... | a4b06886c3693f2dd8f8661bf65ca6390d1b4cf3 | 630,950 |
def check_fit(plaintext: list, ciphertext: list) -> int:
"""Check if ciphertext can fit in plaintext's whitespace.
Sum number of blanks in **plaintext** and compare to number of characters
in **ciphertext** to see if it can fit.
Args:
plaintext (list): Paragraphs of a fake message in a list of... | 5910f4c35e4fb270481a0d94914c5f6faac1732b | 630,951 |
import re
def to_lowercase_alphanum(text):
"""Remove non-alphanumeric characters and convert text to lowercase.
"""
return re.sub(r'[^a-z0-9]', '', text.lower()) | e508e708b964775660a9d188f2ff91e02ea42eaa | 630,952 |
def process_standard_commands(command, game):
"""Process commands which are common to all rooms.
This includes things like following directions, checking inventory, exiting
the game, etc.
Returns true if the command is recognized and processed. Otherwise, returns
false.
"""
if command == ... | fca2dd94275dcfc4de0859d3a0d476d3268b39d5 | 630,953 |
import math
def obliquity_of_ecliptic(t: float) -> float:
"""
Calculate the obliquity of earth's ecliptic around the sun in decimal degrees.
Parameters:
t (float): The time in Julian Centuries (36525 days) since J2000.0
Returns:
float: The obliquity of earth's ecliptic at the given t... | 9ef9cbc9289ceaa19c113c9e98a771ae8f58b1ff | 630,955 |
def __span_overlap__(span1, span2):
"""
"""
if (span1[0] <= span2[1]) & (span2[0] <= span1[1]):
return True
else:
return False | b1407d67a9de9034685e5f6470db8237501dbe8c | 630,956 |
def ycb_mesh_files():
"""Manual enumeration of mesh files, to avoid needing to write extra Bazel
logic.
Recipe to reproduce:
$ cd models
$ find ycb/meshes -type f | \
python3 -c 'import sys; print(repr(sys.stdin.read().split()))'
"""
return [
"ycb/meshes/003_crac... | 6a62490103b42ca21202a2d11c0a5fdc242e36dc | 630,957 |
def fractional_tune(tune):
""" Returns the fractional tune."""
return tune - int(tune) | 4c7b5e5539cd9f1ab8afa62cc20afec182f375b4 | 630,958 |
def pack4bitbuf(
unpackedbuf: list[int]
) -> list[int]:
"""Packs an unpacked 4-bit buffer
into a list
Args:
buf: unsigned byte array
or list
Returns:
list
"""
retval = []
j = len(unpackedbuf) - 1
i = 0
while i < j:
re... | d833ec4bddfe1f3baf49a913e7e1fa3ddbb86e65 | 630,959 |
import torch
def get_available_memory():
"""
Get available GPU memory in GB.
Returns
-------
int
Available GPU memory in GB
"""
gpu_memory = torch.cuda.get_device_properties(0).total_memory
memory_in_use = torch.cuda.memory_allocated(0)
available_memory = gpu_memory - memo... | 2d9a839bcacb60ad02e7356c1ac518060b923585 | 630,960 |
def euclid(a, b):
"""
Extended Euclidean Algorithm; finds (x,y,z) such that ax + by = gcd(a,b) = z
Written with help from
http://en.literateprograms.org/Extended_Euclidean_algorithm_%28Python%29
Input:
(a,b) two integers
Output:
(x, y, z) integers such that ax + by = gcd(a,b) ... | fea2d6c15d3cd170d1db63675cd4b2e01d68a1c7 | 630,961 |
from typing import Iterator
from typing import Dict
from typing import Tuple
from typing import Optional
import logging
def _parse_as_to_org_map_remainder(
f: Iterator[str], org_id_to_country_map: Dict[str, Tuple[str, str]]
) -> Dict[int, Tuple[str, Optional[str], Optional[str]]]:
# pyformat: disable
"""Retur... | 5f3028b97ff97316a5359203890387d6a4edaf34 | 630,962 |
from typing import Dict
from typing import Any
from typing import List
def filter_comparison_report(comparison_report: Dict[str, Any], impact: str = "improvement") -> List[Dict[str, Any]]:
"""
Filters out the comparison report, to create a view such as this, but without the headers:
Domain Report... | 6445127ce9ec0b1f611977afcc167a6c7e69b5d5 | 630,963 |
def is_special(pat):
"""Whether the given pattern string contains match constructs."""
return "*" in pat or "?" in pat or "[" in pat | 1d8b82c925dfbae343382afd91664133120087f8 | 630,964 |
def ReadIDList(infile, delim=None):#{{{
"""
Read a file containing a list of sequence IDs.
"""
try:
fpin = open(infile,"r")
li = fpin.read().split(delim)
fpin.close()
if delim != None:
li = [x.strip() for x in li]
return li
except IOError:
... | 99cf4d55383d07faa08e72fbaa8b0eeca5b49f10 | 630,965 |
import re
def find_ipv4_with_subnet(string):
"""
Find and return IPv4 address with subnet inside a string.
This function will only return an ipv4 address with a subnet
:param string: (str) The string to search for ipv6 with subnet(i.e. "Successfully added Subnet 10.34.33.20/30")
:return: (str) ... | adc6c73258b7ddb365151f9b729441be8d82a680 | 630,966 |
def get_gps_references():
"""Get gps references
Returns:
tuple: containing easting northing and elevation references
"""
cloudEastingOffset = 344178.0
cloudNorthingOffset = 3127579.0
cloudElevationOffset = 2442.0
robotEastingOffset = 344043.8
robotNorthingOffset = 3127408.3
... | 9f0a163653b8c82fdfbef10cf7c4b257fe81edaa | 630,968 |
def generate_args(code: str) -> dict:
"""
Generate the arguments for the model
Args:
code (str): The code to execute
Returns:
dict: The arguments
"""
exec(code,)
ret = locals()
ret.pop("code")
return ret | d4e753bd4a866675dff19ae14a7f86545d2562d4 | 630,969 |
import torch
def rank(X, tol=.01):
"""Evaluate approximate rank of X."""
_, svs, _ = torch.svd(X)
return (svs > tol*svs.max()).sum(), svs | a68c4557bc48af7d746d6d93910940dce55d3631 | 630,970 |
from typing import List
def create_table_dropdown(order_list: List[dict], order_name: str) -> dict:
""" Create the dropdown-options in the context of assembling orders.
Syntax of the returned dictionary is based on dash.
"""
dropdown_options = {
'component': {
'options': []
... | c7885fc28964df79289dacbe96592d2bb9f1bbc1 | 630,971 |
def get_values_lengthes(dictionary):
"""returns the sum of the lengthes of values of a dictionary"""
return sum(map(lambda value: len(value), dictionary.values())) | 63718868ad50dfe38639b1bb21cec93d7d220c40 | 630,972 |
def cleanup_model(model, form):
"""Remove values for fields that are not visible."""
new_model = {}
fields = form["fields"]
for key, value in model.items():
if key not in fields:
continue
if key.startswith("html-"):
continue
field = fields[key]
if ... | 92f8dc7e28650d381edd68b8399829fbc07f7ab7 | 630,973 |
import io
def _is_seed(filename):
"""
Determine if the file is (dataless) SEED file.
No comprehensive check - it only checks the initial record sequence
number and the very first blockette.
:type filename: str
:param filename: Path/filename of a local file to be checked.
:rtype: bool
... | 6002bf4edb141c6173774643a42de0904f695f3c | 630,974 |
import torch
def _interp_array(start: torch.Tensor, end: torch.Tensor,
num_steps: int) -> torch.Tensor:
"""Linearly interpolate 2D tensors, returns 3D tensors.
Args:
start: 2D tensor for start point of interpolation of shape [x,y].
end: 2D tensor as end point of interpolation of ... | 232ca65e13d4896c7c0e580bd48f8629b4622573 | 630,975 |
import os
import torch
def load_checkpoint(file_path: str, device=None):
"""Loads torch model from checkpoint file.
Args:
file_path (str): Path to checkpoint directory or filename
"""
if not os.path.exists(file_path):
raise Exception("ckpt file doesn't exist")
ckpt = torch.load(fil... | d1ca3f7ec77952a3f57d91b4bdfea325cf8f71a9 | 630,977 |
from typing import OrderedDict
def _to_str(dumped_val, encoding='utf-8', ordered=True):
"""
Convert bytes in a dump value to str, allowing json encode
"""
_dict = OrderedDict if ordered else dict
if isinstance(dumped_val, dict):
return OrderedDict((k, _to_str(v, encoding)) for k,v in dumpe... | ed45e4032597b933d019be7f404348a44a012c22 | 630,978 |
import re
def str_to_dollars(doc: dict, dollar_fields: list):
"""
Convert strings to dollar amounts.
"""
for field in dollar_fields:
try:
if field in doc and doc[field]:
doc[field] = re.sub(r'[^0-9.\-]', '', doc[field])
doc[field] = float(doc[field])... | 7b7906acf2e9525614bedcb03a2e9b37e5c6d948 | 630,980 |
def fmt(f):
""" Take a number, and return a string with 3 digits before the decimal and at least 2 after.
It really seems like there must be a way to do this with printf.
"""
rstr = "%03d" % f + str(f%1)[1:]
try:
dot_pos = rstr.index('.')
except ValueError:
# if there is... | ebb054958130d1ba77514c0805299a40b5f129df | 630,981 |
def compare_dicts(first, second, fine_if_wrong=None):
"""Compare two dictionaries, based on their key, value pairs."""
total_keys = len(set(first.keys()) | set(second.keys()))
if fine_if_wrong is None: fine_if_wrong = set()
resemblance = 0
differences = dict()
for key, value in first.items():
... | 67b6c48466f71972b697cc3ad7f49094a8fdd098 | 630,983 |
from typing import List
import os
def find_files_by_suffix(
root_dir: str, suffix: str, prefix: str = "", depth: int = 0
) -> List[os.DirEntry]:
"""
Returns list of files matching suffix, optionally searching in subdirs.
Args:
root_dir: Path to directory where we start searching
suffi... | 53b17d7de65da852911fec51f99118148cbcc667 | 630,985 |
def node_is_shortcuttable(node_i, path, netgraph, rev_netgraph):
"""
Given a index node_i in path and path (list of node numbers) containing node
and the two graph (dict of dicts) structures
where rev_netgraph is just graph with all links reversed, return
True if the node has links only to and from ... | eaabee5cadf80accca728dd00916eacad28b4b44 | 630,986 |
def hide_string(s, char_replace='*'):
"""Returns a string of same length but with '*'"""
return char_replace * len(s) | f25853225d451cf6c8495b1845c06cb9ccc6bad1 | 630,987 |
def infinityNorm(A):
"""Calcula la norma infinita"""
summation = 0
for j in range(len(A)):
summation += abs(A[0][j])
for i in range(1, len(A)):
temp = 0
for j in range(len(A[i])):
temp += abs(A[i][j])
summation = temp if (temp > summation) else summation
return summation | 8b8858c8c8a891f52d14e21852fbf1bdf0453153 | 630,988 |
def GetRegionFromZone(gce_zone):
"""Parses and returns the region string from the gce_zone string."""
zone_components = gce_zone.split('-')
# The region is the first two components of the zone.
return '-'.join(zone_components[:2]) | f877337e010af381ad921eb258b0098ab2941988 | 630,989 |
def key(resource):
"""
Returns key name based on resource
"""
return {
'token': 'address',
'pool': 'address',
'address': 'address',
'allowance': 'hash',
'balance': 'hash',
'claim': 'hash',
'wallet': 'hash',
'transaction': 'hash',
't... | 8cd60e306d74ad6f12eaba07478a4bed86f1bc94 | 630,990 |
import os
def get_project_directory():
""" Returns project directory.
:return: str. path back to top level directory
"""
project_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')
return project_directory | bb14f281bf63575596b24b11bc9fea725bc9999a | 630,991 |
def is_first_read(flag):
"""
Interpret bitwise flag from SAM field.
Returns True or False indicating whether the read is the first read in a pair.
"""
IS_FIRST_SEGMENT = 0x40
return (int(flag) & IS_FIRST_SEGMENT) != 0 | 4620951597ef2dc481638ecb86b3500ff6475126 | 630,992 |
def comment_code(code_str, line_comment=None, block_comment=None):
"""Adds comments to a snippet of code.
If line_comment is a given string then each line is prepended with the
line_comment string.
If block_comment is a tuple of two strings (begin, end) the code str is
surrounded by the strings.
... | 3868a3d2114b9d9f0e30e8dac6120f597b8b2676 | 630,993 |
def convert_string(*args, **kwargs):
"""
Handle converter type "string"
:param args:
:param kwargs:
:return: return schema dict
"""
schema = {
'type': 'string',
}
for prop in ['length', 'maxLength', 'minLength']:
if prop in kwargs:
schema[prop] = kwargs[p... | 383874ec8a2029b0ab4db060c39fc66efdee461a | 630,994 |
def from_image_url(url: str, width: int, height: int) -> str:
"""
Generates GIFT text for a URL.
Parameters
----------
url : str
Input URL.
width : int
Desired width of the image.
height : int
Desired height of the image.
Returns
-------
out: str
GIFT-ready text.
"""
# either both are set or non... | 5b3426b54161d98d98a25e04c6a46d8327691e77 | 630,995 |
import torch
from typing import Optional
def create_src_lengths_mask(batch_size: int, src_lengths: torch.Tensor, max_src_len: Optional[int] = None):
"""
Generate boolean mask to prevent attention beyond the end of source
Inputs:
batch_size : int
src_lengths : [batch_size] of sentence lengths
... | b26c42a5fdc0ec25c1320d4db668e457ada30af2 | 630,996 |
import functools
import random
import time
def rare_delay(delay: float, probability: float):
"""
Decorator to add a fixed random delay before executing the function
with a given probability.
:param delay: Delay in seconds.
:param probability: Probability of delaying the function execution.
:re... | cba0e1d43137bb06173d6a34d2e6c16851047141 | 630,997 |
import re
def _create_special_marks_sequences_regex(max_seq_length=4):
"""
Create a regex object which can detect sequences of '.'/'!'/'?'.
It's assumed the regex will be fed with the result of the tokenization process followed by a space,
i.e. it can detect sequences of the form '. . . ! ? ! '.
:... | 9272d479e2f49ac7d5e5f41d6412f80cec00b10a | 630,998 |
import functools
import sys
def exception(function):
"""
Wrapper function to catch exceptions in functions
Parameters
----------
function : function
A Python function
**Required**
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
try:
r... | 6a982412ce2fdce119f614b9790799ab81b96530 | 630,999 |
import random
def rand_index(word):
"""
Returns a random index in a given text.
"""
return random.randint(0, len(word)-1) | 1c33c88742a9ffb06b3515fb7950c96fc951cf65 | 631,000 |
def get_previous_timestep(timesteps, timestep):
"""Get the timestamp for the timestep previous to the input timestep"""
return timesteps[timesteps.ord(timestep) - 1] | 8e41bccf87ae0b6b68c70cfdc522aca3f61565bd | 631,002 |
import math
def latlon2tms(lat,lon,zoom):
"""
Converts lat/lon (in degrees) to tile x/y coordinates in the given zoomlevel.
Note that it doesn't give integers! If you need integers, truncate
the result yourself.
"""
n = 2**zoom
lat_rad = math.radians(lat)
xtile = (lon+ 180.0) / 360.0 *... | f4c238ad3af7635f6a812021cc38744a73a0a437 | 631,003 |
from typing import Dict
import json
def json_merger(path_to_json_one: str, path_to_json_two: str) -> Dict[str, str]:
"""
Exposes the logic to merge two json files by loading their contents from supplied paths.
:param path_to_json_one: Specifies the filepath of a .json file that is going to be merged.
... | 7860c9f76fc85277b89699f2980fae5ed5523b38 | 631,004 |
import os
def makeStrawName(path, sector, camera, ccd, col, row):
"""Constructh the straw name
Does no testing to ensure the input parameters are sane
Inputs
---------
path
(str) Location of file on disk/s3
sector, camera, ccd, col, row,
(int) Parameters of the straw file
... | c00ec39c41fd7c33a1becc257ec04b145e542a40 | 631,005 |
def map_values(function, dictionary):
"""Map ``function`` across the values of ``dictionary``.
:return: A dict with the same keys as ``dictionary``, where the value
of each key ``k`` is ``function(dictionary[k])``.
"""
return {k: function(dictionary[k]) for k in dictionary} | 569225e40969bb5962779344b68ea8963af8f576 | 631,006 |
import inspect
def get_func_args(func, args, kwargs):
""" 获得函数的所有参数信息,保存在 func_args 中
输入:
func: 函数体
args: 传入的位置参数列表
kwargs: 传入的命名参数列表
"""
# 获得当前函数的所有参数信息
full = inspect.getfullargspec(func) # 含缺省值定义
# FullArgSpec(args=[], varargs='args', varkw='kwargs', defaults=... | 7b3c6908897d21e3ae4d7bbcd9fd7f45cd671f5b | 631,007 |
import os
def get_path(args_master):
"""Prepare the paths for the master DB and output DB
"""
# Get the cwd; set as base path for the outer files
base_path = os.getcwd()
output_data_path = os.path.join(base_path)
master_db = args_master
# If master, creat... | 3713144968899d64d1de69cd89807833e749daf2 | 631,009 |
def _list_of_parts(model, only_objects = True):
"""Return a complete list of parts."""
pl = list(model.parts_forest.keys())
if not only_objects:
return pl
obj_list = []
for part in pl:
dir_place = part.rfind('/')
dir_free_part = part[dir_place + 1:]
if dir_free_part.... | d20f21789e5d2852ebc5e8d0c145a313cd17db9e | 631,010 |
def clean_cos(value):
"""
Limits the a value between the range C{[-1, 1]}
@type value: float
@param value: The input value
@rtype: float
@return: The limited value in the range C{[-1, 1]}
"""
return min(1, max(value, -1)) | a3328c90852e4ed788e6e60e7947b10215734240 | 631,011 |
def sliding_window(l, n):
"""
Creates a sliding window of given length over a list.
Examples
--------
>>> l = range(5)
>>> sliding_window(l, 2)
[[0, 1], [1, 2], [2, 3], [3, 4]]
"""
rngs = range(0, len(l) - n + 1)
return map(lambda rng: l[rng:rng + n], rngs) | 57f677ad14cad4660a03ad0f6b43d8f2b596ae05 | 631,012 |
def call_user_func(settings_module, func_name, *args, **kwargs):
"""Call a user-supplied settings function and clean it up afterwards.
settings_module may be None, or the function may not exist.
If the function exists, it is called with the specified *args and **kwargs,
and the result is returned.
... | b6ff587c8ed3571ac68b318a52af95bada7fa8ff | 631,013 |
import tqdm
def apply_groups(groups, client, func, *args, return_futures=False,
progress_bar=True, **kwargs):
""" Call `func` on each group in `groups`.
Additionally, `args` and `kwargs` are passed to the function call.
Parameters
----------
groups: pandas.DataFrameGroupBy
The re... | 5bca1f2eb0945fa72c517134b0ea4deaf61ecd23 | 631,014 |
def build_final_results(row):
"""
row = (customer_id, [{sku:, action}, {sku:, action}])
"""
skus_list = [e['sku'] for e in row[1]]
actions_list = [e['action'] for e in row[1]]
return {
'customer_id': row[0],
'skus_list': skus_list,
'actions_list': actions_list
} | d6b62f8744d8cfd409de0d4bb549940f4f5a3036 | 631,015 |
def refine_digits_set(digits):
"""美化连续数字的输出效果
>>> refine_digits_set([210, 207, 207, 208, 211, 212])
'207,208,210-212'
"""
arr = sorted(list(set(digits))) # 去重
n = len(arr)
res = ''
i = 0
while i < n:
j = i + 2
if j < n and arr[i] + 2 == arr[j]:
while j <... | 6775501305ec81821aea99afd32f99bf332f6e67 | 631,016 |
def explode_locations(k):
"""Expands the given key ``k``. ``k``s of the form ``'1--3'`` or
``'1,2,3'`` are both expanded into the list ``['1', '2', '3']``.
Can deal with any combination, e.g. ``'1--3,6,9--11,a'`` results in::
['1', '2', '3', '6', '9', '10', '11', 'a']
Always returns a list, e... | f0af9ed9792d48111887ea5bdba256b9d9d8805e | 631,017 |
def _psd_mp_helper(ooi_hyd_data_obj, win, L, overlap, avg_method, interpolate, scale):
"""
Helper function for compute_psd_welch_mp
"""
ooi_hyd_data_obj.compute_psd_welch(win, L, overlap, avg_method, interpolate, scale)
return ooi_hyd_data_obj.psd | f191de119fd359471c532be334746881a4c0efb4 | 631,019 |
def loadPedigree(pedigree_file):
"""
"""
if not pedigree_file: return {} #
pedigree = {}
for line in open(pedigree_file):
# 1006 1006-05 1006-01 1006-02 0 0
col = line.strip('\n').split()
if col[1] in pedigree:
raise ValueError('[ERROR] %s is already in "pedigre... | 1674cba1b26c67523d57f3f378984383094bc5a3 | 631,020 |
def max_common_divisor(x, y):
"""该函数返回两个数的最大公约数"""
hcf = 0
# 获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf | 98f441f9fdd94b4ef2e0d2640af874368f6ffad9 | 631,021 |
def train_native(use_l1=False, lambda_l1=5e-4):
""" Function to return train function instance
Args:
use_l1 (bool, optional): Enable L1. Defaults to False.
lambda_l1 (float, optional): L1 Value. Defaults to 5e-4.
"""
def internal(model, train_loader, optimizer, criteria, dropout, device... | edd3dc41df117ba397816d1b4b8837f85421a5f0 | 631,022 |
def mk_part_uri(uri, idx):
""" Appends fragment part to the uri recording index of the part
"""
return '{}#part={:d}'.format(uri, idx) | ca802c5e7dcbb5b2c0214f90b121b7dc827d4a29 | 631,024 |
import sys
import argparse
def parse_args(args=sys.argv):
"""Parse arguments."""
parser = argparse.ArgumentParser(
description="Create colored Eigen faces.",
prog='python3 {}'.format(sys.argv[0]))
args = args[1:]
parser.add_argument("-d", "--input-dir", help="path to images folder."
... | 9c5386fba836514f2f874241ffde2d8e846c405c | 631,025 |
def clean_data(data):
"""Clean data tuples returned from api"""
return list(map(lambda entry: [str(entry[0]), str(entry[1])], data)) | 8d130ab688184554dd057d13400be0d4aefbde80 | 631,026 |
import os
def _get_salt():
"""
Get random generated 16 bytes.
Returns:
bytes: random generated 16 bytes.
"""
return os.urandom(16) | ed3df720f035c37ef2913a7e1933414371e4a8a9 | 631,027 |
def check_consecutive(lst):
"""Check if a list has consecutive numbers.
Check if a list of names with enumeration include all the elements
in such a way that the enumeration contains all expected numbers.
:param lst: List of names that include an enumeration
:type lst: list
:return: Check if t... | 2f982b908ae466979af12a82ab323fdff1d18e66 | 631,028 |
def formatter(type):
"""Format floating point numbers in scientific notation
(integers use normal integer formatting)."""
if type == int:
return "%d"
elif type == float:
return "%.3e" | 072a60d9f2e1d8eb609eb3aa1fd5d11d31c64658 | 631,029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.