content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def sort_fractions_by_denominator(fractions):
"""
The function takes a list of `Fraction` objects as its argument.
It returns a list of the fractions sorted by its denominator.
Use a lambda expression for the key function.
For example,
INPUT: [1/2, 3/4, 2/3]
OUTPUT: [3/4, 2/3, 1/2]
"""
... | 45f9dac8e4c55a8a9edc1839e9e870c501beff82 | 649,129 |
def clone_instance(instance, fieldnames=None):
"""
returns a copy of the passed instance.
.. warning: All fields are copied, even primary key
:param instance: :py:class:`django.db.models.Model` instance
:return: :py:class:`django.db.models.Model` instance
"""
if fieldnames is None... | fbbe259cc9408d27a607e477e8357d413c5add82 | 649,130 |
import requests
import time
def get_mac_address_vendor(mac_address: str, retries: int = 10) -> str:
""" """
# Can also use https://macvendors.co/api/{mac_address} for a richer payload
prefix = ''.join(mac_address.split(':')[0:3])
response = requests.get(f'https://macvendors.com/query/{prefix}')
... | d683815e371469722068940e229d03f077cf440f | 649,131 |
import argparse
def args_parser():
"""
Parsing arguments passed to script
Returns
-------
args:
Input arguments to the script
"""
print('Parsing in progress')
parser = argparse.ArgumentParser()
parser.add_argument('survey', type=str,
help='Options: eco/resolvea/r... | 74398a54ba603bfd9684ed97d38553e4d57b3a5f | 649,132 |
def fixture_env_name() -> str:
"""Get the name of a testing environment"""
return "D_marshmallow" | a9e7be55f21b5cec725fd01eeb636b18e6a7b713 | 649,133 |
def get_optimizer(dataset_name):
"""
Arguments
---------
dataset_name (str): name of dataset being trained
Returns
-------
optimizer (dict): parameters defining the optimizer to use during
training.
"""
if "noscope" in dataset_name:
# We use... | 51b5c8f745f093868c30b5ce0249195ef0d11209 | 649,134 |
def get_training_status(api, cfg, job_id, model_name):
"""
Gets the status of the given training job id
Arguments :
api : object, API object to access CloudML Engine
cfg : dict, Configurations from yaml file
job_id : string, Job ID of the training job
model_name : string, Na... | e985fd66115cf86c76172557515e53bb8ab9d10e | 649,135 |
def TriFusion(l):
"""
Implementation of the "tri fusion" algorithm
"""
n = len(l)
if n<=1: # Si vide ou un seul éléments, alors déjà trié
return l
else:
sl = []
A = l[:n//2]
B = l[n//2:]
A = TriFusion(A)
B = TriFusion(B)
while ... | fca6cde86ad528d9527b77ec97e257ee97953374 | 649,137 |
def grazing(vs, eaten, zooplankton):
"""Zooplankton grows by amount digested, eaten decreases by amount grazed"""
return {eaten: - vs.grazing[eaten], zooplankton: vs.grazing[eaten]} | 9e955c3cc16e00f8fffd9ef210093ecd82ac11df | 649,138 |
def aa_10(x, ind):
"""Function A with order 1,0"""
if ind[0] == 0 and ind[1] == 0:
return 2 * (x[:, 0:1] + x[:, 1:2])
if ind[0] == 0 and ind[1] == 1:
return -2 * x[:, 0:1]
if ind[0] == 1 and ind[1] == 0:
return -2 * x[:, 0:1]
if ind[0] == 1 and ind[1] == 1:
return 2 *... | 6047f14df33705519c01e99d047892d88690eafb | 649,139 |
def normalize(lines: str) -> str:
""" Remove trailing whitespace from each line,
keeping all line breaks except the last."""
return '\n'.join(line.rstrip() for line in lines.strip().splitlines()) | d90c7f2ce3ac4cbe2c3318df260a88d6ffdd0075 | 649,140 |
def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val | d0ad2209533abf9b83221359922c2e0fc4fa73e5 | 649,142 |
from typing import Dict
from typing import Tuple
def dense_dict(dictionary: Dict, removables: Tuple = (None,)) -> Dict:
"""Return a dictionary ignoring keys with None values, recursively."""
return {
k: dense_dict(v) if isinstance(v, dict) else v
for k, v in dictionary.items()
if v not... | 10c160d1d2acf364ffce8e4da8b83e099a8de450 | 649,143 |
def combine_lines(components, element_list, background):
"""
Combine results for different lines of the same element.
And also add pileup, userpeak, background, compton and elastic.
Parameters
----------
components : dict
output results from lmfit
element_list : list
list of... | 6c2498eb0886e096cf6ddf0a5e990936ea8dade6 | 649,144 |
def alg_int(u, v):
"""
Given two slopes, compute their algebraic intersection number.
"""
a, b = u
c, d = v
return a*d - b*c | 7d75b0a2464f3e28c31a43b9ff9142386082fe82 | 649,146 |
from typing import Any
def mock_create_cache_directories(self: Any, **kwargs: Any) -> int:
"""Mock create cache directories.
Don't actually need the directories created in testing
"""
return 1 | 5040ddb91652e2e5f3ded82ac8242fab9a58c248 | 649,147 |
def current(widget):
"""Decorator to run callable on the current thread.
Useful for quickly changing with `tkthread.main`"""
def wrapped(func):
func()
return func
return wrapped | 3a798a4c50dd6c1786d7f171cdf595f3b38a6e2b | 649,148 |
import os
def create_folder(directory):
"""Function to create a directory
@param: directory Name of the directory to create in string form
"""
if isinstance(directory, str):
if not os.path.exists(directory):
os.makedirs(directory)
return True
return False | c48fc079c9f27ffbba7d1bc91a51f4a604825865 | 649,149 |
import torch
def bound_and_scale(scale, bounds):
"""
Combination of scaling and bounding
Args:
scale (torch.tensor): divide input by this value
bounds (torch.tensor): tuple, clamp to (bounds[0], bounds[1])
"""
return lambda x: torch.clamp(x / scale, bounds[0], bounds[1]) | 63e2ca0c3c135c98bf14bbe159dc2615b756f337 | 649,150 |
def encipher(sentences, shifts):
"""
Encipher the provided sentences with _SHIFT shifts
Args:
sentences (list of string): list of sentences to get encipher
shifts (list of Layer): encipher
Returns
the enciphered sentences
"""
ciphers = []
for sentence in sentences:
cipher = ""
for i in... | 1bdff722a3c488ccdb803a465359bc313f289524 | 649,151 |
from datetime import datetime
def date_from_geo_string(geo_string):
"""get date from GEO release date、last update date、submission date string"""
return datetime.strptime(geo_string, '%Y-%m-%d').date() | 8620b90bd4249e5d817b4716d6be1ef681a3deac | 649,152 |
def nexus_infile(myid,itwist):
""" nexus style input name
Args:
myid (str): prefix
itwist (int): twist index
Returns:
str: input filename
"""
prefix = myid.split('.')[0]
infile = '.'.join([prefix,'g%s'%str(itwist).zfill(3),'twistnum_%d'%itwist,'in','xml'])
return infile | ac3c2482d2fb572ad994241fe2e944c9a74448ba | 649,153 |
def flip_subarray_params(input_params):
"""
Helper function to switch the row and column entries in a SUBARRAY tuple
"""
assert isinstance(input_params, (tuple,list))
assert len(input_params) == 4
output_params = [input_params[1],
input_params[0],
... | 5d30f3c1f5c2b3601f3e8cab65b0d1061d4e920e | 649,154 |
def listWrite(lt):
"""Takes a list and returns the first element as a string"""
return str(lt[0]) | c75b9d4f9551df06cafa111f360e01a7d960dcd2 | 649,155 |
import json
def get(client, bucket):
"""
Get the BIG-IP admin password from the S3 bucket created by the CFT
"""
data = client.get_object(Bucket=bucket, Key="credentials/master")
json_data = data['Body'].read()
return json.loads(json_data)['password'] | 22fb91bfb543b9cbf8cebfc1bb3d48ee1b29d06b | 649,156 |
import sys
def get_info(line, bit_thresh):
"""
get info from either ssu-cmsearch or cmsearch output
"""
if len(line) >= 18: # output is from cmsearch
id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16]
sstart, send, strand = int(line[7]), int(line[8]), line[9]
... | 5f484faf507febdfc372f9404a0f25fe70bf6110 | 649,158 |
def count(catalog):
"""Given a Catalog, return the number of strings actually translated."""
translated = [m for m in
catalog
if m.string]
return len(translated) | 0cbc7074423a9ea9a19f61a3e16e25821527576c | 649,159 |
import argparse
def get_parser():
""" Creates an argument parser. """
parser = argparse.ArgumentParser()
parser.add_argument(
'--url',
type=str,
required=False,
default="http://files.grouplens.org/datasets/movielens/ml-100k.zip",
help='url to download movielens dat... | 60c1ea3f5845bd6874bfe9abf15e7da444df11a5 | 649,162 |
import os
import json
def read_cfg(path):
"""
Function reads json configuration file.
Parameters:
path (string): JSON configuration file path.
Returns:
dict: Tool configuration dictionary. Read config on success,
default config otherwise.
"""
# to avoid script error default... | 47c57a049458aaad32389520dfe849860d6d7edd | 649,164 |
def filter_user(user, using='records', interaction=None,
part_of_week='allweek', part_of_day='allday'):
"""
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
... | 2a988f1d40d77d197921f50122c44403e37d9ec5 | 649,165 |
def json_dict_copy(json_object, property_list, defaultValue=None):
"""
property_list = [
{ "name":"name", "alternateName": ["name","title"]},
{ "name":"birthDate", "alternateName": ["dob","dateOfBirth"] },
{ "name":"description" }
]
"""
ret = {}
for pr... | 33ece90900803cfddcd4b920968d9ea1dd29f145 | 649,166 |
def sequence_key(sequence):
"""Returns a key for mapping sequence paths to graph vertices."""
return ":".join([str(s) for s in sequence]) | eb78fae32636367d8d396df161998869d85fea55 | 649,167 |
def translateCodonToAmino(codon):
"""Translate a DNA codon to it's Amino acid using the RNA codon table."""
rna_codon_table = {
('GCT', 'GCC', 'GCA', 'GCG'): 'A'
}
return rna_codon_table[codon] | 7959694f2024cdc4e8c695f78930461d34277ea1 | 649,168 |
def dict_flat_get_full():
"""Get flat dict for :func:`get` of full data of Dataverse.
Returns
-------
dict
Full Datafile dictionary returned by :func:`get`.
"""
return {
"name": "Scientific Research",
"alias": "science",
"dataverseContacts": [
{"cont... | 35561e3059e474b4e2d1a2c6f41b2374a88ecdb9 | 649,169 |
import html
import re
def clean_title(raw_input):
"""
Removes formatting weirdness from title strings.
@param raw_input: the raw, unsanitized input
@return cleaned string
"""
if raw_input == '':
return raw_input
if raw_input is None:
return ''
t = raw_input
t = ... | 76c908f4ff11ecbf8b7b3bd267f3cb961ab4bb79 | 649,170 |
def sane(id):
"""EnergyPlus variable names my not contain periods."""
return id.replace('.', '_') | a2bccb2ff57503c4c999477c6998f9c981dcb31a | 649,172 |
def use_signals(request):
"""Use signals for timing out or not."""
return request.param | b743ef601ac9a708c4619749697e6078f2cfce5d | 649,173 |
def _parse_user_ids(users, client):
"""parse a string of users separated by commas into IDS"""
ids = []
split_users = users.split(',')
for u in split_users:
u = u.strip()
if len(u) > 0:
uid = client.users.list(query=u)
if uid:
ids.append(uid[0]['id... | 9603d964d6567efcd0150f365da0991472e19b82 | 649,175 |
import os
import glob
def redcap_data_dictionaries() -> list:
"""Return paths to REDcap *DataDictionary* files from 'data' directory"""
base = os.path.dirname(__file__)
return glob.glob(os.path.join(base, "*DataDictionary*"), recursive=False) | 3a2af8f2bff3378d76df14de828754d9691b11df | 649,176 |
def parse_sudoku_file(sudoku_folder_path, sudoku_name):
"""Lukee .sudoku -tiedoston ja palauttaa sen tekstijonona
Args:
sudoku_folder_path: Polku .sudoku -tiedostojen kansioon
sudoku_name: Sudokun nimi kansiossa
Returns:
.sudoku -tiedoston tekstijonona
"""
# Read the .sudo... | ce9fa92a1e05fa5cd359ac0963709e52e379adef | 649,177 |
import socket
def IPv4(ip_addr):
"""
Validate a string as an IPv4 address. See `man 3 inet` for details.
"""
ip_addr = str(ip_addr)
try:
socket.inet_aton(ip_addr)
except socket.error:
raise ValueError('Invalid IPv4 address: %s' % ip_addr)
return ip_addr | 209f54390b02bbf24ff3a2d3cc6a917eaaf975ed | 649,178 |
def cg_has_node(cg, node):
"""
Return True if the cluster graph contains the corresponding node
:param cg:
:param node:
:return:
"""
return cg.nodes().__contains__(node) | b967c1ecb856219ab94a174ede69a482aa8ad2a9 | 649,179 |
def get_movie_data_both_channels (data, movie_ID):
"""Pull out track data in both channels for one movie out of a dataframe.
Args:
data (Pandas dataframe): Parsed tracks for each movie, as created by the
read_2color_data function of the parse_trackmate module. Contains
the follo... | 75a526fbac70f69ff95d79e62977df135c9c1090 | 649,180 |
def create_in_term_for_db_queries(values, as_string=False):
"""
Utility method converting a collection of values (iterable) into a tuple
that can be used for an IN statement in a DB query.
:param as_string: If *True* the values of the list will be surrounded
by quoting.
:type as_string: :cl... | 626cec3ab25623b16708eb0250598171064dc17d | 649,181 |
def list_of_genes_ecoli():
"""List of genes for testing (E. coli)"""
return ['b0720','b1241','b1761','b0003'] | ef9081aaa8f635400b2a9a30412e4ad9ae76c234 | 649,182 |
def track_indexed_db_for_origin(origin: str) -> dict:
"""Registers origin to be notified when an update occurs to its IndexedDB.
Parameters
----------
origin: str
Security origin.
"""
return {"method": "Storage.trackIndexedDBForOrigin", "params": {"origin": origin}} | 9726a3cd3a6f7e0183c233638d142ba2fffcdbaa | 649,183 |
def __pos__(self) :
"""Return self"""
return self; | 00e3a77f75161bedeb4d26302bfa163362c937cf | 649,184 |
def parse_bq_record(bq_record):
"""Parses a bq_record to a dictionary."""
output = {}
for key in bq_record:
output[key] = [bq_record[key]]
return output | c72ad597a5f5a7fabe8f36212ba7ae42b878f1f4 | 649,186 |
from typing import Dict
from typing import Any
import yaml
def _read_config(config_file_path: str) -> Dict[str, Any]:
"""Cached loading and decoding of the config file."""
with open(config_file_path) as file:
data = yaml.load(file, Loader=yaml.SafeLoader)
if not data:
raise RuntimeError(... | b1422bd80d61763dc496674ee8470d78d671d470 | 649,187 |
def get_node_contexts(pipeline):
"""Get a dict of node_name->node_context from pipeline"""
contexts = {k: getattr(pipeline[k], "context", {}) for k in pipeline._node_lookup}
return contexts | 6040356ff39960a9e1680b4cc3f14106db8d73fb | 649,188 |
def before(value, a):
"""Find first part and return slice before it.
"""
pos_a = value.find(a)
if pos_a == -1: return ""
return value[0:pos_a] | 4e2af9ae5bd483606ae5f769b9d51161ba1c32e7 | 649,189 |
def numColors(qimage):
"""Compatibility function btw. PyQt4 and PyQt5"""
try:
return qimage.numColors()
except AttributeError:
return qimage.colorCount() | 8a999c63177484288b469f474b466c70f73f5565 | 649,190 |
def dumps(blackbird):
"""Serialize a blackbird program to a string.
Args:
blackbird (BlackbirdProgram): a :class:`BlackbirdProgram` object
Returns:
str: the serialized Blackbird program
"""
return blackbird.serialize() | f3e8bedcd84d2579c0966f7d4843a626099c25a9 | 649,191 |
import subprocess
import sys
def getInstalledPackages():
"""
Returns list of installed packages.
:return list-str"
"""
reqs = subprocess.check_output([sys.executable,
'-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0]
for r in reqs.split()]
return installed_packages | c53fe98d0c3ca163b245636eadc016e595537173 | 649,192 |
import os
def file_is_outdated(file_path, reference_file_path):
"""
Check if the given file is outdated compared to the reference file.
Also returns true if the reference file does not exist.
:param file_path: Path to the file to check.
:type file_path: str
:param reference_file_path: Path t... | 18806e7c71864be1174352c56da74bef8a825d16 | 649,194 |
def setparas(pdict,ddict,args=0):
"""use paraster dict and default paraster dict to set the runtime variter"""
for key in ddict.keys():
if pdict.has_key(key):
if pdict[key]:
ddict[key]=pdict[key]
else:
ddict[key]=1
if args and pdict.has_ke... | 21bda3d65b023a5ecf7958d97e2abcdf639f0a0f | 649,195 |
def scalar_eq(x, y):
"""Implement `scalar_eq`."""
return x == y | a03fc0ea01e0b3c22ae0b5a3489cf47659382c7f | 649,196 |
def select_all_photo_thumbnail(session):
"""Get a list of all image thumbnails from db"""
session.execute("""
SELECT url, title FROM photos
""")
return session.fetchall() | 71b866de0261ae7f772d326eaa8c3a1c79dd931b | 649,197 |
import os
import hashlib
def locate_checkpoint(checkpoint_dir, msg):
"""
This checks if a message has already been indexed by using a digest of the first 300 characters,
which includes a date, message id, source and destination email addresses.
:param checkpoint_dir: This contains the path where check... | f3ce4e8b715ce6fdf06cec01c0b604e03bf1a0fa | 649,198 |
import re
def is_copy_modify_with_no_change(diff_header):
"""Returns true if similarity index is 100% in the diff header."""
return re.search(r"(?m)^similarity index 100%", diff_header) | ad0e9146e097503db2b58e5f40052281f0f1a35b | 649,200 |
from functools import reduce
def modeOfLengths(input):
"""
PROTOTYPE:
modeOfLengths(input)
DESCRIPTION:
Finds the mode (most frequently occurring value) of the lengths of the lines.
ARGUMENTS:
- input is list of lists of data
RETURNS:
mode as integer
"""
freq = {}
... | 57a8248a5448e3a6af226bf94585a00eb501fd8a | 649,201 |
def create_route_map(obj):
"""
Iterates of all attributes of the class looking for attributes which
have been decorated by the @on() decorator It returns a dictionary where
the action name are the keys and the decorated functions are the values.
To illustrate this with an example, consider the foll... | 3aed962296b953bac1ab23d46b4bd36e4c2d8adb | 649,202 |
from typing import BinaryIO
def _bytes_match(fd: BinaryIO, expected: bytes) -> bool:
"""Peeks at the next bytes to see if they match the expected."""
try:
offset = fd.tell()
data = fd.read(len(expected))
fd.seek(offset)
return data == expected
except IOError:
return... | 69a1063cb46203db78d362d04f731ac98d283ffa | 649,203 |
def remove_result_attr(result):
"""Remove all attributes from the output"""
filtered_list = []
for tup in result:
lis = list(tup)
removeset = set([2])
filtered_list.append(tuple([v for i, v in enumerate(lis) if i not in removeset]))
return filtered_list | ccc38b29d6e97adc3ea380bf9ce5bee7e356a9bd | 649,204 |
def juftmi(x):
"""x juft bo'lsa True, aks holda False qaytaruvchu funksiya"""
return x%2==0 | 9bc9432d91291fd32fb972087588aa282965c64c | 649,205 |
def splitPath(path, sep='/'):
"""
Chops the first part of a /-separated path and returns a tuple
of the first part and the tail.
If no separator in the path, the tail is None
"""
sepIdx = path.find(sep)
if sepIdx < 0:
return (path, None)
return path[:sepIdx], path[se... | e9b3d529731dba4462a425629898a6e0e4ed0c2e | 649,206 |
def is_valid_deck(deck):
"""(list of int) -> bool
Precondition: the length of input list is a list of number.
Return true iff the input deck is a valid deck of cards,
which means number of cards in the deck is consecutive.
Return false if the input deck is not a valid deck of cards.
>>> deck ... | 9de58d4ffb721073efb79a2579b89722e9e3346a | 649,208 |
def volumes(cfg):
"""Return list of dicts defining task container volumes"""
aux_mount = cfg.get('auxiliary_mount')
aux_dest = cfg.get('aux_dir')
stor_mount = cfg.get('storage_mount')
stor_dest = cfg.get('espa_storage')
return [{"container_path": aux_dest, "host_path": aux_mount, "mode": ... | 08b1fe06d3b98eaa563003c084564288775c33da | 649,209 |
import os
import pathlib
import glob
import shutil
def copy_files(files_type, output):
"""Copies the files from the input folder to the output folder
"""
total = 0
out = dict()
for (files, folder_type) in files_type:
counter = 0
full_path = os.path.join(output, folder_type)
... | 9bf4af04a0b2ce71102a92b743ccfc2b51864ee3 | 649,211 |
import argparse
def parse_args():
"""
Args used for preprocessing
"""
PARSER = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawTextHelpFormatter)
PARSER.add_argument('--raw_data_dir',
dest='data_dir',
... | 78926820e910a682db1807cc658ebe4d315ccdd5 | 649,212 |
async def rick() -> str:
"""Rickrolling!"""
return "https://www.youtube.com/watch?v=dQw4w9WgXcQ" | 065a50c652ccb8a95231bb4ea00f75ed07e1be2c | 649,213 |
import math
def _daylight_hours(sunset_hour_angle_radians):
"""
Calculate daylight hours from a sunset hour angle.
Based on FAO equation 34 in Allen et al (1998).
:param sunset_hour_angle_radians: sunset hour angle, in radians
:return: number of daylight hours corresponding to the sunset hour an... | 7eef992832103f0fefdfaa3d936aa7015f3fdc61 | 649,214 |
def get_no_data_value(sensor):
""" Hook for someone to somehow figure out the right NoDataValue"""
return -9999 | bc52851037f99d8ea72f8f897683e6ee6cde3316 | 649,216 |
import os
import shutil
def which(program, mode=os.F_OK | os.X_OK, path=None):
"""
Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of ... | 04c1213c71d8f898d5c648837aca90700fbde522 | 649,217 |
def separate_equally(seq, n=5):
"""
#return index of equally distance of a sequence
>> separate_equally([i for i in range(100)],4)
>> ([25, 50, 75, 100], 25)
"""
delta = len(seq) / n
start, res = 0, []
while (True):
start += delta
if start > len(seq):
break
... | a51165d68bed9d6e389fd7b232d8a9a8ca8cb247 | 649,218 |
def gateway_kind(request):
"""Gateway class to use for tests"""
return request.param | d49091d305931eab7e3c435c73e58eae0af270ff | 649,219 |
import math
def lg(n):
"""
Returns logarithm of n in base 2.
"""
return math.log(n, 2) | a311ac43e226357870454f92370390b38c274d1d | 649,220 |
def strip_quotes(string):
"""
Strips quotes off the ends of `string` if it is quoted
and returns it.
"""
if len(string) >= 2:
if string[0] == string[-1]:
if string[0] in ('"', "'"):
string = string[1:-1]
return string | 88d4a725c4fd6dd33f2eb43c3a2558cc44a88609 | 649,221 |
def __get_token(path: str):
"""
Get the API token from the container's file system.
"""
with open(path, "r", encoding="utf-8") as file:
return file.read() | 3a807fa00311f664e596dcfd025798994349078b | 649,222 |
import json
def filter_json(result):
"""
Builtin Callback, change stdout to json
>>> result = filter_json(ssh_result(["output"], ["error"], "foo", 0))
>>> result.dump()
foo [["output"], ["error"], 0] error 0 0 None
"""
result.out = [json.dumps((result.out, result.err, result.retcode))]
... | 8f00ba40cb6152ab96acc5b4b618db89d0ae13dd | 649,223 |
def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... | 0945c41531e5a1452129c764f81983a5855247ea | 649,224 |
def pade_42(k, params):
"""
Pade [4,2] in eqs.(10) and (11) has several typos
this is now the correct formula from the 2016 paper
old arguments: pade_42(k, l, a, b, g, d, w)
"""
l = params[0]
a = params[1]
b = params[2]
g = params[3]
d = params[4]
w = params[5]
a4b2=a*... | 035c70bfb843bdf9e6d38963665c995dc1480d13 | 649,225 |
def write_int(x):
"""
Examples
--------
>>> sandy.write_int(10)
' 10'
>>> sandy.write_int(-1e5)
' -100000'
>>> with pytest.raises(ValueError): sandy.write_int(-1e10)
"""
y = f"{int(x):>11d}"
if len(y) > 11:
raise ValueError(f"Integer '{y}' exceeds 11 char... | 7fbf687e2872f80dff0f6d754b0c2fc8d6c6092e | 649,226 |
import pickle
def load_from_file(filename):
"""Load a past state from file.
"""
f=open(filename,'rb')
try:
return pickle.load(f)
except EOFError:
print('Nothing written to file.') | 3ccc2938e90bd886a18b583568391b2a975d2a52 | 649,227 |
def py_eval(formula: str) -> float:
"""Calculates the result of the formula."""
return eval(formula) | 738e1e99a0281d14df51be12995aa6e6ebf5479d | 649,228 |
def invert_sign(num):
"""Change sign of number or add/remove leading sign of str."""
if isinstance(num, (float, int)):
return -1 * num
elif isinstance(num, str):
if num.startswith('-'):
return num[1:]
return '-{0}'.format(num)
raise ValueError(
'Num needs to b... | f21385da55d984732266ea1086163e590f2628eb | 649,230 |
def move_n_wrapped_lines_down(text, max_line_width, start, n):
"""Return position that is n lines below start."""
position = text.find('\n', start)
l = len(text) - 1
if position == -1 or position == l:
return l
while 1:
eol = text.find('\n', position)
if eol == -1 or eol == l... | 0d207557dfb3e4a8012fb40c83e2c2d1a30d3113 | 649,231 |
def as_microsoft(expression):
"""
Decorated function is added to the provided expression as the Microsoft
vender specific as_sql override.
"""
def dec(func):
setattr(expression, 'as_microsoft', func)
return func
return dec | bf5ef460324ff33dddf266f23b8a67d8fb506982 | 649,232 |
import tempfile
import os
def check_mesh_diff(mesh1_filename: str, mesh2_filename: str, print_diff: bool = True):
"""
WARNING: this function uses `os.system` and could be used for
hostile purposes. Make *sure* your filenames are valid paths.
Some filename checking is done to try to prevent this.
... | 752f07029879817907d8e4017369aba0ee0a36b9 | 649,233 |
def evaluate(data_iter, net, loss_func, mining_func):
"""
evaluate validate loss
:param data_iter:
:param net:
:param loss_func:
:param mining_func:
:return:
"""
net.eval()
loss_sum = 0.0
n = 0
for batch_idx, (X, y) in enumerate(data_iter):
X = X.cuda()
y ... | fca14464c907d75b1afa1a090f361d4aa60732fc | 649,234 |
def _get_like_function_shapes_chunks(a, chunks, shape):
"""
Helper function for finding shapes and chunks for *_like()
array creation functions.
"""
if shape is None:
shape = a.shape
if chunks is None:
chunks = a.chunks
elif chunks is None:
chunks = "auto"
... | c56187a7fc92b1a69f75d7defe9a57bb6376515c | 649,235 |
from pathlib import Path
def search_just(directory='buckets', files_glob='**/*.json'):
"""
批量搜索文件
"""
p = Path(directory)
files_list = (i for i in p.glob(files_glob))
return files_list | 54d561e939086410b2e4bfa5012c581f42a30d33 | 649,236 |
from io import StringIO
def ret_a_stream():
"""
Return a stream of text
"""
ret = StringIO()
ret.writelines(['1. hello\n', '2. world\n'])
return ret | a7bc9e2254098c62a3d7121a54c3bad745d9b1e6 | 649,237 |
def format_roster(DF, formation):
"""
Cleans up dataframe by removing the coach, GKs, and trainees.
Maintains the formation list.
DF starts with players names as columns, rows are 0 - 22
"""
DF = DF.set_index(['POS'])
DF = DF.transpose()
# Remove Coach?
coach = 'Rogelio Nakamura'
... | 3604e6b68ec0cd75397cdffe217b231ccc364b6f | 649,238 |
def get_kth_minimum(x, k=1):
""" gets the k^th minimum element of the list x
(note: k=1 is the minimum, k=2 is 2nd minimum) ...
based on the incomplete selection sort pseudocode """
n = len(x)
for i in range(n):
minIndex = i
minValue = x[i]
for j in range(i+1, n):
... | 7acaa35b6334560002d429671247a4de5aeb5e40 | 649,239 |
def get_div_ids_by_level(divs, level):
"""
Returns a list of all div ids with level.
"""
if not isinstance(divs, list):
divs = [divs]
ids = []
for div in divs:
if div['level'] == level:
ids.append(div['id'])
# no need to check subdivs
cont... | 3db3c7c0f2882c04fa0c15afaf348d890097aea2 | 649,240 |
def new_admin(user, password_hasher):
""" Create new admin user for testing. """
User = user
# Admin user mock data
admin_user_data = {
"username": "admin",
"email": "admin@email.com",
"password": password_hasher.hash("admin"),
}
new_admin = User(**admin_user_data)
... | bc095d270ccb1f124a408a65b6a3684f407bbda0 | 649,241 |
import numpy as np
def autocorr(a,v):
""" Performs autocorrelation using the np.correlate
in 'full' mode. Normalization has been added for
keeping the values between -1,1
Inputs:
a: Vector a; a 1D array only
v: Vector b: a 1D array to be autocorrelated with a
Outputs:
cor... | 661555f4f10098ea8d2ec3df193dbea12603adf6 | 649,242 |
def clean_up_command_output(raw_command_data):
""" clean up command output
restructures the registered output data """
# initialize vrf command output
vrf_command_output = []
# skip if no data available in the raw command data
if 'results' not in raw_command_data:
return vrf_command_ou... | 30375e50d4193228bb409d350e86bbf4d5ff27fb | 649,243 |
import six
def flatten_content_tree(roots, depth=0):
"""
Transforms a tree into a list with ``indent`` as the depth of a node
in the original tree.
"""
results = []
for key, values in six.iteritems(roots):
elem, nodes = values
elem.update({
'path': key,
... | ac6b2eeefd2d6bf4b38147822106a4c36dec7687 | 649,244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.