content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def filter_startswith(word, beginning=None):
"""Filter a word starting with specified string.
:param word (str): The word.
:param beginning (str, optional): The beginning string to check.
:rtype: bool: The resulting check.
"""
return word.lower().startswith(beginning) | a6da1a1bff5a27ac9e0c480a008450766ef3ce8d | 641,408 |
def na_usd(total_pln, rate_usd):
"""Calculate values in USD"""
return total_pln / rate_usd | dcee34a18808fd41c78cfa1cef8c2547ca540f78 | 641,409 |
from typing import Dict
def calculate_percentages(hour_production: Dict[str, float]) -> Dict[str, int]:
"""Calculate percentages from all values in the dictionary.
Returns dictionary with same keys but percentage values as integers.
Percentage total not always 100 due to rounding to integers
"""
... | f9ac41958c86d2226924c017a165f378531bde29 | 641,410 |
def format_data(data: list)-> dict:
"""将[config, test, test]格式改为{name, config, testcases格式}"""
config = data[0].get('config', {})
name = config.pop('name') if 'name' in config else None
testcases = [test.get('test') for test in data[1:]]
return dict(name=name, config=config, testcases=testcases) | 175f8c88c74ef61b830ee9ceef0c2e25a381fbb7 | 641,411 |
import os
import sys
def _callable_python() -> str:
"""Returns the string that is used to run Python in the terminal.
This is necessary for the warning to indicate the correct python executor,
regardless of the python version, of OS and virtual environment where
the vermon module is being used.
... | 1526066c5ec23bdd46615be30e8f883e78b35569 | 641,412 |
import math
def getnormcdf(x,lowertail=True):
"""
Get the normal CDF function. used to calculate p-value
"""
# ax=math.fabs(x);
#axv=math.erfc(x/(2**0.5))/2; # higher tail
if lowertail==False:
#return axv;
return math.erfc(x/(2**0.5))/2;
else:
#return 1-axv;
return math.erfc(-x/(2**0.5))... | 3ea224edf51eb5d6f790e8faebf2e5d331ff954f | 641,413 |
import inspect
def calling_source_location(skip=0):
"""Return source location of current call stack, skip specified levels (not include itself)."""
skip += 1 # This function itself is excluded.
skipped = 0
frame = inspect.currentframe()
while frame:
if skipped == skip:
return ... | 8955026dc1427e62ad1e14bcb615ef5e86b5be1f | 641,414 |
import copy
def get_leaders(election_data, party_leaders):
"""
This function takes one list of lists as an argument, with each list representing a party's election results, and one
list of tuples, with each tuple containing (party name, part leader). It makes a deep copy of the list of lists and adds
... | 8333e06ad72aacf18489576af0f49c28ba4b5661 | 641,415 |
def killwhitespace(string):
""" Merge consecutive spaces into one space. """
return " ".join(s.strip() for s in string.split()) | 53d45a99fa5ef42309fa4cc6bf74436b85c37b1b | 641,416 |
def find_sub(parent, text):
"""
Given an a ToC entry find an entry directly underneath it with the given
text. Here is the structure of a rendered table of contents with two levels
of depth:
.. code-block:: html
<div class="toctree-wrapper compound">
<ul>
... | bbe60ec9bd8ba28ef333332213db12010949937e | 641,417 |
def first_of(attr, match, it):
""" Return the first item in a set with an attribute that matches match """
if it is not None:
for i in it:
try:
if getattr(i, attr) == match:
return i
except: pass
return None | 9221897112feaed61602a1d16777dafbf42a1dd4 | 641,418 |
import subprocess
def create_disk_image(name, src_dir, out_path):
"""Creates a disk image (compressed, read-only image) from the specified directory contents."""
print('Creating disk image (%s)...' % out_path)
return subprocess.call([
'hdiutil', 'create',
'-volname', name,
'-layout', 'GPTSPUD'... | 5472c108c17d74663abcdf15c84cbfe051baaaa8 | 641,419 |
import os
import tempfile
def tmp_file_name(delete=True, directory=None, suffix=""):
"""Return a filename for a temporary file
Parameters
----------
delete : bool, optional
Flag whether the temporary file should be deleted [default: True]
directory : str, optional
Path to a director... | ee48b5b120f29659cbbb210a97ec76d0c61b910d | 641,420 |
import re
def clean_filename(unclean_name: str) -> str:
"""
Return a valid filename where any character that is not
a letter, number, dash, underscore, space, or period
is replaced with an underscore
"""
return re.sub(r'[^\w\-_. ]', '_', unclean_name) | 7f807cf471befa6194df8ee508f130aae9b7548d | 641,421 |
def convert_to_string(input_value):
"""
:param input_value:
:return:
"""
return input_value.__str__() | 8851091b53b131b17dacb36737a2a0873050e0fc | 641,423 |
import torch
def log_of_gaussian_pdf(x, mean, sigma, reduction='mean'):
"""
x, mean, sigma: [B, D]
Note that we omitted the constant factor -0.5 * log(2 * pi)
"""
rop = - torch.sum(torch.log(sigma) + (x - mean) * (x - mean) / (2 * sigma * sigma), dim=-1)
if reduction == 'mean':
retur... | 5d983e8e68fe065ae4f331f0ed579ca8281a65ea | 641,424 |
def string_to_max_list(s):
"""Given an input string, convert it to a descendant list of numbers
from the length of the string down to 0"""
out_list = list(range(len(s) - 1, -1, -1))
return out_list | dd4d62e64dca027f8acd6ac551ed23b328d68288 | 641,425 |
def eval(x,y,z):
"""
Performs evaluations.
@ In, x, float, scalar
@ In, y, float, scalar
@ In, z, float, scalar
@ Out, list(float), input values and output value
"""
dat=[]
c = 0
for i in [0.3,0.5,0.7,1.0]:
for j in [1.3,1.5,1.7,2.0]:
c+=1
dat.append([c,i,j,x,y,z,(i-x)*(j-y... | e706ae11fc86d6bea005cbecc9f9ce5f7743eca7 | 641,426 |
def gnome_sort(unsorted):
"""Pure implementation of the gnome sort algorithm in Python."""
if len(unsorted) <= 1:
return unsorted
i = 1
while i < len(unsorted):
if unsorted[i - 1] <= unsorted[i]:
i += 1
else:
unsorted[i - 1], unsorted[i] = unsorted[i], u... | aea183a1456050421b93d6afba149b082cf646e9 | 641,427 |
import re
import logging
def extract_phone_number(resume_segments):
"""
Find first phone number in the string_to_search
:param resume_segments: Dictionary containing segmented resume data
:type resume_segments: Dictionary
:return: A string containing the first phone number, or None... | 7da814e157a59ff93f43133d175083cab7822fbf | 641,428 |
def descendants_query(node_id, node_label, edge_label="edge"):
"""Generate Cypher query finding descendant nodes starting at 'node_id'."""
return (
"MATCH path=(n:{} {{id: '{}'}})-[:{}*1..]->(m:{})\n".format(
node_label, node_id, edge_label, node_label) +
"RETURN m.id AS descendant, ... | 88911b937c7d6fb65ebb07a566b0ad3d1fe60720 | 641,429 |
def frac_sec(ms: int):
"""time elapsed with a second"""
return ms / 1e6 | cbfa85750d340c1e55e62869065fe8a79a2375b3 | 641,430 |
def mutate_kmers(seq, k_dict, k_count, k, positions, mutations):
"""
Deprecated due to low speed
Compute the k-mer counts based on mutations.
:param seq: Original Sequence to be mutated.
:param k_dict: Dictionary with kmers.
:param k_count: Array with k-mer counts in the original seq.
:para... | 1ce3d08c55b695b21bacf2a73e4828651c960c94 | 641,431 |
from pathlib import Path
def test_page():
"""Reading sample html page."""
html_path = f"{Path(__file__).parent}/data/page.html"
with open(html_path, encoding="utf-8") as html_file:
test_html = html_file.read()
return test_html | 56becb76be4a00b906ae6576f3e39a32ba23e7ab | 641,432 |
def transformed_classification_data(data_classification_balanced, transformer_classification):
"""Transformed data_classification_balanced test data."""
X = data_classification_balanced[0]
y = data_classification_balanced[1]
X = X.drop(["Date"], axis=1)
transformer_classification.fit(X)
transfor... | 6615ebdf5f431216373f2698f5747782a2ddd3cb | 641,433 |
def where_math(condition, x, y):
""" scalar version of numpy.where """
if condition:
return x
else:
return y | 7e325dda1b38265fcf121e75473f97a4dd46f5fa | 641,434 |
from typing import Dict
def create_example_from_attributes(attributes: dict) -> Dict[str, str]:
"""
Creates an example usage - part of YAML document basing on the schema
:param attributes:
:return:
"""
as_dict = {}
for key, attribute in attributes.items():
as_dict[key] = attribu... | 05e422e6809911386da2c7a3cf2c43a089c13de9 | 641,436 |
from dateutil.tz import tzutc
def tz():
"""Return a timezone."""
return tzutc() | 6793f81419cc2eeaa6a4f6c72a3298f9b376c082 | 641,437 |
def mocked_elasticsearch(mocked_elasticsearch_module_patcher):
"""
Fixture that resets all of the patched ElasticSearch API functions
"""
for mock in mocked_elasticsearch_module_patcher.patcher_mocks:
mock.reset_mock()
return mocked_elasticsearch_module_patcher | 0dabc985d1dbcd7eda3d365447c1241f54143644 | 641,438 |
import numpy
def compute_mean_std(cifar100_dataset):
"""compute the mean and std of cifar100 dataset
Args:
cifar100_training_dataset or cifar100_test_dataset
witch derived from class torch.utils.data
Returns:
a tuple contains mean, std value of entire dataset
"""
data... | e172b9ab1f6732a883f26e640710262bfaf01840 | 641,439 |
def year(request):
"""Добавляет переменную с текущим годом."""
return {
'year': '{% now "Y" %}',
} | 4b01318ff029afb9133863153bb7556c6273d29e | 641,441 |
def split_data(x, y, percentage_training, percentage_test):
"""
Parameters
----------------------------
x: numpy matrix
y: numpy array
percentage_test: float
percentage of data to be set for test set
Return
-------------------
X_train, X_valid, X_test, y_train, y_valid... | 1b3290e4b221a2902ce02cadef65c97dc5c5bd14 | 641,442 |
def avg_ellipsis_length(message):
"""Метрика многоточий
:param message: сообщение
:return: средняя длина многоточия
"""
result = 0
length = 0
count_sequence = 0
duration = 1
for i in range(0, len(message)):
if i < len(message) - 1 and message[i] == "." and message[i + 1] == ... | 7f4d8760d4703c5e6abaf3bcbaac5302a6c24452 | 641,443 |
import os
def read_local_files(*file_paths: str) -> str:
"""
Reads one or more text files and returns them joined together.
A title is automatically created based on the file name.
:param file_paths: list of files to aggregate
"""
def _read_single_file(file_path):
with open(file_pa... | 5641302ef78a6e523b9e2886169b11f2b7151c30 | 641,444 |
import pkg_resources
def discover_controllers(entry_point='steppy.controllers'):
"""Discover controllers registered under given entry point
In:
- ``entry_point`` - The entry point under which to register controllers (default: "steppy.controllers")
Return:
- A dictionary {controller name: contr... | d0a225cd43416899bd948af8049c8528bea2c523 | 641,445 |
def parseJarfiles(classPath):
"""Return a list which contains every jar files"""
retL = []
retL = classPath.split(':')
return retL | 38d23508304cce06d6cc628d01ca77e5c333eccf | 641,446 |
def mass_match(mass1, mass2, parameters):
"""Assess peak match based on mz values and Da mz error"""
if mass1 - parameters.mz_da_error <= mass2 <= mass1 + parameters.mz_da_error:
return True
else:
return False | d810cd0c9cded34a024598de2a7e138ab9c6e403 | 641,447 |
async def sub_command():
"""This is the upper command's sub command"""
return 'This is the sub-command.' | 539db0c82364cf69dbd600b4bd16d7ec50697b1e | 641,449 |
import time
from datetime import datetime
def validateIsmatchDateFormat(date: str, dateFormat: str, fieldName: str, readableFormat: str = ''):
"""Validate date format from string"""
try:
# convert string year.moth to timestamp
sinceTimeStamp = time.mktime(datetime.strptime(date, dateFormat).ti... | 6eed7b6b14cf1a99264763e9725d6a1f74f448a6 | 641,450 |
def __checkInitdbParams(param):
"""
function : Check parameter for initdb
-D, --pgdata : this has been specified in configuration file
-W, --pwprompt: this will block the script
--pwfile: it is not safe to read password from file
-A, --auth,--auth-local,--auth-host: They will be ... | 1f8cc14834913f9c7816001673d00935e1983bcb | 641,451 |
def damage_score(damageDealt):
"""
damage_score
: type damageDealt: float
: rtype damage_score: int
"""
if damageDealt >= 349.45:
damage_score = 100
elif damageDealt >= 300.54:
damage_score = 95
elif damageDealt >= 251.62:
damage_score = 90
elif damageDealt >= 216.7:
damage_score = 85
elif damageDe... | 7add6f88869c7ddd78bdbb34a3dfe757fa1346bc | 641,452 |
import collections
def reorder_props(props):
"""
If "children" is in props, then move it to the
front to respect dash convention
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
dict
Dictionary with {propName: pr... | 13911471c943187f6f022fcfbd22d9e4ad3a66af | 641,453 |
def ql(fmp, fs, f0p):
"""Calculate qL
qL = ((fmp - fs) / (fmp - f0p)) * (f0p / fs)
:param fmp: Fm'
:param fs: Fs
:param f0p: F0'
:returns: qL (float)
"""
return ((fmp - fs) / (fmp - f0p)) * (f0p / fs) | ea47510499a3d678b4d8cb6eae9455d26d4bd333 | 641,455 |
def get_xtick_step(max_xcount):
""" Получить шаг подписей графика тэгов
Аргументы:
max_xcount (numeric) - максимальное количество упоминаний тэга, которое
наблюдается в базе.
"""
if max_xcount < 10:
return 1
else:
return int(max_xcount / 10) | f5c33f009e22a0f28148e03358c5e0358636f9a6 | 641,456 |
import re
def _update_chap_security(module, array, answer=False):
"""Change CHAP usernames and passwords"""
pattern = re.compile("[^ ]{12,255}")
chap = array.get_host(module.params["name"], chap=True)
if module.params["host_user"]:
if module.params["host_password"] == "clear":
if c... | 81aac850d2b160c8d07ff5c081bd1c3b6b7cd195 | 641,457 |
def tostr(lst):
"""Makes all values of a list into strings"""
return [str(i) for i in list(lst)] | 6cfb1f11fb446d8c26e657624516127042d4098a | 641,458 |
def api_endpoint():
"""Api endpoint that can be passed as a parameter to any test
"""
return "http://localhost:5000/api/" | 534f9bb31ed35f4a6e17ca1ca78a68a1ff617f03 | 641,459 |
from typing import Tuple
def extract_entitlement(entitlement: str, text: str) -> Tuple[str, str, str, str]:
"""
Extracts entitlement components from an entitlement string
Args:
entitlement: The entitlement itself
text: The actual reply text
Returns:
Entitlement components
... | 8ecee278f03535f0a3f6426cd400d76c08f8e544 | 641,460 |
def scriptSource(*args, **kwargs):
"""
Same as scriptReadFile().
"""
return None | 4f6fadd8c42b1d861b01feebdfa72551c76cc366 | 641,461 |
def extract_number_of_pages(soup):
"""
Extract the number of result pages from a result page.
"""
pager_span = soup.find('span', class_='smallPager')
return int(pager_span.string.split()[-1]) | b066d25154cd9b3abd972a1a6da0b1d73212db54 | 641,462 |
from typing import List
def date_filter_string(column: str, comp_type: int,
thresholds: List[str]):
""" Generate string for date-based filters
Generates a filter for filtering for specific rows based on different
date comparisons.
Args:
column: Column to filter on
... | ff565d93946894e5f3c6e89913a7ada7a24b84cd | 641,463 |
import torch
def ravel_index(idx, dims) -> torch.Tensor:
"""
Computes the linear index in an array of shape dims.
It performs the reverse functionality of unravel_index
Args:
idx: A LongTensor of shape (N, 3). Each row corresponds to indices into an
array of dimensions dims.
dims... | ff7319f8097ec3c4c6be303dc3415f0408210f71 | 641,464 |
def _is_password_valid(pw):
"""Returns `true` if password is strong enough for Firebase Auth."""
return len(pw) >= 6 | fbaff0d6b2866de14ddd7719cd369ea589f02e84 | 641,465 |
import os
def switch_workdir(path):
""" Check if it makes sense to change directory """
if path is None:
return False
if path == "":
return False
if path == "./":
return False
if path == ".":
return False
assert os.path.exists(path), f"Cannot change directo... | b87dedaa372957d91fd26b0efe4a8a6624194d92 | 641,466 |
def get_snapping_pos_line_chart_vertical(data_objects, line_pos):
"""
Calculates the nearest pos of and objects from a line chart with an vertical line.
:param data_objects: The nodes of the data objects in the chart.
:type data_objects: dict[str, PolyLineNode]
:param line_pos: The necessary positi... | bb0db8aa9280d21119fd07d85b3046453fa4ffda | 641,467 |
def encode_augmentation_type(data):
""" Encode splits as intetgers and return the array. """
lookup = {'none': 0, 'inplace': 1, 'full': 2}
return [lookup[datum['augmentation_type']] for datum in data] | a18d25cef3b951bd6c1609e148682cd9b6e9778c | 641,468 |
import os
def combine_pitch_lost_txt(pitch_5cols_noloss_txt_path, pitch5cols_loss_txt_path):
"""
预处理输入到rolling_prediction中的文件,前3行采用的是pitch_5cols_loss的,然后后面的采用的是no_loss数据
但在第5列添加对应loss帧的标志位,返回处理后数据的路径
Args:
pitch_5cols_noloss_txt_path: noloss_data的路径,用于获取no_loss数据
pitch5cols_loss_txt_pa... | 2444c4e54f6e105a901d22e032c28f5ffa86e09c | 641,469 |
import os
def get_filename_with_extension(pathname: str) -> str:
"""Get the filename from the pathname with the file extension.
Parameters
----------
pathname : string
The pathname which the filename will be extracted.
Returns
-------
filename : string
The filename with t... | d4fb23fd3bd7df8c9b731c0394415fa18ba4934e | 641,470 |
import json
def parse_json_file(distribution_json_file):
"""
Parse a json distribution file for a distribution id.
Look for node of type 'dynamicPluginConfiguration' that contains the attribute id
Note: The file should contains only one distribution.
:param distribution_json_file: filepath
:r... | cbd3a29ca7e1370772b1699a598f4ff53e6bc12d | 641,472 |
def conv_continuity_constraint(output, sobel_filter, use_tb=True):
"""y
div(sigma) = -f
Args:
"""
sigma1_x1 = sobel_filter.grad_h(output[:, [1]])
sigma2_x2 = sobel_filter.grad_v(output[:, [2]])
# leave the top and bottom row free, since sigma2_x2 is almost 0,
# don't want to enforce si... | 76942a384578b4c7bf0ba757dabc79ddd213e66a | 641,473 |
def ensure_ref_position_is_valid(ref_position, num_alts, param_title):
"""
Ensures that `ref_position` is None or an integer that is in the interval
`[0, num_alts - 1]`. If None, ensures that intercepts are not the
parameters being estimated. Raises a helpful ValueError if otherwise.
Parameters
... | ac50cbe94ae2874f03c568bec7206d7cf05d85dc | 641,474 |
def _recursion_merge_sort2(l1, l2, tmp):
""" 递归合并排序
递归对2个列表进行操作,每次取各列表第一个元素插入到传递的中间列表中 """
if len(l1) == 0 or len(l2) == 0:
tmp.extend(l1)
tmp.extend(l2)
return tmp
else:
if l1[0] < l2[0]:
tmp.append(l1[0])
del l1[0]
else:
... | 518e2db255d5fc9f3edf81f76da8c6f7c627f3a9 | 641,475 |
import os
from datetime import datetime
def basic_args():
"""The basic args which are guaranteed to be available."""
return {
"env": os.environ,
"now": datetime.now(),
"utcnow": datetime.utcnow(),
} | efb24be8cae6f9102fba4da21d342155695d2412 | 641,476 |
import os
def build_subprocess_cmd(csv_path, train_folder):
"""Builds the command used to call a subprocess for model training.
Other parameters like split and num_epochs are not passed
since they are the default in the generated code.
"""
csv_path_join = os.path.join('..', csv_path)
return... | 06084d7fc973b85b1a8c74d68ece2549a97fca7f | 641,477 |
def _actionNumber(action, numberProjects):
""""Function to obtain action position in qTable"""
studentNumber = action[0]
projectNumber = action[1]
return (studentNumber * numberProjects) + projectNumber | 021b0d52b5d657ae9a53861d8c9547c358e71841 | 641,478 |
import math
import numpy
def inertialToVNC(position, velocity):
""" Convert position and corresponding velocity in an inertial frame of reference (TEME, ECI or similar) to
Velocity-Normal-Co-normal frame.\n
Parameters
----------
@param position, velcity - dimensional position and velocity in the ... | 2342e007f65b6463f3a66efe3a23b39f4c1c131b | 641,479 |
from typing import List
import requests
import json
def get_user_repos(user_name: str) -> List:
"""This method returns list of repos that belongs to user
Inputs: string
Output: List
"""
link: str = "https://api.github.com/users/" + user_name + "/repos"
user_data = requests.get(link)
reposi... | e3387cae3c305993615c33c5a2ffbec6e729ac35 | 641,480 |
def _suggest_target_postcodes(system, threshold=None):
"""Sort postcodes by population density (descending)
- if considering threshold, filter out any with capacity above threshold
"""
postcodes = system.postcode_sectors.values()
total_postcodes = len(postcodes)
if threshold is not None:
... | eb6a6e2740df6c7adec9cf1eae30fa969d6a1be8 | 641,481 |
import os
def transform_path(path: str) -> str:
"""Transform tests/test_foo.py to monkeytype.foo"""
path = 'monkeytype/' + path[len('tests/'):]
*basepath, file_name = path.split('/')
basename, _ext = os.path.splitext(file_name[len('test_'):])
return '.'.join(basepath + [basename]) | c31215fbf735fc216de509b39f9a11075f79cb39 | 641,483 |
def parse_size(root):
"""Parse the width and height of the image out of the root node.
Args:
----
root: xml.etree.ElementTree.Element
Output:
------
width: str
height str
"""
size_node = root.find('size')
width = size_node.find('width').text
height = size_n... | 40ccfc56a4f1a7c8135104a2bebeb0c82fd939a2 | 641,484 |
import pkg_resources
def getResourcePath(name):
"""
Return the path to a resource
"""
return pkg_resources.resource_filename(__name__, "data/%s" % name) | 73242fe1c37bad0919177b2f27d5ffe130737939 | 641,485 |
import requests
def is_darksky_quota_error(err):
"""Return Tre if input 'err' is a DarkSky quota error, else False"""
tf = False
if isinstance(err, requests.exceptions.HTTPError):
resp = err.response
if resp.status_code == 403 and 'darksky' in resp.url:
tf = True
return tf | 5c6689580370b765d6fdfac884691dccac6768ac | 641,486 |
def colors(graph, node_type_attr='type'):
"""
Utility function that generates colors for node
types for drawing graph in Ipython Notebook.
:param graph: networkx.Graph
:returns: Dict. Nodes as keys, colors as values.
"""
colors_dict = {}
colors = []
counter = 1
for node, attrs i... | cee009fa85636f89b5d743b9da2fde334717ce03 | 641,487 |
from random import randint
def cpf_gerar(a=1):
"""
Author: Wallace Wictchen
Gera CPFs válidos 'ilimitados'
:param a: (amount) quantidade de CPF a serem gerados
:return: Números de CPFs com a formatação pronta
"""
cpf = list()
for qua in range(a):
while True:
gerar =... | a0922dfc6ae0e5f81673d388a6ea76023e0f999c | 641,488 |
def constraint(x):
""" Evaluate the constraint here. """
ret1 = x[2] >= 13.0 and x[1] > 11.0
ret2 = x[2] <= 13.0 and x[1] < 90.0
return ret1 or ret2 | 8056bb135918fd1cab5eeb0268cc2437da64cda9 | 641,489 |
def create_weighted_list(peoplex, no_showx):
"""
Function to create a list using weights (avoiding no shows)
:param peoplex:
:param no_showx:
:return:
"""
jc_listx = []
for name in peoplex:
if peoplex[name] == 0:
continue
if peoplex[name] in no_showx:
... | 6edbfb4d68f854bd7881854be54081da89a405a8 | 641,490 |
import marshal
def loadpyc(filename):
""" Load the code from a byte compiled file filename and return it
as code object.
"""
f = open(filename,'rb')
f.read(8) # skip header (id check omitted)
return marshal.load(f) | af3ff96b17b58d576f61dfb5096a3cca4dbf7df7 | 641,491 |
from typing import Callable
def get_lr_schedule_rnd(
rnd: int, lr_initial: float, lr_decay: float
) -> Callable[[int], float]:
"""Return a schedule which decays the learning rate after each round."""
lr_rnd = lr_initial * lr_decay ** rnd
# pylint: disable-msg=unused-argument
def lr_schedule(epoch... | cd44feb673bb51f4c32276dd302d776fa17407e8 | 641,492 |
def thisorthat(this, that):
"""
If this is None takes that otherwise takes this.
:param this:
:param that:
:return:
"""
if this is None:
return that
else:
return this | 25e9fcc024d93335f296284bcf0822a9075f13e0 | 641,493 |
import os
def get_img_list(_dir, ext='.png'):
""" Retrieves the list of images from the specified directory. Specify the
extension(image type) with ext parameter.
"""
images = []
for _file in os.listdir(_dir):
if _file.endswith(ext):
images.append(_file)
return images | 786334386a58576439ca8be06f13974721965827 | 641,494 |
def cli_echo(argv: list):
""" Help message here """
message = f"argv: {argv}"
return message | c13dc0c2a19b563af0cfc5c0d374b847ac73bb3f | 641,496 |
def errfun_sae(x,y):
"""
Sum of absolute errors
"""
return sum(abs(x-y)) | 15dd69b81a2781e5f815e0db5fdfdf808b9dfb1e | 641,497 |
import argparse
def get_args():
"""get args"""
parser = argparse.ArgumentParser(description='Argparse Python script')
parser.add_argument('arg', help='File/string to count', type=str)
parser.add_argument('-c', '--charsort', help='Sort by character',
dest='charsort', action='sto... | f87c1031f3fc1cce66120d2d8f0d0eebe740ba38 | 641,498 |
import textwrap
def wrap_str(_str, max_len):
""" Textwrap _str to provided max length """
len_str = len(_str)
if len_str > max_len and len_str > 3:
_str = textwrap.wrap(_str, max_len - 3)[0] + '...'
return _str | f29009e4ab7a814771ca3b4b9379299a1bc87589 | 641,500 |
from unittest.mock import call
def get_available_supply():
"""
Returns how many rai are in the public supply
:returns: dict with `available` key
:rtype: dict
"""
action = 'available_supply'
return call(action) | 365043e4c3066a1d5ac2b4971ec818f80c3ee899 | 641,501 |
import os
def __locate_executable(candidate_paths):
"""Find executable among a set of paths.
Args:
candidate_paths (list of str): list of locations in which to
look for an executable file.
Returns:
str, first entry of candidate_paths that is an executable
file, or... | cfeb227bd00e687da83f7f6ab31490b04642d3f5 | 641,502 |
def _calculate_value_in_range(min_val, max_val, percentage):
"""Get the value within a range based on percentage.
Example:
A percentage 0.0 maps to min_val
A percentage of 1.0 maps to max_val
"""
value_range = max_val - min_val
return min_val + int(percentage * value_range) | 5b2104ba0db7bb168b014fb6214d1e495ce785d8 | 641,503 |
def get_indexes_of_split(split, Y_size, Z_size):
"""
get all the writing offset in one split
(j,i) -> (index_start,index_end)
"""
index_list = []
for i in range(0, split.split_x):
for j in range(0, split.split_z):
# calculate the indexes (in bytes) of each tile, add all the ... | 6182abb6d32067069fbf2b567f003027a95643da | 641,504 |
def set_cid(dataset, char_vocab):
"""
set cid field for the records in the dataset
:param dataset: dataset
:param char_vocab: vocabulary of character
:return:
"""
n_records = len(dataset)
cids = []
for i in range(n_records):
words = dataset[i]['words']
cids = []
... | 843c03b68d4e48c197ccd2a58787c360f983e156 | 641,505 |
def fmt_item_ipv4(entry):
"""Format an IPv4 range with lo and hi addresses in decimal form."""
return "%d,%d,%s\n"%(entry[0], entry[1], entry[2]) | f4eddcf377c769fa7943b725acdc713fe5818f57 | 641,506 |
def p_time_unit(units):
"""Returns human readable version of time units string."""
# NB: other time units are supported by resqml
if units.lower() in ['s', 'sec', 'secs', 'second', 'seconds']: return 'seconds'
if units.lower() in ['ms', 'msec', 'millisecs', 'millisecond', 'milliseconds']: return 'millisec... | d4c4a3bf4743fb3fa1c639f55a3e2cc950447641 | 641,507 |
import torch
def loss_loglik(y_mean, y_logvar, x):
"""
Args:
y_mean of shape (batch_size, 1, 28, 28): Predictive mean of the VAE reconstruction of x.
y_logvar of shape (batch_size, 1, 28, 28): Predictive log-variance of the VAE reconstruction of x.
x of shape (batch_size, 1, 28, 28): Trainin... | 227fdc0d65bfed8c375f1baf506d1fc15bc16615 | 641,508 |
def find_shift(p, row, test_col):
"""Find how many cells to shift up when encountering possible merged cells."""
max_shift = 4
for shift in range(max_shift):
test_val = p[test_col + str(row - shift)].value
# If None,the cells were merged vertically; look up.
if test_val is not None:... | 8a366655581fcb4b533ded920eb121444d4af23d | 641,509 |
def selective_title(str):
"""
Convert string to Title Case except for key initialisms
Splits input string by space character, applies Title Case to each element
except for ["NHS", "PCN", "CCG", "BNF", "std"], then
joins elements back together with space
Parameters
----------
str : str
... | 742f2a929353424b74199fa5c3ac0a55276b811c | 641,510 |
def get_acc(vals):
"""
return the accuracy given binary scores
"""
acc = (sum(vals) / len(vals)) * 100
return acc | 8e40bc677ab7c52a5e72e4e03817d1c6ab44c857 | 641,511 |
def CLSID(MyClass):
"""Return CLSID of MyClass as string"""
return str(MyClass._reg_clsid_) | 4651515afc9863d77c770256a0cf3f4d0fe9cc58 | 641,512 |
import re
def spec_add_spaces(text: str) -> str:
"""Add spaces around / and # in `text`. \n (code from `fastai`)"""
return re.sub(r"([/#\n])", r" \1 ", text) | 3ca3534b91a877636ca463493c0ba7b5061fb19d | 641,513 |
def bubble_sort(lst: list) -> list:
"""Sort a list in ascending order. The original list is mutated and
returned. The sort is stable.
Design idea: Swap adjacent out-of-order elements until the list is sorted.
Complexity: O(n^2) time, O(1) space. Stable and in-place.
See quicksort, merge sort and ... | 0acc4561a7c1cbdd04ff9e3f054533b5a3e1aea4 | 641,514 |
def datetime2hr(dtime):
""" Calculate hours of day from datetime
Parameters
----------
dtime : (dt.datetime)
Universal time as a timestamp
Returns
-------
uth : (float)
Hours of day, includes fractional hours
"""
uth = dtime.hour + dtime.minute / 60.0 \
+ ... | f1434eff301ad953760cbc333b248e6c4e09afe6 | 641,515 |
def format_contexts(contexts, positions, grads=None):
"""
:param contexts:
:param positions:
:param grads:
:return:
"""
class color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\03... | a89b6b7be720aaa0d5f89da9eaddeb869b351fee | 641,516 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.