content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_student_record(student, teacher):
"""Create and return a student record object"""
student_record = {
"id": student["id"],
"firstName": student["fname"],
"lastName": student["lname"],
"email": student["email"],
"ssn": student["ssn"],
"address": student["... | b6bfc7af0441c95f57ed50e5e80fdcdf866a5f66 | 637,758 |
import click
def is_valid_job(job) -> bool:
"""Detect interface contracts.
This utility function is used to detect interface contracts in solc and Truffle
artifacts. This is done by checking whether any bytecode or source maps are to be
found in the speficied job. This check is performed after the pa... | 5185c03419c8512799db9ea13546e63e91932ac0 | 637,760 |
import json
import os
import logging
def load_labeled_files_json(json_datafile_path):
"""
Load a JSON file which contains a list of {'raw': 'xy', 'mask': 'z'}.
Parameters
----------
json_datafile_path : str
Path to a JSON file which contains a list of labeled images.
Returns
----... | 070a07b554aaa980032646abd4b5a5c4e4f79c10 | 637,761 |
import json
def load_lens_json(lens_output_path: str):
"""Loads in JSON data pulled from the Lens API.
Args:
args (lens_output_path): Path of the JSON file.
Returns:
dict: A dictionary representing the JSON file.
"""
with open(lens_output_path, 'r', encoding='cp866') as json_file:... | 33d5564d04b8f3252882bff5784966a5ac08e047 | 637,762 |
from pathlib import Path
def _get_activity_names_path(data_processed_dir: str) -> Path:
"""Returns path to the file with activity names.
"""
return Path(data_processed_dir, "activity_names.json") | a9b9224aaefb4b170cd8b2c539e353ac4f0c8d54 | 637,764 |
import typing
async def pagify_commands(coms: typing.List[str]) -> typing.List[str]:
"""Takes a list of command names and returns a pagified list
It will return a page of 15 commands
Parameters
----------
coms: List[:class:`str`]
The list of commands to iterate over
Returns
----... | 21b1acb5b56a6ced7ce49eea93b0a8ca665a8061 | 637,766 |
import sympy
def symbolize(pair):
"""Turn a pair of symbol names into a pair of symbols."""
return (sympy.Symbol('x' + str(pair[0])),sympy.Symbol('x' + str(pair[1]))) | 78953374868ecd10989e796881003bb7ef38b036 | 637,768 |
def list_all_videos(api_instance, location, account_id, access_token, page_size=100): # noqa
"""List all videos, using the API paging mechanism.
The default page_size is set to 100 (the API default is 25).
"""
done = False
skip = 0
all_videos = []
while not done:
list_videos = api_... | e86960a23ccbb19a18bd4bedafa0db37869695ba | 637,769 |
import json
def DictToJSON(pydict):
"""Convert a dict to a JSON-formatted string."""
pretty_string = json.dumps(pydict, sort_keys=False, indent=2)
# json.dumps sometimes returns trailing whitespace and does not put
# a newline at the end. This code fixes these problems.
pretty_lines = pretty_string.split('... | 9c02d41efc12d27f210d2d0260826a7f2edaddd2 | 637,770 |
def get_argument_name(arg_parser, *args, **kwargs):
"""Takes argparse arguments and returns the dest name.
"""
try:
return arg_parser._get_optional_kwargs(*args, **kwargs)['dest']
except ValueError:
return arg_parser._get_positional_kwargs(*args, **kwargs)['dest'] | fd79a2d4e818842c79852e837049c24c07e815e9 | 637,771 |
import pandas
def results_as_dataframe(user_actions, recommendations):
"""
Converts the recommendation results into a pandas dataframe for easier evaluation.
@param user_actions: A list of the actually performed user actions.
@param recommendations: For each of the performed actions the list of calcul... | 102df770d6f252aad8c2c73f396d293f312c1595 | 637,772 |
def icc_brightness_int(brightness: float, min_brightness = 0.05) -> int:
"""Brightness values are stored as integers, with a brightness of 1.0 stored as hex 65536."""
if brightness > 1.0 or brightness < min_brightness:
raise ValueError(f"Brightness {brightness} swas invalid. Must be between {min_bright... | d570be1af25702c70cbed74637b9fe7db2d7a7ca | 637,773 |
def normalise_number_of_homologues_to_categorical_variable(x):
""" DEPRECATED. Replaced with cubed root of the n_homologues.
Convert non-linear number of homologues to an integer value.
Parameters
----------
x : int
Number of homologues in fasta alignment of TMD region including gaps.
"... | c9f878703a00f78e4cc843a4aa55c6bd7bc2abd2 | 637,774 |
def get_sizeChange(size1, size2):
""" Returns change in size of an echo as the ratio of the larger size to
the smaller, minus 1. """
if (size1 < 5) and (size2 < 5):
return 0
elif size1 >= size2:
return size1/size2 - 1
else:
return size2/size1 - 1 | d8b75fa231c8a957db68e7fbac4e1f6ff2270533 | 637,777 |
def set_id(project_id, entity, args):
"""
:param project_id:
:param entity:
:param args:
:return:
"""
entity["_id"] = str(project_id) + "-" + str(entity[args.get('id')])
return entity | 347bb8049232e17c523d07ce5a2fe190c80be249 | 637,778 |
import random
def random_crop2d(*images, min_perc=0.5, max_perc=1.):
"""Crop randomly but identically all images given.
Could be used to pass both mask and image at the same time. Anything else will
throw.
Warnings
--------
Only works for channel first images. (No channel image will not work... | 80d512f3a84b658ee70dde8311be0318aa89a068 | 637,779 |
import torch
def split_and_sum(tensor, N):
"""spliting a torch Tensor into a list of uneven sized tensors,
and sum each tensor and stack
Example:
A = torch.rand(10, 10)
N = [4,6]
split_and_sum(A, N).shape # (2, 10)
Args:
tensor (torch.Tensor): tensors to be split and ... | ba2c677935946967f7fc755b51234b003e119652 | 637,780 |
def csv_list(l):
"""Format list to a string with comma-separated values.
"""
if len(l) == 0:
return ""
return ', '.join(map(str, l)) | 0b9388d97a0620c8a105d2fd766358fbbfcc8ae8 | 637,782 |
import six
import sys
def wsgi_app(monkeypatch):
"""Return a WSGI app stub."""
class WSGIAppMock:
"""Mock of a wsgi module."""
def application(self):
"""Empty application method.
Default method to be called when no specific callable
is defined in the wsgi ... | 7e64f1cf1b54eddfaab38813e82a4040062f431c | 637,783 |
from typing import List
def catrmd(filenames: List[str],
input_path: str = './',
output_name: str = "cat.Rmd",
output_path: str = './') -> None:
"""Create an R markdown file from markdown files and scripts."""
def read_file(filename):
with open(filename) as file:
... | ac7e56f92a0490a0cb6ecd7226a90c38bb7ef9b8 | 637,784 |
def var_name(string: str) -> str:
"""Strips out the Variable name from a string
:param string: e.g. $MY_PATH:$YOUR_PATH
:return string: e.g. MY_PATH
"""
key = ""
for char in string:
if char.isalpha() or char.isdigit() or char == "_":
key += char
else:
retu... | acce01104edaffc3ffe72c98e362ae0c0bcfa131 | 637,786 |
def normalize_input(defined_symbols):
"""Normalize input and remove duplicates."""
symbols = set()
normalized_symbols = []
for value in defined_symbols:
if isinstance(value, str):
if not (value in symbols):
symbols.add(value)
normalized_symbols.append... | d971027140efe7917169f52e2c84c63cda5e4ac7 | 637,787 |
def load_embeddings(path, dimension=300):
"""
Loads the embeddings from a word2vec formatted file.
word2vec format is one line per word and it's associated embedding
(dimension x floating numbers) separated by spaces
The first line may or may not include the word count and dimension
"""
vect... | 0ae0777b371781ffbc1519f5828aa9d492b364d9 | 637,788 |
def nlineas(n):
"""Escribe n líneas o línea según el valor de n"""
if n == 0:
return "cero líneas"
elif n == 1:
return "una línea"
elif n == 2:
return "dos líneas"
else:
return "%d líneas" % n | addee9fcbab080ddbdf69c5cda573b557f0a6c59 | 637,789 |
import re
def clean_conditional_autograd_lname(l_name, l_type):
""" clean autograd layer names for conditional ops."""
l_name = re.sub("/cond_grad/", "/cond/", l_name)
l_name = re.sub("/StatelessIf/", "/", l_name)
for cond_str in ["/cond/else", "cond/then"]:
l_name = re.sub(r"{}/_[0-9]+/gradie... | 70cc293b4b439f7adc7d0f4641bd5683b912f0d5 | 637,790 |
from pathlib import Path
def subjects_data_folder(folder: Path, rglob: bool = False) -> Path:
"""Given a root_data_folder will try to find a 'Subjects' data folder.
If Subjects folder is passed will return it directly."""
if not isinstance(folder, Path):
folder = Path(folder)
if rglob:
... | 69e30bb001ec412b5341212fb3fd58065dc5b77c | 637,791 |
from typing import List
import os
import mimetypes
def get_images_in_a_directory(filepath: str) -> List[str]:
"""pass in a filepath to get a sorted list of images in a dir
Args:
filepath (str): path to images
Returns:
List[str]: sorted list of image files
"""
all_files = os.listd... | f8538eaa0d38c6abc68d353de6c7836fab126fa9 | 637,792 |
def getConfigIds(config):
"""Get a list of all config fields that have been set along with the ID.
:param config: The configuration object
:type config: configuration.Configuration
"""
fields = [
f + ': ' + str(getattr(config, f)) for f in dir(config)
if not f.startswith('_')
... | 2f9b9258ebf2b001df2e3344853541425bb3adb7 | 637,793 |
def lasso(number: complex, unit: str = '') -> str:
"""
Make a large number more readable by inserting commas before every third power of 10 and adding units
"""
return f'{number:,} {unit}'.strip() | ce79711c10f44d88865f36c63023fc7a276a691f | 637,794 |
def format_register_value(val):
"""
Encode each byte by two hex digits in little-endian order.
"""
result = ""
mask = 0xff
shift = 0
for i in range(0, 8):
x = (val & mask) >> shift
result += format(x, '02x')
mask <<= 8
shift += 8
return result | f333114086fbfd53e76944336195b46d04a5a233 | 637,795 |
def render_header(level_and_content):
"""
- level_and_content: None OR string OR list of [postive-int, string] OR tuple of
(positive-int, string), the header level and content
RETURN: string, the header
"""
if level_and_content is None:
return ""
if isinstance(level_and_content, st... | 948e1f16c3ce11a6f30c12a44cdb436aae4b79d8 | 637,796 |
def get_table_j_1():
"""表J.1 節湯の効果係数
Args:
Returns:
list: 表J.1 節湯の効果係数
"""
# 表J.1 節湯の効果係数
table_j_1 = [
# f_sk_A
0.91,
1.00,
# f_sk_C
0.70,
1.00,
1.00,
# f_ss_A
0.80,
1.00,
# f_ss_B
0.85,
... | 5587557eb234b96c15edc627f8dedceec8232baa | 637,797 |
def remove_coords(cube):
"""
Remove non-essential coordinates from ``cube``. This should prevent a number
of subsequent cube concatenation issues, plus reduce output file size. Note,
however, that scalar coordinates, such as level number in the case of a
vertical subset, are also removed.
"""
... | 06b5992bb457c8a63ba7e290b981af8bc66229cc | 637,798 |
import os
def tests_path():
""" """
return os.path.abspath(os.path.dirname(__file__)) | 4e3dd054757225fc33585f1fe0a9731ebc97fbe8 | 637,799 |
def add_gencfg_parser_options(p):
"""Add `pbsv1 genenrate-config` parser options"""
p.add_argument('-o', '--cfg_fn', metavar="sv.cfg", dest="cfg_fn",
type=str, default=None, help="Pbsv1 config file.")
return p | 3089a258131dffe153060aeabe8e6a82f0196cca | 637,800 |
def guess_scheme(environ):
"""Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https'
"""
if environ.get("HTTPS") in ('yes','on','1'):
return 'https'
else:
return 'http' | 4e2451f231841df653af913f9242bd82134f9537 | 637,801 |
def get_twotuple_value(twotuple_tuple_or_list, key):
""" from a tuple like (('lS', 5.6), ('lT', 3.4000000000000004)), get the value from giving a key """
return list(filter(lambda el: el[0] == key, list(twotuple_tuple_or_list)))[0][1] | ee1f06853b30f4244e9ba31ce233285508d3b525 | 637,802 |
import base64
def authorization(pat_token, response_type):
"""
Creates the header for using api calls with PAT tokens
"""
authorization_base64_bytes = bytes(':'+pat_token, 'ascii')
authorization_base64_encode = base64.b64encode(authorization_base64_bytes)
authorization_base64_string = str(auth... | 30d4b3ee2016adb9578016ec98739e8f39c74c91 | 637,804 |
def read_int(data):
"""Reads a string and outputs a integer.
Args:
data: The string to be read in.
Raises:
ValueError: Raised if the input data is not of the correct format.
Returns:
An integer.
"""
return int(data) | 1a50f81d8da0d5f280e51f510c1d1839826abdc9 | 637,806 |
from pathlib import Path
def check_and_get_subdirectory(base_dir: Path, subdir_name: str) -> Path:
"""
Checks existance of base_dir, NON-existance of base_dir/subdir, and
returns the Path(base_dir / subdir).
Raises:
FileNotFoundError if the base_dir does not exist
OSError if the... | 1df2d2f03b4933a25f1bba7e1cb62f6ce998ccb3 | 637,809 |
import torch
def compute_i_th_moment(input, n):
"""
compute the i-th moment for every feature map in the batch of size 1
:param input: tensor
:param i: the moment to be computed
:return:
"""
mean = torch.mean(input)
eps = 1e-5
var = torch.var(input) + eps
std = torch.sqrt(var)
... | a74fe7561adf926897840c0389b5f3c490d8be68 | 637,810 |
def wsgihandler(environ, start_reponse):
"""WSGI application"""
start_reponse("200 OK", [('Content-Type','text/plain')])
#r = Request(environ)
return [('You asked to '+environ['REQUEST_METHOD']+' '+environ['PATH_INFO']).encode('utf-8'),
b' some more data',
b'\r\n'] | 586f37005e705cd12f4c7dcee1bc6255b9ca5ced | 637,811 |
def uncompress_indices(compressed):
"""Reverse of compress_indices.
"""
indices = []
for i in range(len(compressed) - 1):
indices.extend([i] * (compressed[i+1] - compressed[i]))
return indices | 8df26971dcc65dee4ce19c033040e940211c521b | 637,812 |
def create_graph_args(title="", x_label="", y_label="", *args, **kwargs):
"""
Create html string for classEquityChart.EquityChart initialization
:param title: string for graph title
:param x_label: string for graph x_label
:param y_label: string for graph y_label
Return a dict
"""
ti... | e8e3ca96eaf1eb30a91f658afc67c7524cbd75e9 | 637,813 |
import glob
import os
def get_prefix_files(file_dir, prefix):
"""
:param file_dir:
:param prefix: "best*"
:return:
"""
file_list = glob.glob(os.path.join(file_dir, prefix))
return file_list | 710550eba41df9434e7350d3ceb0277077cb1039 | 637,814 |
def _format_public_key(public_key):
"""PEM-format the public key."""
public_key = public_key.strip()
if not public_key.startswith("-----BEGIN PUBLIC KEY-----"):
public_key = "-----BEGIN PUBLIC KEY-----\n" + \
public_key + \
"\n-----END PUBLIC KEY-----"
... | 02889e62a19ab65af5de7dba88146bc4c4ad3ad1 | 637,815 |
def accuracy_metrics(act, exp):
"""Return precision and recall for a single query
Args:
act (set): actual result
exp (set): expected result
Returns:
float, float: precision and recall
"""
if act == exp:
# Consider the edge case: act=[] exp=[]
... | b88ca95bd4c1692f1b4215ba18b3a1b5b63a8bf0 | 637,816 |
import sys
def api_decode(value):
"""
Convert bytestrings from utf-8 to unicode.
Anything else is returned untouched.
Args:
value - The Python value to decode.
Returns:
The value decoded into unicode if it was a bytestring
"""
if sys.version_info[0] < 3:
if isinst... | 4cecc94be304534a518f497ccaf87ed682f145b3 | 637,817 |
def isgenerator(x):
"""
Returns `True` if the given value is sync or async generator coroutine.
Arguments:
x (mixed): value to check if it is an iterable.
Returns:
bool
"""
return any([
hasattr(x, '__next__'),
hasattr(x, '__anext__')
]) | 057b6d6231e5edac726bf5142d374720fc381885 | 637,818 |
def to_years_and_months(months):
"""
Convert a integer value into a string of years and months e.g.
27 would be represented as '2 Years 3 Months'
"""
whole_years = months // 12
remaining_months = months % 12
result = ''
if whole_years >= 1:
if whole_years == 1:
result... | ee151b5bedafda5c1e12edaf8069a9ba5e6825e9 | 637,819 |
def get_words_list():
"""Return a list of words from words file, with no newline characters."""
# get words from the file
lines = list()
with open("/usr/share/dict/words", "r") as file:
lines = file.readlines()
# removing newline characters from strings in words file
words_no_newline = [... | 4da235e1ded495d35290d49176056717c4bbd4f9 | 637,820 |
def crop_op(x, cropping, data_format='channels_first'):
"""
Center crop image
Args:
cropping is the substracted portion
"""
crop_t = cropping[0] // 2
crop_b = cropping[0] - crop_t
crop_l = cropping[1] // 2
crop_r = cropping[1] - crop_l
if data_format == 'channels_first':
... | 8992d7866c0cc5353f86b293d9eaafd736fe05f4 | 637,821 |
import operator
def sub_wo_carry(n1, n2):
"""
Substract two integer strings of same length without carry
>>> sub_wo_carry('9007', '1234')
'8873'
"""
l1 = [int(x)+10 for x in str(n1)]
l2 = [int(x) for x in str(n2)]
res1 = map(operator.sub, l1, l2)
res2 = [str(x)[-1] for x in res1]
... | f4247c27f6c0b5e93205cb528100ec3ec41378b4 | 637,822 |
def generate_sets_item_query(names, sets):
"""
Builds a query with a specified number of sets.
:param list names: The name of the workout item.
:param int sets: The number of sets to generate in the query.
:return: SQL compatible query as a string.
"""
master_tuple_list = []
for name in... | c7db77cd1ad81c5029ba1a71eaf35fa421033b32 | 637,825 |
def _format_servers_list_networks(networks):
"""Return a formatted string of a server's networks
:param server: a Server.networks field
:rtype: a string of formatted network addresses
"""
output = []
for (network, addresses) in networks.items():
if not addresses:
continue
... | 64abd24922d8df72bb1333409b1e3f6765914965 | 637,827 |
def has_arguments_left(argt):
""" is this tracker at the end?
"""
argv, pos = argt
return pos < len(argv) | 8be7622aec80a21745cbe0ffa7d8b559233d19ad | 637,828 |
def get_fname(dsrc,depTime,mforecast):
"""
Returns the name of the grib file on the NCDC server at the time requested
Args:
* 'dsrc' (string): type of source files for weather: either namanl or rap
* 'DT (string): date and time of the grib file requested
* 'mforecast' (string): ... | 8e3a25e5c5e23802c870cfe253b276a8fa0c5d2e | 637,829 |
import random
def make_bord_flag_data():
"""
境内外标识数据,网络支付、预付卡、银行卡收单必须填写,境内、外数量比例4:1
:return:
"""
return random.choice(["11" if num > 1 else "12" for num in range(10)]) | 12818c952cf7f65ed45a749780bd2d559375e7fe | 637,830 |
import os
def splitpath(path):
"""Recursively split a filepath into all directories and files."""
head, tail = os.path.split(path)
if tail == '':
return head,
elif head == '':
return tail,
else:
return splitpath(head) + (tail,) | 8bb07ff1d30ea9c497e06c776206a270bdf32262 | 637,832 |
import six
import os
def expand_envvars(d):
""" Recursively convert lookup that look like environment vars in a dict
This function things that environmental variables are values that begin
with '$' and are evaluated with ``os.path.expandvars``. No exception will
be raised if an environment variable is... | d760b6e5dbc7be8f39f6166ba2821f38bb0fad99 | 637,833 |
import multiprocessing as mp
import numpy as np
def parallelize(data, func):
"""
"""
# Import Libraries
# Function
if mp.cpu_count() > 2:
cores = mp.cpu_count()-1 # Runs in all cores except for one
else:
cores = 1 # Runs in a single core
data_split... | 834ca65e903cc21e21de32fb769b25f7964fc579 | 637,834 |
import json
def _hash_task(task):
""" Returns a unique hash for identify a task and its params """
params = task.get("params")
if params:
params = json.dumps(sorted(list(task["params"].items()), key=lambda x: x[0])) # pylint: disable=no-member
full = [str(task.get(x)) for x in ["path", "int... | f898bcc5ea95bf1fb79068043a7fc9348afd4372 | 637,836 |
def count(context, tag, needle):
"""
*musicpd.org, music database section:*
``count {TAG} {NEEDLE}``
Counts the number of songs and their total playtime in the db
matching ``TAG`` exactly.
"""
return [('songs', 0), ('playtime', 0)] | 89e6a6474ef6baf7d4c85a913c244de48c901c26 | 637,838 |
def make_error_response(err_msg="", err_code=-1, err_details={}):
"""
-1 means you cannot show to users
-2 means you can show to users
:param err_msg:
:param err_code:
:param err_details:
:return:
"""
return {
"status": False,
"error": {
"errCode": err_cod... | dbaff5e040583e94cdebf74da6ba2bc8b904756c | 637,839 |
import argparse
import os
def parse_command_line():
"""
Parses the command-line.
Returns
-------
args: namespace
Database with arguments parsed from the command-line.
"""
formatter_class = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(description='Plots the 2D vorticity,... | 4da9448a824ad7c4fa5a625f8442e10759655695 | 637,840 |
def dSigma_dCosT(eNu, cosT):
"""Return differential cross section in MeV^-2 as a function of the emission angle of the outgoing (detected) particle.
Input:
eNu: neutrino energy (MeV)
cosT: cosine of the angle between neutrino and outgoing (detected) particle
"""
# Energy dependence is ... | 7d3c8d18dfd54646ccbc2dfee360e006f4589ef4 | 637,841 |
def iter_board_vertices ():
"""
Generator: iter_board_vertices
------------------------------
iterates over all vertices on the board, starting from top left
of square (A, 1), returning them in board coordinates
"""
for i in range (8):
for j in range (9):
return (i, j) | 5ff4b9954b22533347c0e0d59460b2ce9f69e787 | 637,842 |
import random
def RandomSample(data, size):
"""Returns random sample of given size
"""
return data.ix[random.sample(data.index, size)] | 063267fc19cdab65b435cf30763cea17284a0eca | 637,843 |
import os
def create_vocab(data_dir):
"""
Args:
data_dir: atis/snips
Return:
Vocabulary list.
"""
vocab = set()
with open(os.path.join(data_dir, "train", 'seq.entities-full'), 'r', encoding='utf-8') as f:
for seq_concepts in f:
for token_concepts in seq_co... | 9afe70a88220a7c52655c1e6bdcffa13b67179af | 637,844 |
def JsonTextConvert(text):
"""Text2Json
Arguments:
text {str} -- webContent
Returns:
str -- jsonText
"""
text = text.encode('utf-8').decode('unicode_escape')
head, sep, tail = text.partition('(')
tail=tail.replace(")","")
return tail | 6a04d6b9fecf5baa6bc73257181a1ea68a7cdcee | 637,845 |
def check_horizontal_winner(board) -> bool:
"""checks for horizontal winner"""
for row in board:
if row[0] == row[1] == row[2] and row[0] is not None:
return True
return False | 5ca3bea6451e59c42dd032f472c155c4266fede6 | 637,846 |
def days_to_string(delay_days):
"""convert a number of days to a sensible string"""
DAYS_PER_MONTH = 30
if delay_days == 0:
delay_text = f"now"
elif delay_days < 1 / 24:
mins = delay_days * (24 * 60)
if mins == 1:
delay_text = f"in {mins:0.0f} minuite"
else:... | e9d3f0741f7118492973624c2cf797af0ebdf623 | 637,847 |
def _comment(s):
"""Returns a new string with "#" inserted before each line in 's'."""
if not s:
return "#"
res = "".join(["#" + line for line in s.splitlines(True)])
if s.endswith("\n"):
return res + "#"
return res | e00d0d83a4605c81a8c5a176bac773544b3ebab7 | 637,848 |
import random
import string
import os
def create_temp_folder(file_path):
"""
It creates a folder in the directory /tmp of the client/server.
This folder has the prefix "swid_". To this prefix a random generated String is appended to
prevent collisions of foldernames.
:param file_path: Path to the... | 8dfe48553932b20add514d4967ea35cbe1f88f56 | 637,849 |
def _fp_update(func):
"""
x[i] -> f(x[i-1])
"""
return lambda x: func(x) | a9abbfbb82422486a6b24e1294e1c12058fc2432 | 637,850 |
def flatten_string_list(arglist):
"""
Assemble a list of string, such as for a subprocess call.
Input should be a string or a list containing only
strings or similar lists.
Output will be a list containing only strings.
"""
if isinstance(arglist, ("".__class__, u"".__class__)):
retur... | c96d98163286ff9b56f18530523e463f5e833269 | 637,851 |
def extract_name(filepath):
"""Get item name and desc. from English.dat"""
data = {}
try:
for l in open(filepath, encoding="utf8"):
if l.startswith('Name'):
data['Name'] = l.split(' ', 1)[1]
if l.startswith('Description'):
data['Descr... | 46a4d9b575cc38bf66c74ab92c09a72a30cb28ac | 637,852 |
def extract(input_data: str) -> tuple:
"""take input data and return the appropriate data structure"""
rules = dict()
messages = list()
rules_input, messages_input = input_data.split('\n\n')[0:2]
for rule_input in rules_input.split('\n'):
rule_id, rule = rule_input.split(': ')
rules... | f646868d39f095777e86b63a3a4eb1ba913d5aca | 637,853 |
import math
def aika(etäisyys, nopeus):
"""
Laske annetun etäisyyden ajamiseen tarvitun ajan tunneissa ja minuuteissa.
"""
aika = etäisyys / nopeus
minuutit, tunnit = math.modf(aika)
return (int(tunnit), int(minuutit * 60)) | 135036cbeae6f691b25f815ed069cde33aea1f13 | 637,854 |
def content_function(obj):
"""Just return content"""
_, _, _, content = obj
return 'content', content | 7f11a6b86d81a1437b8643cd2461d44caeb2b4aa | 637,856 |
from typing import Tuple
def fixTridec(sPre:str, sMid:str) -> Tuple[str, str]:
"""Handles special case for tridec, tetradec, ..., as "tri" leaks into sPre and not sMid for detection"""
if sMid == "dec": # special case for tridec, tetradec and whatnot
for prefix in ["tri", "tetra", "penta", "hexa"]:
... | 8f56e7e09b6e2b368fa67f7d39eae6d270fe6ec5 | 637,858 |
import re
def validate_maintenance_window(window):
"""Validate PreferredMaintenanceWindow for DBInstance"""
days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
day_re = r'[A-Z]{1}[a-z]{2}'
hour = r'[01]?[0-9]|2[0-3]'
minute = r'[0-5][0-9]'
r = ("(?P<start_day>%s):(?P<start_hour>%s):(?P<s... | ced6140fa250e157aaa532f7c531abf64e41768e | 637,860 |
import ctypes
from typing import Optional
def _aligned_ptr_offset_in_object(obj: object, referent: object) -> Optional[int]:
"""Return the byte offset in the C representation of *obj* (an
arbitrary Python object) at which is found a naturally-aligned
pointer that points to *referent*. If *search_for*
... | accde7b5a999c62ad0a104d7dbdc7be46f109973 | 637,861 |
import pickle
def load_classifier(model_path, vec_path):
"""
Loads classifier from subfolder .
Parameters
----------
model_path: String
The path where the classifier is stored
vec_path: String
The path where the vectorizer is... | 103f7669b4e68ca836c605f1e0133317d02a6210 | 637,862 |
def has_vowels(input_string):
"""
helper for semantic split; useful to weed out non-words
"""
vowels = ["e", "a", "i", "o", "u", "y",
"E", "A", "I", "O", "U", "Y"]
char_set = set(input_string)
for v in vowels:
if v in char_set:
return True
return False | 148efe3ef54502dd393b1103cfdaaa4e5dd6f48a | 637,863 |
import html
import inspect
def _format_func_doc(func_name, func, full_doc=False, prop_set=None):
"""Format function signature."""
func_disp_name = func_name.replace("_", "\\_")
doc_lines = [f"### {func_disp_name}\n"]
if prop_set and func_name in prop_set:
doc_lines.append(f"{func_disp_name} [p... | 67ad37dffe561c2c46ad0b9d35bd2067a3eef99d | 637,864 |
def check_config_inputs(arg):
"""
Checks that all the data that should be numerical from that config
can be represented as a float.
Parameters
__________
arg: unknown
any argument can be passed.
Returns
_______
is_number: Boolean
Value is True if the arg is a number... | bcba3e7cc65a351d53ad2b6b07f73fb9eabcf299 | 637,865 |
def dim_check(dev_dist, std_min, std_max):
""" Boolean: does value fall within allowed range? """
return std_min <= dev_dist <= std_max | c692c22ce131081597fea05b39d75e4ae8b0fdc6 | 637,866 |
import torch
import operator
def summarize_profiler_info(prof: torch.autograd.profiler.profile) -> str:
"""
Summarizes the statistics in the specified profiler.
"""
# create sorted list of times per operator:
op2time = {}
for item in prof.key_averages():
op2time[item.key] = (
... | ab1cddab0f690b491012c9fa7fff9ee3c68a7c74 | 637,867 |
import os
def check_input(argument):
"""
checks if argument is a valid relative or absolute path
"""
if os.path.isdir(argument):
return argument
elif os.path.isdir(os.path.join(os.getcwd(), argument)):
return os.path.join(os.getcwd(), argument)
# If we got here, value is b... | 810749af3edd16875be8bf3a2ee00032868667e0 | 637,869 |
import os
def is_subpath(base, path, sep=os.path.sep):
"""
Check if the given path is a proper subpath of a base path.
"""
if path.startswith(base):
trailing = base[len(base) :]
return trailing == "" or trailing[0] == sep
return False | 0a615b46e3eecd8ac569e8a9d6e89f1aa218a7db | 637,870 |
def decode(string):
"""Decodes a String"""
dec_string = string \
.replace('&', '&') \
.replace('<', '<') \
.replace('>', '>')
return dec_string | fb930daa6761d78bfa6cde523a56ffe8be374da7 | 637,871 |
import glob
def _get_header_files(include_dirs):
"""Return a list of all extra headers to include in checks."""
headers = []
for path in include_dirs:
headers += glob.glob(path + "/**/*.h", recursive=True)
headers += glob.glob(path + "/**/*.hh", recursive=True)
headers += glob.glo... | 981652963a8bbf71beef10a31a24d02fafd71695 | 637,874 |
import os
def get_path(path, suffix_name, *args):
"""深度遍历获取所有后缀名为suffix_name的文件列表,可接收多个后缀名"""
# 获取当前目录下的所有文件
path_list=[]
path_name=[]
dir_list = os.listdir(path)
# print(dir_list)
for file in dir_list:
# 遍历所有文件
# print(os.path.abspath(path))
# print(file)
#... | 2f431d3b366ccf7928cc83bb793d28d7701339f4 | 637,875 |
def factorial(num):
""" Calculatte the factorial of a positive integer num
Assumption : num is not less than or equal to 0"""
if num == 1:
return num
else:
return num * factorial(num - 1) | b27137eac64277c90ae5fd7811a4cbadf08d11d9 | 637,876 |
def read_file(filename, delimiter=None, startline=0):
"""Reads a text file into a list of lists
Parameters
----------
filename : string
the file path to open
delimiter : string (optional)
the delimiter separating the column data (default to None for all white space)
startline : ... | 425daa6b70840a49277754e6e1422ffc73ef8b6d | 637,877 |
def penalize_short(genotype, weight=20):
"""fitness function handling short notes
Args:
genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome
weight (int, optional): Defaults at 20. Defines penalty/reward rate
Returns:
int: aggregate fi... | ffde1330c2e2e6aa562c8f1a8047c6d0e08cd441 | 637,878 |
def isfastq(f, verbose=False):
"""
Simple check for fastq file
"""
if 'fq' in f or 'fastq' in f:
return True
return False | e81d458023a851a19e6fe32725c8a5988c7a2eb2 | 637,879 |
def GroupPc2Pixel(pc_x, pc_y, scale, range):
"""Convert points in lidar coordinate system(axis rotated projection) to feature_map coordinate system."""
fx = (range - (0.707107 * (pc_x + pc_y))) * scale
fy = (range - (0.707107 * (pc_x - pc_y))) * scale
x = -1 if fx < 0 else int(fx)
y = -1 if fy < 0 e... | c3eb4df05b2a2b1eae2631b2d7b369a6d799baad | 637,880 |
import requests
from bs4 import BeautifulSoup
import random
def grab_a_paper(base_url):
"""
Given an arXiv base url, grab a random paper from that URL
"""
links = []
titles = []
papers = {} # a dictionary of links and titles
# Get webpage and initialize bs object
r = requests.get(bas... | bb86ad0e4862f32b2172402ee3395400e6a16939 | 637,881 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.