content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def tpms(messages):
"""TPMS decoder."""
d = messages[0].data
if len(d) == 0:
return None
else:
return dict(tire_fl_pressure=round((d[7] * 0.2) / 14.504, 1), # bar - Front Left
tire_fl_temperature=d[8] - 55, # C - Front Left
tire_fr_pressure=ro... | a6bcced9bea43a7d13aefb60292a4afd724ee721 | 683,858 |
from textwrap import dedent
import inspect
def get_func_code(f):
"""Get the code of function f without extra indents"""
return dedent(inspect.getsource(f)) | 95b0de92937adaa9a2e64a1855aa4e7298d7e259 | 683,859 |
def mmedian(lst):
"""
get the median value
"""
sortedLst = sorted(lst)
lstLen = len(lst)
if lstLen==0:
return 0.0
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0 | b0aab9d47d7f2ee12d442b84cdb6ae5aa00578dd | 683,860 |
def sampling(df, max_rows=3000, random_state=0):
"""Select first 'max_rows' rows for plotting purposes."""
if df is not None and df.shape[0] > max_rows:
return df.sample(max_rows, random_state=random_state)
return df | 3b769f9d14241e23ddd0bf232ecd780cb0a8ac5f | 683,861 |
import argparse
def read_cmd():
"""Function for reading command line options."""
desc = "Script for downloading Khan Academy content tree."
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-c','--content', dest='content_type', required = True, help='Which kind of content should we ... | 43c0bd45831c43b270ce5323ef1373baaf92c1fd | 683,862 |
import torch
import logging
def save_checkpoint(policy, name, *,
optimizer=None,
replaybuf=None):
"""Save model (and replay buffer) checkpoint
:param name: File base name
:param replaybuf: Save also replay buffer
"""
state = {
'policy': policy.state_... | b7e043ab2d21744fa18a3dad799217be6696ecfb | 683,863 |
def getFunctionCallSigs(function, joinClause=' -OR- '):
"""Explains what you can use when calling a function.
The join clause doesn't make as much sense for Python functions,
but is very useful for overloaded Java calls.
>>> getFunctionCallSigs(getFunctionCallSigs, joinClause=' <> ')
"(function, joinClause=' -O... | f464b2aac8d749ea15d3eeaed9f0cb131ea3ae04 | 683,864 |
def count_jobs(results):
"""
run through each of the lists in results, count all of the jobs which haven't
finished
"""
unfinished = 0
finished = 0
for sample in results:
for r in results[sample]:
if not r[2].ready():
unfinished += 1
else:
... | 36cf4a64b19f4ddb18ba04d7f464feed200d0ff3 | 683,865 |
def _default_host(host, default_host, default_port):
"""Build a default host string
"""
if not host:
host = default_host
if ':' not in host:
host = "{}:{}".format(host, default_port)
return host | 0b9a519669908ca30bd4ea51dfc33913381b13d6 | 683,866 |
def _format_spreadsheet_headers(token):
"""
Return formatted authorization headers for further
interactions with spreadsheet api.
"""
return {
"Authorization": f"Bearer {token}"
} | 5dc8cd880c598246b7c47ccbc0138daac03c3131 | 683,867 |
def correctName(val):
"""
:param val: integer value to be brought into correct format
:return: str of corrected name
"""
if abs(val) < 10:
step_name = "0000" + str(abs(val))
elif abs(val) < 100:
step_name = "000" + str(abs(val))
elif abs(val) < 1000:
step_name = "00" ... | 0112a38b0fb56f9e1d7f146b5b2c7c87d37ab53f | 683,868 |
def test_int_flgs(lst):
"""
Test if all elements in list are 0.
"""
for i in lst:
if i:
return(1)
return(0) | 39ec058c386cddc716c3ebdd9481c94c4d16dc0a | 683,869 |
def handle_diag_constraints(bqm, subsets, diag_constraints):
"""Update bqm with diagonal (and anti-diagonal) constraints.
Duplicates are penalized.
"""
for constraint in diag_constraints:
for i in range(len(subsets)):
if constraint in subsets[i]:
for j in range(i):
... | f3d1d9c820c3e27d4ce1b3f87f9c31102d677166 | 683,870 |
import re
def getFilename(name):
"""Get a filename from given name without dangerous or incompatible
characters."""
# first replace all illegal chars
name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name)
# then remove double dots and underscores
while ".." in name:
name = name.replace('..', '... | 6444ed2a215171d99e281172fcd302923b854603 | 683,871 |
from pathlib import Path
def _get_old_file(new_file: Path) -> Path:
"""Return the same file without the .new suffix"""
assert new_file.name.endswith('.new') # noqa
return new_file.with_name(new_file.stem) | ac0738099d088aa1af184b8b37bf3423180b7f24 | 683,872 |
def xor_fixed_buffers(buf1, buf2):
"""
Creates XOR buffered string from two hex string buffers
:param buf1: hex encoded string
:param buf2: hex encoded string
:return: xor hex encoded string
"""
# Convert hex to bytearray
decoded_hex_buf1 = bytearray.fromhex(buf1)
decoded_hex_buf2 =... | ea9f7f88f8653ef55774383a2734c14324283bf1 | 683,873 |
def fancy_time(build_time):
"""
returns build time in human readable form
:param build_time: total time taken for the build
"""
seconds = build_time.seconds
minutes = round(seconds / 60)
hours = round(seconds / 60 / 60)
days = build_time.days
f_time = ""
if days > 0:
... | 1942cc46e45ff6e08d53b92784678945d79fa5d1 | 683,874 |
def previous(some_list, current_index):
"""
Returns the previous element of the list using the current
index if it exists. Otherwise returns an empty string.
"""
try:
return some_list[int(current_index) - 1] # access the previous element
except:
return '' | d886b30c304a448dd76ecb3b10c20a5ef1f31aee | 683,875 |
def get_truck(client, truck_id):
"""
returns the truck specified.
:param client: The test client to make the request with
:param truck_id: The id of the truck to find
:return: truck with id=id
"""
return client.get(f'/api/trucks/{truck_id}') | a03814daa72a91859c3668dc3b852fd20a6ca9e9 | 683,877 |
import json
def read_json(filename):
"""
Permet de lire un fichier json.
"""
with open(filename, encoding="utf-8") as fichier:
data = json.load(fichier)
fichier.close()
return dict(data) | 5db060fdd093123466f540865f6a7d1247302b01 | 683,878 |
import json
def get_file_list(hypes, phase):
"""
Get a list of tuples (input, output) of files.
Parameters
----------
hypes : dict
phase : {'train', 'test'}
"""
x_files, y_files = [], []
jsonfile = hypes['data'][phase]
with open(jsonfile) as data_file:
data = json.loa... | cea247f15846b1ab476c39019687d63891d37c2b | 683,880 |
import os
import numpy
def write_ipf(dir,teff,logg,metals,am,nm,cm,vm=None):
"""
NAME:
write_ipf
PURPOSE:
write a FERRE input.ipf file
INPUT:
dir - directory where the input.ipf file will be written to
Parameters (can be 1D arrays):
teff - Effective temperature (K... | faefc13a34aea372c14f90ad93f2de099ae5cbc8 | 683,881 |
def ros_service_response_cmd(service, result, _id=None, values=None):
"""
create a rosbridge service_response command object
a response to a ROS service call
:param service: name of the service that was called
:param result: boolean return value of service callback. True means success, False failu... | 963c2b69d07dd01c393be11050310ac325d37516 | 683,882 |
def escapeAttrJavaScriptStringDQ(sText):
""" Escapes a javascript string that is to be emitted between double quotes. """
if '"' not in sText:
chMin = min(sText);
if ord(chMin) >= 0x20:
return sText;
sRet = '';
for ch in sText:
if ch == '"':
sRet += '\\"'... | 1c2f0f9e77e988c68d3fa48caa180761595c0b7c | 683,883 |
import os
def InternetConnectionCheck() -> bool:
"""
Test internet connection
"""
response = -1
if os.name == "nt": # if is windows
response = os.system(f"ping -n 1 google.com > NUL")
else:
response = os.system(f"ping -c 1 google.com > /dev/null 2>&1")
return response == 0 | b1f4246f1abd9da47b8da746ec2c59e605860901 | 683,884 |
def center_scale_to_corners(yx, hw):
"""Convert bounding boxes from "center+scale" form to "corners" form"""
hw_half = 0.5 * hw
p0 = yx - hw_half
p1 = yx + hw_half
return p0, p1 | 1dcc9204da54905c880870d7e5c7ae440c289415 | 683,885 |
import re
def size_to_bytes(size):
"""
Returns a number of bytes if given a reasonably formatted string with the size
"""
# Assume input in bytes if we can convert directly to an int
try:
return int(size)
except:
pass
# Otherwise it must have non-numeric characters
size... | 3d747d2d01a0b603e2c4593522e38a988f3c375c | 683,886 |
from typing import Union
def get_error_message(traceback: str) -> Union[str, None]:
"""Extracts the error message from the traceback.
If no error message is found, will return None.
Here's an example:
input:
Traceback (most recent call last):
File "example_code.py", line 2, in <module>
... | bb1ccbb55e15a9670efbb4ddc71b22a35cfd9b17 | 683,887 |
def decode_to_text(encoded_list):
"""Decode an encoded list.
Args:
encoded_list: Encoded list of code points.
Returns:
A string of decoded data.
"""
return ''.join([chr(c) for c in encoded_list]) | 229db29b3fdd66eee361c786c7a6a3caefc2a6ae | 683,888 |
from pathlib import Path
from typing import Optional
from typing import Tuple
import warnings
def get_imzml_pair(path: Path) -> Optional[Tuple[Path, Path]]:
"""get the pair of '.imzml' and '.ibd' files in the archive
Args:
path (Path): Folder containing both files
Returns:
Optional[Tuple... | 1e3002680be2c703a460561db1f181b62b1fa7d3 | 683,889 |
def read(filepath, readfunc, treant):
"""Read data from a treant
Args:
filepath: the filepath to read from
readfunc: the read callback
treant: the treant to read from
Returns:
the data
"""
return readfunc(treant[filepath].abspath) | 24e94b244dacd603158a9d779a167133cdd2af50 | 683,890 |
def create_class_agnostic_category_index():
"""Creates a category index with a single `object` class."""
return {1: {'id': 1, 'name': 'object'}} | cb014efb03b9905a8560cfa46e6c271da95dbd05 | 683,891 |
from typing import List
import logging
def tag2word(chars: str, tags: List[str], verbose=False):
""" 将 tag 格式转为词汇列表,
若格式中有破损不满足 BI 标准,则不转换为词汇并支持报错。
该函数针对单条数据处理,不支持批量处理。
Args:
chars(str): 输入的文本字符串
tags(List[str]): 文本序列对应的标签
verbose(bool): 是否打印出抽取实体时的详细错误信息,该函数并不处理报错返回,
... | b926e8c4f142d2d9f486f53e7aebb7a9c95b7eab | 683,892 |
import re
def is_project_issue(text):
"""
Issues/pull requests from Apache projects in Jira.
See: https://issues.apache.org/jira/secure/BrowseProjects.jspa#all
>>> is_project_issue('thrift-3615')
True
>>> is_project_issue('sling-5511')
True
>>> is_project_issue('sling')
False
... | f96f63488c97311cdc79f3fa2dd526023e300969 | 683,893 |
def get_vector05():
"""
Return the vector with ID 05.
"""
return [
0.5,
0.5,
] | 3b7609c473ec6e5b78f570e80a0716e90ada6bb5 | 683,894 |
def pandas_arguments_upload():
"""Return a dict with the keyword arguments for pandas."""
return {
"csv": {"header": ["one", "two"]},
"json": {"orient": "index"},
"txt": {"header": ["one", "two"]},
"xls": {"header": ["one", "two"]},
"xlsx": {"header": ["one", "two"]},
... | dc92fddf264a4cb202648ed79b25175e4465eab5 | 683,895 |
def recognition_sphinx(speech, status):
"""We get the command"""
print("Произнесите команду в течении 10 секунд")
# Need to add recording and saving audio track
for phrase in speech:
if status.isSet():
status.clear()
print("Команда получена")
return phrase | cdd793009e95c4726a6fcc018d08bc90dda77f05 | 683,896 |
def build_globals():
"""Returns a dictionary that can be used as globals for exec."""
return {
'__name__': '__p1__',
'__doc__': None,
'__builtins__': __builtins__
} | 8a3ddc6b745afab0fd8ee4a5369883476a80c30f | 683,897 |
def read_input(fpath):
"""
Read the global input file.
Args:
fpath (str): Path to the input file to read.
Returns:
list
"""
with open(fpath, 'r') as f:
return [line.strip() for line in f.readlines()] | 11d14dcd8db05b6f23e53d8233448da23495907a | 683,898 |
def combine_last_two_dimensions(x):
"""Reshape x so that the last two dimension become one.
Args:
x: a Tensor with shape [..., a, b]
Returns:
a Tensor with shape [..., a*b]
"""
# old_shape = x.get_shape().dims
# a, b = old_shape[-2:]
# new_shape = old_shape[:-2] + [a * b if ... | 3afe72f237eab111629b34e91bdbc82a48043cf2 | 683,899 |
def calc_velocity(dist_km, time_start, time_end):
"""Return 0 if time_start == time_end, avoid dividing by 0"""
return dist_km / (time_end - time_start).seconds if time_end > time_start else 0 | c96131b6bfd46e1da8852eca4970be8a77c41d8f | 683,900 |
import os
import io
import json
import logging
import sys
def read_setting(config_filename):
"""
Load Config from json file.
config_filename default is 'config.json'
"""
# config_path = os.path.join(application_path, config_filename)
if os.path.exists(config_filename):
with io.open(con... | 9a9db0b043f3c9c3d7b5ee925484e3e8e9774487 | 683,901 |
def get_factor_value(data, name, prefix, result):
"""Get value from data by name
then by "prefix+name" as key, put the value in result
return result[key] and new prefix
When the data is list, need loop the data.
In this case, the default value of result[key] is empty array,
if value is list, ex... | 93637cd168cefb5f9322bf9675efa4c54a2b902b | 683,902 |
from typing import OrderedDict
def metadata_xml_to_json(elem):
"""Convert metadata xml into JSON format"""
assert elem.tag == 'metadata', "Invalid metadata file format"
def _xml_to_json(elem):
"""Convert xml element to JSON object"""
out = OrderedDict()
for child in elem.getchildr... | 741102e112bd153caa7fc35642e8a4697f8e3aca | 683,904 |
def _cell_fracs_sort_vol_frac_reverse(cell_fracs):
"""
Sort cell_fracs according to the order of increasing idx and decreasing
with vol_frac.
Parameters
----------
cell_fracs : structured array
The output from dagmc.discretize_geom(). A sorted, one dimensional
array, eac... | 74ab5c5cee05e83612dace0c4e1ec4ea80ca4858 | 683,905 |
import os
def checkValidFilePath(filepath, makeValid=True):
"""Checks whether file path location (e.g. is a valid folder)
This should also check whether we have write-permissions to the folder
but doesn't currently do that!
added in: 1.90.00
"""
folder = os.path.split(os.path.abspath(filepat... | 3fdee357d3578e3f5f607b0ed8b7467bee720b1d | 683,906 |
import re
def remove_urls(text):
"""
删除https/http等无用url
:param text: str
:return: str
"""
text_remove_url = re.sub(r"(全文:)?(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b",
"", text, flags=re.MULTILINE)
return text_remove_url | 115235eb8cfbdd502fd492c8faa91382237e88ed | 683,907 |
import os
def read_seqmaps(fname):
"""
seqmap: list the sequence name to be evaluated
"""
assert os.path.exists(fname), 'File %s not exists!'%fname
with open(fname, 'r') as fid:
lines = [line.strip() for line in fid.readlines()]
seqnames = lines[1:]
return seqnames | ef5721ae12d473d92c7ba4f1bc394e8d4070e9ad | 683,909 |
def reverse(s):
"""return the str that be reversed"""
if len(s) == 0: # basic case
return ""
return reverse(s[1:]) + s[0] | 1739b006e99752901522852c696ab05048dec453 | 683,910 |
import math
def fromSpherical(r, theta, phi):
""" convert spherical coordinates to 3-d cartesian coordinates """
return r*math.sin(theta)*math.cos(phi), r*math.sin(theta)*math.sin(phi), r*math.cos(theta) | fda9ddb7a777504452822a34aa15671965de5566 | 683,911 |
import argparse
def parseCmd():
"""Parse command line arguments
Returns:
dictionary: Dictionary with arguments
"""
parser = argparse.ArgumentParser(description='Creates hints for EVM and ' \
+ 'TSEBRA from ProteinAlignment file in gff format')
parser.add_argument('--topProts', typ... | e88c38538f3f23a9876f275ba4eac923c702b0e8 | 683,912 |
import torch
def cross_product_matrix(v):
"""skew symmetric form of cross-product matrix
Args:
v: tensor of shape `[...,3]`
Returns:
The skew symmetric form `[...,3,3]`
"""
v0 = v[..., 0]
v1 = v[..., 1]
v2 = v[..., 2]
zero = torch.zeros_like(v0)
mat = torch.stack([... | 5cf69cc7f57b085070418234c8422f0646013a0c | 683,913 |
import glob
import os
import shutil
def _make_workdir(base_dir, slurm_template):
"""Make working directory for a single cluster job."""
# Get all direcories in base dir and convert to integers
dnames = glob.glob(base_dir + "/*")
runids = [
-1,
]
for i in range(len(dnames)):
tr... | d21bf44d87aaaecfcd9c8cb6b0042c98fd936112 | 683,914 |
import os
def get_setting(key, msg, default=None):
"""設定値を取得する。
Parameters
----------
key : str
設定値取得のためのキー。
msg : dict
Pub/Subから受け取ったメッセージ。
default : str, optional
設定値が存在しなかった際のデフォルト値。
Returns
-------
str or None
設定値(存在しない場合は `None` もしくは `default`... | 62ae2fe3b317871b234f31cf3eb698491f8c0b2d | 683,916 |
def max_dos(n1: int, n2: int):
"""[Funcion que devuelve el numero mayor de dos numeros]
Args:
n1 ([int]): [Primer numero a comparar]
n2 ([int]): [Segundo numero a comparar]
Returns:
[n_max]: [Numero mayor de los dos]
"""
if n1 > n2:
return n1
elif n2 > n1:
... | a9a9424d7637e9df7d9cf19f05f914295312239c | 683,917 |
def is_generator(iterable):
"""
Check if an iterable is a generator.
Args:
iterable: Iterable.
Returns:
boolean
"""
return hasattr(iterable, '__iter__') and not hasattr(iterable, '__len__') | b441a96c42c2c57d3ec26ecf64d5b4392d837c0b | 683,918 |
import argparse
import getpass
def get_args():
""" Get arguments from CLI """
parser = argparse.ArgumentParser(description='Create VMW VM from template')
parser.add_argument('-u', '--user', help='VC User', required=True)
parser.add_argument('-p', '--passw', help='VC User Pass', required=False)
par... | 4bc35ca0c58e80abc09a544b33b9656ee89ae7e4 | 683,919 |
import yaml
def std_receive_command(send):
"""
Standardise la réception des commandes
Params :
string send => Mettre socket.recv()
Return :
Dict
"""
return yaml.safe_load(send) | 9348b0a8f12e36dcd78d5e8f8f33566ebb65584b | 683,920 |
def value_from_char(character):
"""
Args:
character (string): Takes an ASCII alphabet character
and maps it 0-25, a-z.
Returns:
int: Numerical representation of the ASCII alphabet character inputted.
"""
return ord(character.lower()) - ord('a') | fef2b6235be1188329a5d9bbba376f865fbf193f | 683,921 |
import inspect
def caller(n=1):
"""Return the name of the calling function n levels up in the frame stack.
>>> caller(0)
'caller'
>>> def f():
... return caller()
>>> f()
'f'
"""
return inspect.getouterframes(inspect.currentframe())[n][3] | df142a8416da526a3af5a00cd8d473ea35d6bfd5 | 683,922 |
def rss_configuration(bot):
"""Load configuration"""
config = bot.config.get(__name__, {})
"""Remove default hash key from config and determine commands"""
if 'hash' in config:
del config['hash']
return config | 24eb22321acaab9aed5efb430bb3616393c9eed4 | 683,923 |
import collections
def parse_result_ranks(stream):
"""Reads a results stream: one line per item, expected format:
``qid, iter, docno, rank, sim, run_id``.
The output data structure is a dict indexed by (tid, docno)
and the values are ranks.
"""
ranks = collections.defaultdict(int)
for i, ... | 50679336dd9fe0596c091196d7eef5d3bb808775 | 683,924 |
def getFormURL(form_id):
""" Return a form URL based on form_id
"""
return 'https://docs.google.com/forms/d/%s/viewform' % (form_id, ) | c206e89d7246be95586f51d363490e9124a56a16 | 683,925 |
def coroutine(func):
"""
decorator that makes a generator function automatically advance to its
first yield point when initially called.
"""
def wrapper(*args, **kwargs):
gen = func(*args, **kwargs)
gen.next()
return gen
wrapper.__name__ = func.__name__
wrapper.__di... | 0791171d6eaf228001dadef8e27feb912142e6c9 | 683,926 |
import unicodedata
def to_ascii(s):
"""
Translates the string or bytes input into an ascii string with the
accents stripped off.
"""
if isinstance(s, bytes):
s = s.decode('utf-8')
return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) | fb86e21b66a1abd9acd144cbcb596a2d8835b748 | 683,927 |
import re
def _expect_regex(client, regex):
"""Reads a line from the client, parses it using the regular expression."""
line = client.read_line()
match = re.match(regex, line)
if not match:
raise ValueError("Received '{}' which does not match regex '{}'".format(
line, regex))
return match.groupd... | c76bd2b5548a58585edea911acea575431e909d2 | 683,928 |
import os
import re
def detect_watchdog_device():
"""
Find the watchdog device. Fall back to /dev/watchdog.
"""
wdconf = "/etc/modules-load.d/watchdog.conf"
watchdog_dev = "/dev/watchdog"
if os.path.exists(wdconf):
txt = open(wdconf, "r").read()
for line in txt.splitlines():
... | b8b7420128a2c1e6edbf45bff1fa8ed4ff7403e9 | 683,929 |
import tempfile
def tmp():
"""
Return the location of the temporary directory.
"""
return tempfile.gettempdir() | c8063a86642686088bcb615f559cdc968b0a4ad2 | 683,930 |
import torch
def rejoin_props(datasets):
"""
Rejoin properties from datasets into one dictionary of
properties.
Args:
datasets (list): list of smaller datasets
Returns:
new_props (dict): combined properties
"""
new_props = {}
for dataset in datasets:
for key, va... | f0913486571ea14d5ecf0fab7e9021b7663f3ad7 | 683,931 |
def choose_healing_potion():
"""A healing potion, works as advertised."""
return "healing potion" | a1da940fc1d8f2ec80dc7882f1879c47f0c5b246 | 683,932 |
def _l_str_ ( self ) :
"""Self-printout of line: (point, direction)
>>> line = ...
>>> print line
"""
return "Line3D(%s,%s)" % ( self.beginPoint() , self.direction() ) | 816564e5d27a3a2afbc5f0173928dea06585f34a | 683,933 |
import os
def file_size(file_path):
"""this function will return the file size"""
if os.path.isfile(file_path):
file_info = os.stat(file_path)
return file_info.st_size | 57c44236f4a16173729e15b46a3ac2f9cca01505 | 683,934 |
def parents_at_rank(graph, root, parent_rank):
"""
loop through graph from root taxon, assigning leaf nodes to parent nodes at
a given rank.
"""
parents = {}
def descend(root, parent):
"""
Iteratively descend from a root to generate a set of taxids
unless the child taxid... | e14e62ecb6acc2f4dc85248c33811669a0ff76e1 | 683,935 |
def get_mesh_texture(bsp, mesh_index: int) -> str:
"""Returns the name of the .vmt applied to bsp.MESHES[mesh_index]"""
mesh = bsp.MESHES[mesh_index]
material_sort = bsp.MATERIAL_SORT[mesh.material_sort]
texture_data = bsp.TEXTURE_DATA[material_sort.texture_data]
return bsp.TEXTURE_DATA_STRING_DATA[... | 55db88564032771d2ba8b41513d1b55077809542 | 683,936 |
def verify_askingto_by_verify_y(actor, x, y, ctxt) :
"""Updates the actor for y to x and then verifies that action."""
y.update_actor(x)
return ctxt.actionsystem.verify_action(y, ctxt) | 09a089ab29042d371849efdcbe16ed6a15720b83 | 683,937 |
def create_document(bookmark):
"""Creates a Document (a dict) for the search engine"""
return {
"id": str(bookmark.id),
"title": bookmark.title or "",
"notes": bookmark.notes or "",
"tags": ", ".join([tag.name for tag in bookmark.tags]),
} | a3af46f6827b725f949056de0372e2d55121874f | 683,938 |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled for... | 9e94788a4d9b6c102e56cc95422b5f367754b22e | 683,939 |
def position_from_instructions(instructions, path=None):
"""
Find out what position we're at after following a set of instructions.
"""
x = y = 0
heading = 0 # 0 = N, 1 = E, 2 = S, 3 = W
instructions = instructions.split(', ')
for instruction in instructions:
turn = instruction[:1]... | e153f855834a615ba9fd789d5e1347769a4e5021 | 683,940 |
import csv
def get_data_X_y(data_dir, X=[], y=[]):
"""Read the log file and turn it into X/y pairs."""
with open(data_dir + 'driving_log.csv') as fin:
next(fin)
log = list(csv.reader(fin))
for row in log:
if float(row[6]) < 20: continue # throw away low-speed samples
X +=... | f906b9fdbb76b3eac59ece9ec1d6d56452dffce2 | 683,941 |
def company_data():
"""Returns a dict for some `Company` (`account_validation=True`)."""
company_option_1 = {
"companyname": "Craig, Smith and Ford",
"companystreet": "8429 Jones Street",
"companyplz": "71974",
"companycity": "Valerieshire",
"companycountry": "United Stat... | 488f80c9d806fe77610bc663a704ea065fada208 | 683,942 |
import subprocess
import sys
def git_hash() -> str:
"""Returns the current git hash.
Returns
-------
_git_hash: str
The current git hash.
"""
try:
_git_hash = subprocess.check_output(["git", "rev-parse", "HEAD"], stderr=subprocess.PIPE).decode().strip()
except FileNotFound... | 10c8e4215944e3ea9e3ace08218f1ae7ec3b5c8f | 683,943 |
def sigfig(number, places):
"""
Round `number` to `places` significant digits.
Parameters:
number (int or float): A number to round.
places (int): The number of places to round to.
Returns:
A number
"""
# Passing a negative int to round() gives us a sigfig determinatio... | 0aae9fff082b35a18418b2dae8c6b6787e3c947a | 683,944 |
from datetime import datetime
def read_time_stamp (out):
"""Reads timestamp from a file provided. Format: time.time()"""
st_hd = open(out, 'r')
st = st_hd.read()
st_hd.close()
stamp = datetime.fromtimestamp(float(st)).strftime('%Y-%m-%d %H:%M:%S')
return(stamp) | 1f87cc1b38b03d48d04547f22848a22e0d7b95d6 | 683,945 |
import os
def identify_netcdf_and_csv_files(path='data'):
"""Crawl through a specified folder and return a dict of the netcdf d['nc']
and csv d['csv'] files contained within.
Returns something like
{'nc':'data/CNRS_data/cSoil/orchidee-giss-ecearth.SWL_15.eco.cSoil.nc'}
"""
netcdf_files = []
... | eedefd371d3fd3b4b08a5d0d2bb2ef5ade4cec21 | 683,946 |
import json
def load_characters(path_to_backup):
"""
Characters are saved in a json file.
Read and return the saved content
as a Python dict.
"""
with open(path_to_backup, 'r') as content:
try:
return json.loads(content.read())
except json.JSONDecodeError:
... | f2570fbb0d719b2fe97dc8ea4fe605b99666d3cd | 683,947 |
import hashlib
def file_hash(filename):
"""
Hash the contents of the specified file using SHA-256 and return the hash
as a string.
@param filename The filename to hash the contents of
@return String representing the SHA-256 hash of the file contents
"""
hasher = hashlib.sha256()
with... | 933c79a20bf56a4953eff2b90ceec698db870ebf | 683,948 |
def check_raster_clip_crs(
raster_dataset, roi_bbox, enable_transform=True, verbose=False
):
"""
Check band crs match to provided bbox
Parameters
----------
raster_dataset: raster instance opened by rasterio
roi_bbox: geodataframe instance
enable_transform: bool to enable trasnform or r... | 0f64e7e1e45bb118f38798f0d06de74ef6a88088 | 683,950 |
def port( location, standard ):
"""Extracts the port"""
end = location.find(':')
if -1 == end or len(location) == 1+end:
return standard
return int(location[1+end:]) | 8a446780bf096e0cbf233ef736602cc004258f4a | 683,951 |
def get_matrix08():
"""
Return the matrix with ID 08.
"""
return [
[4.0, 5.0, 10.0],
[3.0, 10.0, 6.0],
[3.0, 20.0, 2.0],
[2.0, 15.0, 5.0],
] | 1a3e836d9a6558261466ae5103e91fb0984f93d9 | 683,952 |
def unionRect(rect1, rect2):
"""Return the smallest rectangle in which both input rectangles are fully
enclosed. In other words, return the total bounding rectangle of both input
rectangles.
"""
(xMin1, yMin1, xMax1, yMax1) = rect1
(xMin2, yMin2, xMax2, yMax2) = rect2
xMin, yMin, xMax, yMax ... | 4f81c8e0eeabe181ac9fab439d289ba6f2d923a6 | 683,953 |
import numpy
def problem_6(limit=100):
"""The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural
... | 4842df7fed10b3d51dbb2bc8dcfeba3db9055266 | 683,954 |
def to_markdown_table(pt):
"""
Print a pretty table as a markdown table
:param py:obj:`prettytable.PrettyTable` pt: a pretty table object. Any customization
beyond int and float style may have unexpected effects
:rtype: str
:returns: A string that adheres to git markdown table rules
"""... | adce2949a462c0b191e9a82bcb2f05712f5dad4d | 683,955 |
import importlib
def _get_module(service_type):
"""Get the module for service_type."""
try:
parts = service_type.split('/')
if len(parts) == 2:
parts = [parts[0], 'srv', parts[1]]
package_name = parts[0]
module = importlib.import_module('.'.join(parts[:-1]))
... | 41ad56d53392fda31eeefdd30d550924580e97da | 683,956 |
import re
def tokens_from_treestring(s):
"""extract the tokens from a sentiment tree"""
return re.findall(r"\([0-9] ([^\(\)]+)\)", s) | 63c86b17e4fe992af44b3987475f5d2675b9c30f | 683,957 |
def build_synthethic_iid_datasets(client_data, client_dataset_size):
"""Constructs an iterable of IID clients from a `tf.data.Dataset`.
The returned iterator yields a stream of `tf.data.Datsets` that approximates
the true statistical IID setting with the entirety of `client_data`
representing the global distri... | 8e9da5194d0249b837be78315875106227e5564b | 683,958 |
from typing import Any
from typing import Dict
def _as_str(key: str, entry: Any) -> Dict[str, str]:
"""Convert an entry to a string"""
if isinstance(entry, dict):
values = {}
for subkey, subentry in entry.items():
values.update(_as_str(f"{key}__{subkey}", subentry))
return ... | 125256efa1cb6481229b368b917c57ae83e82b80 | 683,959 |
def is_int(s: str) -> bool:
"""Test if string is int
Args:
s (str): Input String
Returns:
bool: result of test
"""
try:
int(s)
return True
except ValueError:
return False | c454ba51fb0dec8cc1b9b4706849ee4c17995234 | 683,960 |
from pathlib import Path
def _new_file(file: Path) -> Path:
"""Return the same file path with a .new additional extension."""
return file.with_suffix(f"{file.suffix}.new") | e7adafdecbe4d7fdef53e188895de33ae3b589cd | 683,961 |
def compute_facility_energy(F, pairwise_distances, centroid_ids):
"""Compute the average travel distance to the assigned centroid.
Args:
pairwise_distances: 2-D Tensor of pairwise distances.
centroid_ids: 1-D Tensor of indices.
Returns:
facility_energy: [1]
"""
return -1.0 * F.sum(... | a82732fc1bbfb9960f8d9de769dc1806f144bc2b | 683,962 |
import re
def search_query(query):
"""Process search query"""
return re.sub(r"[^\w]", r"", query.lower()) | 5097b7dc391a72fb199e7a9ea1567f46379d9995 | 683,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.