content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
from pathlib import Path
import shutil
def copy_files(path_pairs):
"""Copy files and directories to specified new locations
path_pairs should be a list of [Path(src), Path(dst)]
"""
def is_older(path_1, path_2):
return path_1.stat().st_mtime < path_2.stat().st_mtime
def copy_di... | 162a773eb364045d4e1e696bf93f765ba6733abd | 624,655 |
def drake(Rs, fp, ne, fl, fi, fc, L):
"""
Ecuación de Drake.
Parámetros
----------
Rs : float
Tasa anual de formación de estrellas en la
galaxia.
fp : float
Fracción de estrellas que tienen planetas en su órbita.
ne : float
Número de esos planetas orbitando d... | 87f7514c72305082905984157db79267dc80912a | 624,656 |
def tile_to_quadkey(tile_x, tile_y, level):
"""This is a function that converts tile coordinates at a certain
level of detail of a Bing Map to a unique string identifier (QuadKey).
:param tile_x: The x axis coordinate of the tile at `level` level of detail
:param tile_y: The y axis coordinate of th... | 6416511a03e4bb65eef969fa223aacbb18b8ee32 | 624,657 |
import sqlite3
def create_abundance_dict(database, datasets):
"""Process the abundance table by dataset in order to create a dictionary
data structure organized like this:
transcript_ID -> dataset -> abundance in that dataset
"""
abundance = {}
conn = sqlite3.connect(database)
... | 973bf185d5d83be7c738ec0dd1c4c8d39202ff5c | 624,658 |
import pkg_resources
import pathlib
def _get_ee_sources_path() -> str:
"""Gets the ee-sources folder path.
Returns:
The ee-sources folder path.
"""
ee_extra_py_file = pkg_resources.resource_filename("ee_extra", "ee_extra.py")
pkgdir = pathlib.Path(ee_extra_py_file).parent
return pkgdi... | 150c703871825968eab3b4b737b0a132dba63a2d | 624,659 |
def merge_optional_trees(tree, big_tree):
"""Merge two MacroConditionTrees when one or both objects may be `None`."""
if tree is not None:
if big_tree is None:
return tree
else:
return big_tree.merge(tree)
else:
return big_tree | b8aaad8d595bf5dd9848bd7df37222044f34a604 | 624,662 |
def do_move (move, facing, x, y):
"""calculate new move location"""
valid_move = True
if facing == 'N':
if move == 'forward' and y > 0:
y -= 1
elif move == 'left' and x > 0:
x -= 1
facing = 'W'
elif move == 'right' and x < 5:
x += 1
... | 2f6f63ba0f0fc440ce3f267502af9dd2f6d26d1b | 624,663 |
def tones(last, length = 16, **kwargs):
""" produces a palette varying from the base color to grey """
r, g, b = last.rgb
m = max(r, g, b)
if r == m:
r = m
else:
r += m/(length+1)
if g == m:
g = m
else:
g += m/(length+1)
if b == m:
b = m
else:
b += m/(length+1)
return r, g, b | 696e39c7d98504a8073f800fc8197214e0b05484 | 624,664 |
def ibis_test_file(tmp_path):
"""Return a golden ibis model file to test with."""
ibis_file = tmp_path.joinpath("test.ibs")
with open(ibis_file, "w", encoding="UTF-8") as output:
output.write(
r"""[IBIS Ver] 5.1
[File Name] example_tx.ibs
[File Rev] v0.1
[Date] 2019-02-10
... | 15e8c0c257c968f91eff21fd515cbec7521c4a1d | 624,665 |
def csrf_token():
"""Dummy implementation for older versions of Django"""
# Should be deprecated, Django versions prior to 1.2 aren't supported
# anymore.
return u'' | e3ab4103d46ad3b96eab7c92d03a7812c5b67420 | 624,666 |
import socket
import sys
def _create_udp_socket():
"""Create a UDP socket for usage with a datagram endpoint."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# Python says this is unsafe, but we need it to have
# multiple servers live on the same host.
sock.setsockop... | c505f496883ef13079a2dc850007153d580451c7 | 624,669 |
def _calc_trsp_at_density_levels(trsp_ds, rho_w, rho_s, ufld, vfld, lat=None):
"""Helper function to compute transport at binned density levels
given the maskW and maskS. Extracted here to do the same operations for
latitude or section masks
Parameters
----------
trsp_ds : xarray Dataset
... | a22ca4c899c821179d17be39cc3b5197a3722b70 | 624,670 |
def tower(n):
"""computes 2^(2^(2^...)) with n twos, using recursion"""
if(n==0):
return 1
return 2**tower(n-1) | 30554f29eee5498d06910d580afaaa606894a83a | 624,671 |
def convert_feature_to_vector(feature_list):
"""
:param feature_list:
:return:
"""
index = 1
xt_vector = []
feature_dict = {}
for item in feature_list:
feature_dict[index] = item
index += 1
xt_vector.append(feature_dict)
return xt_vector | 9460cdef12666cc7e98ad221316c159f78a9b230 | 624,672 |
import re
def _single_quote_strings(sql: str) -> str:
"""Replace unquoted double-quotes with single-quotes."""
return re.sub(r"(?<![\\])\"", "'", sql) | 8cb5cda475b0e1cbb60dc85cbdb4354741fd5ae4 | 624,673 |
import os
def count_files_in_dir(dirpath):
"""
Counts the number of files contained in the specified
directory.
:param dirpath: Path to the directory
:return: Number of files
"""
return len(
[
name
for name in os.listdir(dirpath)
if os.path.isf... | 5f7aa6c6ecdbc4bdb609c17cba6901d027a588a3 | 624,674 |
def random_state_tuple_axis_1(request):
"""
Specific to `test_sample*_axis_1` tests.
A pytest fixture of valid `random_state` parameter pairs for pandas
and cudf. Valid parameter combinations, and what to check for each pair
are listed below:
pandas: None, seed(int), np.random.RandomState
... | aa9a7d6d916dcac0ae89c91b3ac735b7175329fe | 624,675 |
def _mul(x, y):
"""
Multiply x and y.
:param x: First element
:param y: Second element
:return: The multiplication result of x and y.
"""
return x * y | 132ce1678014de9512b73ead87cb53cfa3baaf46 | 624,676 |
import subprocess
def ping(host):
""" Checks if ping is possible and its response
"""
ret = subprocess.run(
['ping', '-c 3', '-w 5', host ],
capture_output=True,
)
return ret | 36950aadc20f6adb732cfcce10e510ab664654e0 | 624,677 |
def is_overlap(object1, object2):
"""Detects overlap between two rectangles.
Taking two objects, detects whether they overlap.
Assumes the presence of the following attributes:
- x
- y
- width
- height
Tests whether the rectangles are above/below each other, or
left/right of ea... | 648ea314a76cdd00d757239afbe1200cfad880f4 | 624,678 |
def lst_depth(lst):
"""Check max depth of nested list."""
if isinstance(lst, list):
return 1 + max(lst_depth(item) for item in lst)
return 0 | d94ba4ae4076fe9ad9685f89f8cfcb4540ace2d0 | 624,679 |
import argparse
import sys
def parse_args(args):
"""Parse command-line arguments.
Parameters
----------
args : list of strings
command-line arguments.
Returns
-------
options : :class:`argparse.ArgumentParser`
Command line arguments.
"""
parser = argparse.Argumen... | 2168ced9ef27b5b048ef436e099d95c052ed7a19 | 624,680 |
import importlib
def get_classifier(name, params):
"""
Returns an instance of a classifier based on a string of the package and parameters from the yaml experiment
"""
module_name, class_name = name.rsplit('.', 1)
module = importlib.import_module(module_name)
clf = getattr(module, class_name)
... | 06a33213e9f525dacdde84717514efe40771832f | 624,681 |
def is_operator(node):
"""This function checks whether a validation node is an operator or not.
Args:
node(str): The node key you want to check.
Returns:
: bool.
"""
return node.startswith('$') | fe8136058b924f9831af1dba3d67c2bf5ed30687 | 624,682 |
def hide(obj):
"""
Mark object as private.
"""
obj._spec__is_private = True
return obj | 9a78a7f5e0098d36cb16b714c79b299f403384c0 | 624,683 |
import math
def logmgf_exact_party_level(q, noise_eps, l, k, max_q):
"""Computes the logmgf value given q and privacy eps.
The bound used is the min of three terms. The first term is from
https://arxiv.org/pdf/1605.02065.pdf by extending to k partitioning.
The second term is from our paper.
The th... | 09d9ea67a3b66d99ee85e942eaf01ea1c15cffd9 | 624,684 |
def parse_logs_covdist_all_base(fname):
"""Parses _covdist_all_base_table.txt
_covdist_all_cpg_table.txt
_covdist_q40_base_table.txt
_covdist_q40_cpg_table.txt
Inputs: fname - filename of table
Returns: data - dictionary of coverage distributions up to 30X data
... | 76f25060144c17cfc287eb8f3e9ba5b24ef831a1 | 624,687 |
import re
def remove_punctuation(body):
"""
- Removes punctuation, symbols, and numbers
- Changes to lower case
- Strips new lines and extra spaces
Args:
body: a body of text
Returns:
A string with clean-up procedures applied
"""
punctuation_removed = re.sub(r'[^\sa-zA-... | f2ce17029f998d4be2a897999ed7cc1f27f9f0d2 | 624,688 |
from typing import List
import os
def get_dir_names(path: str) -> List[str]:
""" Returns the dir names inside directory specified by path. """
return [dir_name for dir_name in os.listdir(path) if \
os.path.isdir(os.path.join(path, dir_name))] | fd61dd5f09f6a022c26f56f7aed1442b42af8a23 | 624,689 |
import os
def fileparts(filepath):
"""
Splits into dirname,base,ext
"""
dirname,baseall = os.path.split(filepath)
base,ext = os.path.splitext(baseall)
return dirname,base,ext | 7536f0cc18017b7538c8ea1cd5b235923ff57bdb | 624,690 |
from pathlib import Path
import argparse
def check_file(fn):
"""Validate that the file exists and is readable."""
fp = Path(fn)
if not fp.exists():
raise argparse.ArgumentTypeError(f"{fp!r} does not exist.")
elif not fp.is_file():
raise argparse.ArgumentTypeError(f"{fp!r} is not a file... | 1209cbd3e2cdb54e052acbea936bc2b2a1cefce5 | 624,691 |
import json
def get_job_payload(id):
""" Retrieves JSON payload of the job from the assets folder
Arguments:
None
Returns:
Job's JSON payload {dict}
"""
payload_path = "assets/payload" + str(id) + ".json"
with open(payload_path, 'r') as f:
... | c3de91b7d70cf068ec3970f7ee967ab595949591 | 624,692 |
def convertToCPM(dose, period):
"""
Converts from milliSieverts/hr to CPM
Parameters:
dose (double): The dosage
period (double): The time period over which the dosage
is administered
Returns the measurement in CPM
"""
conversionFactor = 350000 / 1.0
return conversionFactor * dose / period | 1ec1f1b49c2596496b0b3dc6fe857fdea1e776c0 | 624,694 |
def cut_column(ser):
"""Determine two sets of indices identifing the values to be stored in left
and right partitions after the cut.
:ser: Pandas series
"""
if ser.dtype.name in ('object', 'category'):
frequencies = ser.value_counts()
pos = len(ser) // 2
median_idx = lc = 0
... | b4dc843b860cf902436e6d7424629d397aa3ad4c | 624,695 |
from typing import List
def _read_from_path(config:dict, path:List[str]):
"""Reads nested dictionary.
Eg `_read_config({'foo':{'bar':1}}, ['foo','bar']) = 1`
"""
if len(path) == 1:
return config[path[0]]
return _read_from_path(config[path[0]], path[1:]) | ec1b6917ca854cdb90c6b82a5833433428a83be5 | 624,696 |
import os
def get_info_dict(data_dir):
"""
idir:
original data root, egs: dev-clean
return:
wav_info, dict, wave_info[spk]=[wav1_path, wav2_path, wav3_path...]
"""
wav_info = dict()
entries = os.listdir(data_dir)
for spk in entries:
wav_name = []
cdir = os.p... | fa950c15c012c964f567c3b808464588fbfa0703 | 624,697 |
def read_asteroids(filename):
"""Returns a list of asteroid locations in the map provided in the file
Parameters
----------
filename : str
path/name of file that contains the asteroid map
"""
asteroids = []
with open(filename, "r") as f:
lines = f.read().splitlines()
... | abd1fefdaa80d35b570cc3afe7ae5a93d27dc87a | 624,698 |
def should_cache_download(url: str) -> bool: # pragma: no cover
"""
Determine whether this specific result should be cached.
Here, we don't want to cache any files containing "-latest-" in their filenames.
:param url: url string which is used to decide if result is cached
:return: When cache shou... | 8406668267b7e6b20b16a020646092547aee78cd | 624,699 |
import math
def find_threshold_time(neighbours_by_space, node_paired_unpaired, case):
"""
1. Arguments: "neighbours_by_space" = dictionary having the keys as the node no.s and values as their corresponding neighbours in space coordinates only
"node_paired_unpaired" = dictionary containing i... | a318680d52e02b1feef242fb1d33bc427835c43a | 624,700 |
def smallest_with(expr, symbol):
"""
Return the smallest sub-tree in an expression that contains a given symbol.
"""
assert symbol in expr.free_symbols
candidates = [arg for arg in expr.args if symbol in arg.free_symbols]
if len(candidates) > 1 or candidates[0] == symbol:
return expr
... | b20f6bd35359557e0ceea28c27bcf9f2a9b436ba | 624,701 |
def dict_differs_from_spec(expected, actual):
"""
Returns whether all props in "expected" are matching in "actual"
Note that "actual" could contain extra properties not in expected
"""
for k, v in enumerate(expected.items()):
if not k in actual:
return False
if actual[k] != v:
return False
return True | 67189b1a48eae66f9705197014f72824a7c7ef82 | 624,702 |
def quicksort(arr):
"""
qucik sort by py
"""
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right) | 6e8a5f423aede149438a93b489b59f35e03fbd9b | 624,703 |
def pipe_commands(commands):
"""Pipe commands together"""
return ' | '.join(commands) | b90bd203c3a6ff7fa57701425d0551ee98d5c0b6 | 624,704 |
def upper(text):
"""A tag/function/filter that converts `text` to uppercase. Inner tag names and attributes are converted, too (!)."""
return text.upper() | 9a8f27dee56692bebaa778bf9a9acb27c3279ae9 | 624,705 |
def neuron_cal_pd_total_net_input_wrt_weight(neuron, index):
"""
# The total net input is the weighted sum of all the inputs to the neuron and their respective weights:
# = zⱼ = netⱼ = x₁w₁ + x₂w₂ .... The partial derivative of the total net input with respective to a given weight
# (with everything els... | 0ef2b3386e0593ad365ee3198a79cb2674f74fd6 | 624,706 |
def parseColorLine(ls, keys, flags=set()):
"""
>>> parseColorLine("CODE 0 VALUE #05131D FOO".split(), {"CODE", "VALUE", "EDGE", "BAR"})
({'CODE': '0', 'VALUE': '#05131D'}, set())
"""
d = {}
s = set()
for idx, val in enumerate(ls):
if val in keys and idx+1 < len(ls):
d[val... | 0cd1fddd490990fb57769f9dc1f4c37ba138eba0 | 624,707 |
import json
def get_json(x):
"""Convert Python dict to JSON.
Convert Python dictionary into a JSON string.
Args:
x: Python dictionary
Returns:
JSON string
"""
return json.dumps(x) | bb7c5625834ecc56daba6f71ac7204b5fb38408b | 624,708 |
import re
def song_meets_search_requirement(
search,
song,
case_sensitive,
authorized_types,
):
"""
Check that a song meets the settings
"""
if song["type"] not in authorized_types:
return False
# Check if search match with an anime name
if (
song["type"] in ... | 19fe8888b78c7b4b9c25c5a65a020690e1c814e1 | 624,709 |
def file_linear_byte_offset(image_size, bytes_per_voxel, start_coords):
"""
Return the file byte offset corresponding to the given coordinates.
Files generally assumed to have the first dimension most rapidly changing
Assumes you have a stream of bytes representing a multi-dimensional image,
"""
... | 94303aeb0ccb84fd56ec9049a0cdd6c4de6b5678 | 624,710 |
from typing import Optional
import os
import re
def _find_most_recent_backup(normal_path: Optional[str]) -> Optional[str]:
""" Find the most recent old settings to migrate.
The input is the path to an unqualified settings file - e.g.
/mnt/usbdrive/config/robotSettings.json
This will return
- Non... | 973d59b9540c24f7109da9e5116905d36a3785d1 | 624,713 |
import functools
def decorator(function):
"""Decorator"""
#Eleganckie rozwiazanie problemu name i doc i przebijania sie ich od wrappera a nie funkcji opakowanej
@functools.wraps(function)
def wrapper(*args, **kwargs):
"""Wrapper"""
answer = function(*args, **kwargs)
return answer
#Toporne rozwiazanie probl... | 0dd01cb9c3fdba07990745012c820103ba5f107b | 624,714 |
def max_degree(graph):
""" Return the maximum degree in the graph """
return max(graph.degree, key=lambda kv: kv[1])[1] | f0ce7063df056bdd6046a496eee44ad7f219e32b | 624,715 |
def sequential(inputs,
layers,
):
"""Applies a sequence of layers to an input."""
output = inputs
for layer in layers.values():
output = layer(output)
return output | 7005dccf74bad55afa44747249d1802ee0bc03db | 624,716 |
def unscramble(word, unscramble_map: dict) -> str:
""" Takes a scrambled input word, and converts to unscrambled.
Args:
word (str): Scrambled input
unscramble_map (dict): Map of scrambled char->unscrambled char """
return "".join(sorted([unscramble_map[char] for char in word])) | aecb8bd551f4250ced3dd1634d4689bf3ecbfd16 | 624,717 |
def assert_params_all_zeros(module) -> bool:
"""Check if the parameters of the module is all zeros.
Args:
module (nn.Module): The module to be checked.
Returns:
bool: Whether the parameters of the module is all zeros.
"""
weight_data = module.weight.data
is_weight_zero = weight_d... | a00ccc7fa8718d97df71f3c21bed39c09bc4a9a2 | 624,718 |
def generate_frequency_dicts(result_frame):
"""generated frequency dictionarys of phred quality.
Args:
result_frame: pandas result frame from pileup
Returns:
baseQ frequency dictionar,mapQ frequency dictionary
"""
baseQ = [result_frame.iloc[x, 13] for x in range(len(result_frame))... | a9e2ca4524540ed0060683347445f5934c26c829 | 624,720 |
def ts_epoch():
"""Timestamp as epoch timestamp."""
return 1451606400000 | dcb64d16867fc29b0b10c1c01db1568302210812 | 624,721 |
import os
def format_dt(string):
"""
Formats datetime string to os appropriate format
"""
if os.name == 'nt':
return string.replace('-', '#')
else:
return string.replace('#', '-') | ccdafc55cc614770816a4af914a3c5b4f1ed5c2b | 624,722 |
def chinese_literature_ent_type_process_fn(d):
"""Not match my need
Arguments:
d {[type]} -- [description]
Returns:
[type] -- [description]
"""
ent_type = d.split(' ')[1].replace('\n', '')
return ent_type | 4af7e949811fae6f86af15210de1e8acb5b68901 | 624,723 |
from typing import Dict
def flip_dictionairy(dictionairy:Dict[str, str]) -> Dict[str, str]:
"""
Flips the dictionairy. Self explanatory.
"""
keys = list(dictionairy.keys())
values = list(dictionairy.values())
flipped_dict = {}
for i in range(len(keys)):
flipped_dict[values[i]] = ... | 7b601f1f95a37aba74205a078dfa0e4639ea70c4 | 624,724 |
def choose_hp(q_ideal, t_biv=-2, method=0, hp_type='aw', t_ground=10):
"""
Choose heat pump depending on desired thermal power and bivalence point
Method 0: Return best possible Heat Pump with average COPs
Method 1: Choose heat pump from catalogue of existing devices (source: Dimplex)
Parameters
... | a762055ddba6361254235bf7b270ee59b16d691e | 624,725 |
def capitalize(wordList, spacer):
""" Generally, capitalize all words for discover """
return spacer.join(word.capitalize() for word in wordList) if isinstance(wordList, list) else wordList.capitalize() | 5df3d8baecaab005c21c865fb8ad3adb4c08c2e4 | 624,726 |
def check_prompts(device_list):
"""check to verify prompt of devices.In order to ensure, that all processes were killed by previous
test, before running a new test.
:param device_list: List of devices to check
:type device: List
"""
for dev in device_list:
assert "FOO" in dev.check_outp... | 928afbd50ca8ddcb2159463b3df4fc2ef42b9ac5 | 624,727 |
import argparse
def getInput():
"""
Collects input from parser
@ In, None
@ Out, args, argparse.parser, dict-like argument interface
"""
parser = argparse.ArgumentParser(description='RrR Test Code')
parser.add_argument('-i', type=str, help='main input file')
args = parser.parse_args()
return a... | a8a2129c8ba6c1aa22ba9b47725551f87f4b3e3b | 624,728 |
def _lcss_point_dist(x, y):
"""
Parameters
----------
x: nd-array
Time series x (query).
y: nd-array
Time series y.
Returns
-------
The LCSS distance.
"""
dist = 0.0
for di in range(x.shape[0]):
diff = x[di] - y[di]
dist += diff * diff
... | 76cc333bf53b35668a5bfacbcd82e34143ffa71b | 624,729 |
def rule_dict(item):
"""Make a Python dict from a PDF page label rule.
Args:
item -- a tuple (pno, rule) with the start page number and the rule
string like <</S/D...>>.
Returns:
A dict like
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int}.
""... | 2752e37d80a50a0346c9052a8d25574abf87630d | 624,730 |
def prepend_parts(parts_prefix, n):
""" Recursively preprend parts_prefix to the parts of the node
n. Parts is a list of markers that indicates where you are in the
regulation text. """
n.label = parts_prefix + n.label
for c in n.children:
prepend_parts(parts_prefix, c)
return n | 37a11e2ff2b0b3a633e372d0488412f568522163 | 624,732 |
def read_famipc_fnames():
"""
Return a sorted list of FAMIPC5 CESM history filenames
"""
f_in = 'famipc5_hist_files.txt'
with open(f_in, 'r') as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
return sorted(lines) | ef45563817299604f41526d9193a4b2cf565960f | 624,733 |
import warnings
import copy
def clone_trainer(trainer, is_reinit_besides_param=False):
"""Clone a trainer with optional possibility of reinitializing everything besides
parameters (e.g. optimizers.)"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
trainer_new = copy.deep... | fc65f663665265fa31a5cd0bcca2e5b05464e079 | 624,734 |
def onlydigits(value):
"""
Filtre `value` pour ne garder que les chiffres.
On peut ainsi retirer toutes les sauts de lignes présents
dans le fichier `score.txt`.
Parameters
----------
value : str
La chaîne à filtrer
Returns
-------
str
La chaîne obtenue après f... | 46d0c8c271bbec3e49792dbab6183e982b107387 | 624,735 |
import binascii
def yara_image_generator(self) -> list[dict[str, str]]:
""" puts the data in a format that we need for later in the process
returns dict_list """
dict_list = []
if self.image_name is not None:
for file_type in self.image_name:
for match in self.get_file[1][file_typ... | e48cec217c9e2af1f62dead7ffaa74b97b1bbcae | 624,736 |
def calculate_number_of_needs(row, case_id_col, reindexed_need):
"""
Given a case id, returns the number of needs associated
"""
case_id = row[case_id_col]
rows = reindexed_need.ix[[case_id]]
return len(rows) | 76d42ac23959c49d475d1509f3b21f4c68a8cc94 | 624,737 |
def get_same_padding(kernel_size):
"""Return SAME padding size for convolutions."""
if isinstance(kernel_size, tuple):
assert len(kernel_size) == 2, 'invalid kernel size: %s' % kernel_size
p1 = get_same_padding(kernel_size[0])
p2 = get_same_padding(kernel_size[1])
return p1, p2
... | e7e5cbc2f87543015731fe50560708f2fb68ff16 | 624,738 |
def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | 6d4bea95cf4e13d929ea8f5d50b87f28af896a92 | 624,739 |
def rtf_encode(text):
"""
Convert unicode text to rtf format with substitution of non-ascii
characters. (Based on Martijn Pieters' code.)
"""
return ''.join(['\\u%i?' % (ord(e) if e < u'\u8000' else ord(e) - 65536) if (e > '\x7f' or e < '\x20' or e in u'\\{}') else str(e) for e in text]) | 2fb4a0f9a0326320fee6ac965319c9e2f1897fd9 | 624,740 |
from pathlib import Path
def get_project_path(project_name: str) -> Path:
"""Get the assets project path for the given project name (with no ".flxproj").
If you want to open the project, please use open_project() or copy_project() instead,
as they will copy the project to a temporary directory and clean ... | 05a5c4cb18b4e7b239da258fd6ca87185a0dec1c | 624,741 |
def mirror_from(source, attributes, only_getters=True):
"""Decorator (factory) for classes that mirror some attributes from an
instance variable.
:param source: the name of the instance variable to mirror from
:param attributes: list of attribute names to mirror
:param only_getters: if true only ge... | f40fb88b6982e5520aa740d334bd8eb1897d4024 | 624,742 |
def get_netcdf_response(coverage_offering, dataset, crs):
"""Uses a standard xarray function to create a bytes-like data stream for http response"""
dataset.attrs['crs'] = crs
return dataset.to_netcdf() | 1289f522133f663f26ca13bad7d2820619c328a9 | 624,743 |
import secrets
def criar_token():
"""
Cria um token somente com números e letras.
"""
token = secrets.token_urlsafe(6)
while ('-' in token or '_' in token):
token = secrets.token_urlsafe(6)
return token | e902c1d3b0c661f8301c18cb7be9054b9ba2ab5e | 624,744 |
def fatorial(n, show=False):
"""
-> Calcule um fatorial de um número.
para n1: O número a ser calculado.
para show: (opcional). Mostrar ou não a conta.
:return: O valor do fatorial de um número.
Criado por Tom Alves.
"""
if show == True:
f = 1
cont = 0
for c in r... | b76881c2437f2d2282dafb421ef2907f0979ed5c | 624,745 |
def echo(s):
"""Return the string passed in."""
return "We are echoing: %s" % s | 770497efe8d9b5662eae3811f59f155fc9202f43 | 624,746 |
import math
def round_up(x, near):
"""
Round x to nearest number e.g. round_up(76, 5) gives 80
Args:
x: Number to round-up
near: Number to which round-up to
Returns:
rounded up number
"""
return int(math.ceil(float(x) / float(near))) * near | f0726917905a363cbea3547a0cf03fcf8c1ee109 | 624,747 |
def get_penalty(start_time, submit_time):
"""
:param start_time: time in DateTimeField
:param submit_time: time in DateTimeField
:return: penalty in seconds
"""
return max(int((submit_time - start_time).total_seconds()), 0) | a97e3fc4ea2853ccd3c73f41d807023ae00e353c | 624,748 |
def getDimDict(seed, dim, labels=False):
"""
make a column dictionary for one of the dimensions of a query seed. this dictionary is often used
to recode a column in a Spark DataFrame either via SQL or a python user-defined function (udf)
e.g. We may want to recode the DHCP_HHGQ schema's 'hhgq' dimensio... | 0ed6f710d1ae316560b6cb763811c6f233b465a8 | 624,749 |
from functools import reduce
def model_summary(model):
"""
得到模型的总参数量
:params model: Pytorch 模型
:return tuple: 包含总参数量,可训练参数量,不可训练参数量
"""
train = []
nontrain = []
def layer_summary(module):
def count_size(sizes):
return reduce(lambda x, y: x * y, sizes)
for... | ca4b0296e404a2e9c08e953c7ecef14cf4cf6402 | 624,750 |
def cleanFilePaths(file, listOfResults, type=None):
"""
Constructs the data which consists of a dictionary within a dictionary.
The first level has keys that are the data file name, and the second
level contains two keys: saved and read. Within 'saved' and 'read'
are a list that contains the scripts... | a3f4306fdc2c7bf623075c31a0e6a591bc6facd1 | 624,751 |
def to_sting(reads):
"""join FASTQ reads to a single DNA string"""
return ''.join(i for i in reads) | b3ca3e5220807283744f46452ac44f1b4aa0115b | 624,752 |
def qe_at(df, energy):
""" Extracts QE at the specified energy.
"""
return df[df.E >= energy].sort_values(by='E', ascending=True).iloc[0].QE | 0473fea95bb6c4f09432556b19217b9bd58f31fe | 624,753 |
def unit(*args):
""" Create a unit dictionary.
Call with (abbreviation, name, units) or (abbreviation, name, plural
name, units). If the plural name is not given, it is calculated by
adding "s" to the singular name. Note that the abbreviation, name,
plural name (if given) and unit... | 16aa8afe1919212ff363dfce15fdcb6723937d6d | 624,754 |
def URLFIX(df, find_string, replace_string, columns):
"""Use this to fix path URL issues between operating systems"""
for col in columns:
df[col] = df[col].str.replace(find_string,replace_string)
print(df[col][1])
return(df) | 6c42306bd317716d65a15486a1b554584afe286d | 624,755 |
def dot(u1,u2):
""" Dot product of two vectors """
return u1[0]*u2[0] + u1[1]*u2[1] + u1[2]*u2[2] | 740f613598b2a725b26ad8f685f63b2cd5ce7ebd | 624,756 |
def train_test_split(df, train_proportion=0.7):
"""Split dataset into training and testing sets"""
# Index before which data will be used to training, and after which will be used for testing
split_index = int(df.shape[0] * train_proportion)
training = df.loc[:split_index, :]
testing = df.loc[spli... | c23c6087e5540f35ba5134769a5f6d262b9d60f2 | 624,757 |
import os
def _disable_recording():
"""Disable VCR.py integration."""
return os.getenv("RECORD", "false").lower() == "none" | 708f25aa350f9b7b8915391ba70c362fd4c3c2dc | 624,758 |
def exists_jpg_extension(files):
"""Checks whether any file in files is a jpg image
Args:
files: List of filenames
Returns:
True if any file is a jpg otherwise False
"""
has_jpg_extension = ['jpg' in fname for fname in files]
return any(has_jpg_extension) | 342846e89c52b3f791b5eadc4c99638f6d309596 | 624,759 |
def format_transaction(timestamp: float, address: str, recipient: str, amount: int, operation: str, openfield: str):
"""
Returns the formatted tuple to use as transaction part and to be signed
This exact formatting is MANDATORY - We sign a char buffer where every char counts.
"""
str_timestamp = '%.... | 7cf785d3edac138924a74e43fa733551b1e9de69 | 624,760 |
def detect_result_post_process(_detect_result, _detector_model_type):
"""
对检测的结果根据检测算法类型进行后处理
:param _detect_result: 检测结果
:param _detector_model_type: 检测模型的类型
:return: 后处理后的结果
"""
to_return_polygons = []
if _detector_model_type in {'pse', 'pan'}:
# 对label map进行多边形抽取以及聚合
... | 744aede8c1b5753837fe4f7cd41ac570deee45cc | 624,761 |
import string
def num_to_str(num, b=36, numerals=string.digits + string.ascii_lowercase):
"""
Converts integer num into a string representation on base b
@param b {int} base to use
@param numerals {string} characters used for string representation
@returns {string} string representation of num in ... | 8d19813fdbc72bffbdc23659b9d8afa1b77cbc41 | 624,763 |
def UppercaseMutator(current, value):
"""Uppercase the value."""
return current.upper() | ee16c6a92cd7e3f4d55859d22ab7a23c0a39af9b | 624,764 |
from functools import reduce
def specfile_changed(body: dict) -> bool:
"""
Does the commit contain specfile change?
:param body: message body
:return: bool
"""
files = reduce(
lambda val, key: val.get(key) if val else None,
["commit", "stats", "files"],
body,
)
... | 8541fc36cf1c5679e754f9ecd24703662bb5d40d | 624,765 |
import unicodedata
def clean_unicode(value):
""" Attempts to normalize a string to a nonunicode value
:param value: the value to be cleaned of unicode characters
:type value: str
:return: a mangled key
"""
try:
cleaned_value = str(value)
except UnicodeEncodeError:
cleaned... | 97af34bd95cd0d7b6a875d974561387bae1256b3 | 624,766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.