content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def human_readable_bytes(value, digits= 2, delim= "", postfix=""):
"""Return a human-readable file size.
"""
if value is None:
return None
chosen_unit = "B"
for unit in ("KiB", "MiB", "GiB", "TiB"):
if value > 1000:
value /= 1024
chosen_unit = unit
els... | f455087c124dd26df68d3404a2bf96fd0f24efb7 | 656,796 |
def validate_num_results(request):
"""
A utility for parsing the requested number of results per page.
This should catch an invalid number of results and always return
a valid number of results, defaulting to 25.
"""
raw_results = request.GET.get('results')
if raw_results in ['50', '100']:
... | 83a0ef8849ffc1c1c990036c1ae9fe33aa07a4cb | 656,797 |
def estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
"""
Estimate the probabilities of a next word using the n-gram counts with k-smoothing
Args:
word: next word
previous_n_gram: A sequence of words of len... | 69d680ef3f833a823d3773293dd595c5530d809c | 656,798 |
def dfs(graph, vertex, explored=None, path=None):
"""
Depth first search to compute length of the paths in the graph starting from vertex
"""
if explored == None:
explored = []
if path == None:
path = 0
explored.append(vertex)
len_paths = []
for w in graph[vertex]:
... | 475a5c3e8bdbdd6d3b358c6f02b8368395eef1ae | 656,799 |
def samflags(flag=0, verbose=True):
"""This script converts a decimal flag to binary and get the corresponding properties according to the sam-flag standard.
The code is based on the explanation given here https://davetang.org/muse/2014/03/06/understanding-bam-flags/
For manual checking sam flags, check htt... | d5a54fa373fdda58f8dd890b12a8958706db1cd1 | 656,800 |
def get_payer_information(json_list_of_transactions):
"""Function that returns payer specific information from each transaction
and adds columns relating to user settings."""
# Identifying columns that don't contain values.
# Not adding first or last name since they are present in display name
ke... | 4ae7e5e51631d8731f944c97cb11f8d1dc30615e | 656,801 |
def pool_update(parms_fixed, measure_list, pool_results):
"""
Function used to update the pool_results.
Parameters
===========
parms_fixed : list, index of parameters that are to fix
measure_list : list, measures newly calculated for parameters in parms_fixed
pool_results : dict, contains bo... | dde0fe05a91eaec9923b9ff86b25b15074beb1ee | 656,802 |
def parseHeader(header):
"""Extracts metadata from space-separated header"""
header = header.split()
id = header.pop(0)
meta = dict(data.split('=') for data in header)
meta['id'] = id
return(meta) | 289b05a81026ea2341a4f5fc221c64ea492cc1b4 | 656,803 |
import os
def checkfile(path):
"""Check file in the path, and extend with '(1)' like numbering system if there exists.
That helps to avoid overwriting and existing file.
"""
path = os.path.expanduser(path)
if not os.path.exists(path):
return path
root, ext = os.path.splitext(os.path.... | 0581cc05ea4938602af0ee58809f4116b3f716ef | 656,804 |
from typing import Callable
def easyintegrate(f: Callable[[float], float], a: float, b: float) -> float:
"""Calculate the area under a linear function f between and and b."""
return (f(a) + f(b)) * (b - a) / 2.0 | 85e24cee68b45f251401186b513287874bde3bd7 | 656,805 |
import hashlib
def hash_resource(resource):
"""
Hash a :class:`web_fragments.fragment.FragmentResource
Those hash values are used to avoid loading the resources
multiple times.
"""
md5 = hashlib.md5()
for data in resource:
if isinstance(data, bytes):
md5.update(data)
... | 511c95c70b6d0df84689ee4db28eb22adefd6811 | 656,806 |
def dump_matrix_group_name(value):
"""dump matrix_group_name"""
return value | ff49e9a40efa94ddfe56cb5d03249daa23131e5c | 656,807 |
def mini_batch_size_update(mini_batch_size, gpu_count):
"""Increase mini-batch size to accommodate more than 1 GPU."""
if gpu_count <= 1:
return mini_batch_size
elif gpu_count > 1:
return mini_batch_size * gpu_count | 9bcbad73bfc6adfbda3cc4fb03e741eee01f5699 | 656,808 |
import pickle
def load_pixel_corner_lookup(filename):
"""
Returns (lons, lats, corners), the pickeled objects created by
save_pixel_corner_lookup.
Equivalent to the arguments returned by read_official_corner_lut.
"""
with open(filename, 'rb') as f:
obj = pickle.load(f)
return obj | ff74990edd326c771d991bd6f8a526e247c06d9f | 656,809 |
import typing
def parse_s3_uri(s3_uri: str) -> typing.Tuple[str, str]:
"""
:param s3_uri:
:return:
"""
chunks = s3_uri.split("/", 3)
bucket = chunks[2]
key = chunks[3]
return bucket, key | e64886508ffb17801b41bd964fbce0914f63fd67 | 656,810 |
def binlist(n, width=0):
"""
Return list of bits that represent a non-negative integer.
n -- non-negative integer
width -- number of bits in returned zero-filled list (default 0)
"""
return list(map(int, list(bin(n)[2:].zfill(width)))) | bc25337e8a6edd0406c15c5b095ae7d13b4fa6b5 | 656,811 |
def check_for_output_match(output, test_suite):
"""Return bool list with a True item for each output matching expected output.
Return None if the functions suspects user tried to print something when
they should not have.
"""
output_lines = output.splitlines()
if len(output_lines) != len(t... | 8ba49e33f6af183650b47d8890543854a3aadacc | 656,812 |
def andSearch(inverseIndex, query):
"""
Input: an inverse index, as created by makeInverseIndex, and a list of words to query
Output: the set of all document ids that contain _all_ of the specified words
"""
docIds = set()
for q in query:
if q in inverseIndex:
if not docIds:
... | 04d31d96ba072d943a98b965f6f3abf589c532ed | 656,813 |
def extract_split_timing_info(fn):
"""
Group lines by benchmark iteration, starting from migrad until
after the forks have been terminated.
"""
with open(fn, 'r') as fh:
lines = fh.read().splitlines()
bm_iterations = []
start_indices = []
end_indices = []
for ix, line in en... | ad599a56323fca12427c2f3a5e19394575703909 | 656,814 |
def get_find_mode(conanfile):
"""
:param conanfile: conanfile of the requirement
:return: "none" or "config" or "module" or "both" or "config" when not set
"""
tmp = conanfile.cpp_info.get_property("cmake_find_mode")
if tmp is None:
return "config"
return tmp.lower() | 2ce911d19f57a3604501a1680e3c130a8bc0d5e6 | 656,815 |
def name_sort(long_format_list):
"""This function returns the sorted list of final output based on name of the files
"""
name_sorted_list=sorted(long_format_list, key = lambda x:x[6])
return name_sorted_list | 9c3e442a53d9ca59f4c5a1182ca6552fd323eab4 | 656,816 |
import torch
def create_verts_index(verts_per_mesh, edges_per_mesh, device=None):
"""
Helper function to group the vertex indices for each mesh. New vertices are
stacked at the end of the original verts tensor, so in order to have
sequential packing, the verts tensor needs to be reordered so that the
... | 6ac55d2b5bf1c2b323026b8de4a2c59ab064d38f | 656,817 |
def extract_mean_ci_score(rec):
"""
Parameters
----------
rec : dict
Audio recording record.
Returns
-------
Mean cacaophony index as float or -1 if it could not be found.
"""
ci = -1.0
try:
caco_id = rec['additionalMetadata']['analysis']['cacoph... | 16770d67baa8fd1894fc19fa3a3f4f688d858f2e | 656,818 |
def destagger(data, dim, new_coord, rename=True):
"""
Destagger WRF output data in given dimension by averaging neighbouring grid points.
Parameters
----------
data : xarray dataarray
input data.
dim : str
destaggering dimension.
new_coord : array-like
new coordinate... | 4ff4750b916f71208cf910d60c56c98179ddb130 | 656,819 |
def points_at(links, other):
"""Whether any of the links points at the other"""
return any(_.points_at(other) for _ in links) | 52b8663d2d5c3b5cafe899b8e5e63055a6969470 | 656,820 |
def convert_to_list(input, _type=int, _default_output=None):
"""
Converts the input to a list if not already.
Also performs checks for type of list items and will set output to the default value if type criteria isn't met
Args:
input: input that you are analyzing to convert to list of type
... | dd7a520bd263922164369483a3beebe8ccb4af7c | 656,821 |
def calc_channel_current(E, sigma, A):
"""
Calculate channel current
"""
I = E * sigma * A
return I | 1602bdaf37599d48361decb214a9f9e426c97d22 | 656,822 |
def sentinel2toa(img):
"""
Convert processed sentinel toa reflectance to raw values, and extract azimuth / zenith metadata
Parameters:
img (ee.Image): Sentinel-2 image to convert
Returns:
ee.Image:
"""
toa = img.select(['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8... | fff7e47e0364f5dc00ea3a8cd6060c0c2f59a27c | 656,823 |
def build_html_component_without_title(html_string):
"""
This function builds the html string for a component.
:param html_string: html_string of the component
:param title: Title of the html component
:return: html_string
"""
html = """
<div class="row">
<div class="col-md-... | e50e0cf816418ac8fca033f8ac6686e50538705a | 656,825 |
import logging
def build_keys_json_object(keys, blobname, anchor_key, found_keys, ocr_text, ocr_boundingbox,
page, height, width):
"""
This function build the json object for the auto-labelling
:param keys: The json object
:param blobname: The name of the file we are process... | 15e60c02ba91eac796e5a9ea6c608916901fa07c | 656,826 |
import re
import logging
def nonISOdate2ISO(ds):
"""
Convert a non ISO date string to a ISO date string
Parameters
-----
ds(str): date string
"""
logging.info('nonISOdate2ISO called')
regex = re.compile('(\d\d\d\d-\d-\d\d)')
regexII = re.compile('(.*\s\d:.*)')
print(ds)
fo... | 2f4b169246903d7bab690f391de8f25518e6ef74 | 656,827 |
def _make_bin_midpoints(bins):
"""Get midpoints of histogram bins."""
return (bins[:-1] + bins[1:]) / 2 | 67bea58555588488321f9f7443da7355bb58f3f4 | 656,828 |
import pathlib
def get_relpath(src, dst):
"""
Returns the relative path from ``src`` to ``dst``
Args:
src (``pathlib.Path``): the source directory
dst (``pathlib.Path``): the destination directory
Returns:
``pathlib.Path``: the relative path
"""
# osrc = src
ups =... | 87a11a909920d6da8ffc3b66519eb0762e04403d | 656,829 |
from typing import Optional
def validate_ref_component_optional(ref_component: Optional[int]) -> Optional[int]:
"""
Validates the reference to a component of an object.
:param ref_component: The reference to a component of the object.
:return: The validated reference to a component.
"""
if re... | ae2257375b97766e2310c11d8e638cfb6cbdb34c | 656,830 |
def mean_reversion(prices, shortMA, longMA, upper_threshold, lower_threshold):
"""
Buy or sell against the trend
:param prices: list of prices
:param shortMA: integer short moving average
:param longMA: integer long moving average
:param upper_threshold:
:param lower_threshold:
:return: ... | 96e363549c183ca94da67a7f1093248f6c10620c | 656,831 |
def flat_dict_diff(old_dict, new_dict):
"""
return: {
'name': {'old': 'old-value', 'new': 'new-value'},
'ttl': {'old': 'old-value', 'new': ''},
'prio': {'old': '', 'new': 'new-value'},
..
}
"""
def _fmt(old, new):
return {
'old': old,
'... | 4210cc383056096f505053ca93396b43c1d1f801 | 656,832 |
import os
def _GetPathPrefixes(path):
"""Returns all prefixes for the given path, inclusive.
That is, for 'foo/bar/baz', returns ['', 'foo', 'foo/bar' 'foo/bar/baz'].
Args:
path: str, the path for which to get prefixes.
Returns:
list of str, the prefixes.
"""
path_prefixes = [path]
path_remin... | 76a64187bb1c31791eb15f999d4ec876d9206cb9 | 656,833 |
def normalise(x):
""" Normalises data to 0-1 """
return (x - x.min()) / (x - x.min()).max() | be93a12b66fd4a4accd4ad74fc5a5226a3d029aa | 656,834 |
def denormalize(indv, mu, scale_to_mm):
"""
de-normalizes the data again
:param indv:
:param scale_to_mm:
:return:
"""
div = 1000 / scale_to_mm
#mu = np.mean(indv, axis=0)
#return (indv + mu) * div
return indv * div + mu | 807c8cabb82d685257f4581bc8a161d3e6ff121b | 656,835 |
def _fuse_deps(dep_dic, job_fusing_dic):
"""Fuses dependencies according to the fuse map in job_fusing_dic."""
inverse_fusing_dic={}
for (new_dep, older_deps) in job_fusing_dic.items():
for dep in older_deps:
inverse_fusing_dic[dep] = new_dep
new_dep_dict={}
# first tran... | fdb9c26ba5630fa70a8480c8552abde8fc14a890 | 656,836 |
import math
def format_bytes(bytes):
"""
Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl
"""
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent ... | b541f7ba67faaff44578b2791a13577494f1228a | 656,837 |
def _get_object_presentation(obj_dict):
"""Returns one of object possible presentation:
- display_name
- title
- name
- slug
if Nothing is presented in serrialized object
than it will return `{tytle}_{id}` presentation.
"""
keys = ("display_name", "title", "name", "slug")
for key in keys:
if o... | 456497d6e2b76c5d4a85cf882e6a01085eca4202 | 656,838 |
import gzip
import shutil
import os
def gzip_file(file_path: str, *, remove_original: bool = False) -> str:
"""
gzips the file at `file_path`, removing the original if
`remove_original = True`. Returns the file path of the
saved gzipped file.
"""
zipped_file_name = f'{file_path}.gz'
with o... | 6471f0e2fd5ba6890ba65d2ae489b4c95a1d21fa | 656,839 |
def distinct(not_distinct_list: list):
"""
Returns a list with no duplicate elements
"""
return list(set(not_distinct_list)) | 87dfa260b7882e28ada5803db30f12275968f44d | 656,840 |
import os
def get_project_folder_dir():
"""
This is to handle the situation when user run part of the program at different directory level, and the paths are not correct.
This is to find the highest parent directory no matter where the folder is or the program is run at.
:return: folder_dir, the absol... | 6a056d0a9df94a58bb6cfa4aeb9fb5e4cf3684d2 | 656,842 |
import os
def replace_suffix(filename, suffix):
"""
replace the suffix of filename with suffix
example: replace_suffix("/path/to/test.sam", ".bam") ->
"/path/to/test.bam"
"""
(base, _) = os.path.splitext(filename)
return base + suffix | 45869d523cf4690e2c52796ce1b3ac57bdc61878 | 656,843 |
def add_vector(vector, increment, mod = False, bounds = (0, 0)):
"""
Adds two 2D vectors and returns the result
can also do modular arithmitic for wrapping
"""
result = [0, 0]
result[0] = vector[0] + increment[0]
result[1] = vector[1] + increment[1]
if mod:
result[0] = resu... | b83c1a4e3c024f0e4fc67286c6f9e46b48555358 | 656,844 |
def get_config():
"""
===========================
Configuration for Workflows
===========================
plugin: "Linear", "SGE" for grid
plugin_args: qsub args
outputsink_directory: where to store results
working_directory: where to run things
"""
config = dict()
#config["... | 447ed18eef51e9feed97fd0f7b0bc6dc91013077 | 656,845 |
def run_threaded(fx, *args, **kwargs):
"""
Helper function to run a function in a separate thread
:param fx: the function to run in a separate thread
:param args: list arguments to pass to fx
:param kwargs: dictionary keyword arguments to pass to fx
:return: whatever fx returns
"""
retu... | 4777bc1304e80ef69acee3524e1ee61dcb7fd36f | 656,847 |
def find_ncolumns_in_gensim_corpus(corpus):
"""
find highest index to get appropriate n dimensionality of written matrix
"""
indexes={}
c=0
for doc in corpus:
if len(doc) > 0:
highest_in_doc = max([ix for (ix, value) in doc])
indexes[highest_in_doc] = 'dummy'
... | 73ad2685c33937d446ee9a6cda6e137b785345ef | 656,848 |
def addHtmlBreaks(s, isXhtml=True):
"""Replace all returns by <br/> or <br>."""
tag = {True:'<br/>\n', False:'<br>\n'}[isXhtml]
return s.replace('\n',tag) | dc4fb9d39fc7a2fba8d8c795c3c8394630358425 | 656,849 |
from typing import Iterable
import itertools
def xor_cipher(string: Iterable[str], key: Iterable[str]) -> str:
"""XOR шифр
:param string: Шифруемый/расшифровываемый текст
:type string: Iterable[str]
:param key: Ключ
:type key: Iterable[str]
:return: Текст после шифровки/дешифровки
:rtype:... | b9d37fef58c80e827a04d36b4551a8af4cd82633 | 656,850 |
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
f = open(words_file)
... | ff110f45e02fc48049f3d4180b093a72771e098e | 656,851 |
import re
def get_datatype_for_sequence_string(concat_seq):
"""Take a sequence string and return 'prot' or 'nucl' depending on the
content of letters from the alphabet.
"""
#print(concat_seq)
#print(list(concat_seq))
#print(set(list(concat_seq)))
# Define regular expressions to identify d... | b37949702af9197dba421135546567a7aee2bb43 | 656,852 |
def diff(list1, list2):
"""
Returns the list of entries that are present in list1 but not
in list2.
Args:
list1 A list of elements
list2 Another list of elements
Returns:
A list of elements unique to list1
"""
diffed_list = []
for item in list1:
if item not in list2:
diffed_list.... | 0a8cb8f9d2962591df6b46abb6c48c57f121492c | 656,854 |
def _get_sigmoid_signal(layer_labels):
""" A function using the sigmoid layer fraction as the signal. """
internal_layers = [ll for ll in layer_labels if ll not in ['ip', 'op', 'linear']]
good_layers = [ll in ['logistic', 'relu'] for ll in internal_layers]
return sum(good_layers) / float(len(internal_layers) + ... | c54333f4b1f7f4515e566afb00b5069a0e7e92df | 656,855 |
def agg_across_entities(entity_lists_by_doc):
"""
Return aggregate entities in descending order by count.
"""
if not entity_lists_by_doc or len(entity_lists_by_doc) == 0:
return []
result_set = {}
for doc_id in entity_lists_by_doc.keys():
cur_list = entity_lists_by_doc[doc_id]
... | ff0981630098d999c75e5efc1818c2c788a0a240 | 656,856 |
def generic_hash(obj):
"""
Compute a hash of all the fields in the object
:param obj: Object whose hash needs to be computed
:return: a hash value for the object
"""
sum = 0
for field in obj.attribute_map.keys():
sum = sum + hash(getattr(obj, field))
return sum | 6f9f105f1054b48a5613b3ae473835227dd94b8e | 656,857 |
def check_api_token(api_key):
"""
Check if the user's API key is valid.
"""
if (api_key == 'API_KEY'):
return True
else:
return False | 82689522445bd2aab2c4a6108d0a62373eef9430 | 656,858 |
def GetMosysPlatform(config):
"""Get the name of the mosys platform for this board.
cros_config_schema validates there is only one mosys platform per
board. This function finds and prints the first platform name.
Args:
config: A CrosConfig instance.
Returns:
An exit status (0 for success, 1 for fa... | 7011c72846cba8347c2e6c1455daed0961abba7b | 656,859 |
def is_valid_target_host(host):
# Rules where a target host contains multiple wildcards or a slash.
"""The target host must be a hostname, not URL, and must use at most one wildcard."""
if "/" in host:
return False
if host.count("*") > 1:
return False
return True | 4a7c7b3aa3d735a10c4ccf8b274a1aac814a69f0 | 656,860 |
def get_operations(product_id):
"""Get ProductImageCreate operations
Parameters
----------
product_id : str
id for which the product image will be created.
Returns
-------
query : str
variables: dict
"""
query = """
mutation ProductImageCreate($product: ID!,... | 895e5b20dacf8883712a00d605778cc9ac22efa5 | 656,861 |
def parse_variables(var_dict):
"""Parse variables in current context"""
valid_vars = {}
for key, value in var_dict.items():
if type(value) is int:
valid_vars[key] = value
if type(value) is float:
valid_vars[key] = value
if type(value) is list:
val... | 9bceca153607bf12af1d2fc2a4cfa5af9bc9abda | 656,862 |
import os
def genPSK256():
"""Generate a random preshared key"""
return os.urandom(32) | 777b5068f6f217b03bc68e0806f3c910a31fc495 | 656,863 |
import re
def _IsPreProlinePhiPsiAngle(PhiPsiInfo, Index, LastIndex):
"""Check for Pre-Proline phi and psi angles."""
# Pre-Proline: Only residues before proline not including glycine or proline
# Not a last residue...
NextIndex = Index + 1
if NextIndex >= LastIndex:
return False
... | 500c3a633a27fe47883857b06c4774e131a70a7d | 656,864 |
import os
def check_input(user_input):
""" Checks if the user provided a file or a sequence """
if os.path.isfile(user_input):
# Checks if the input corresponds to an existing file
input_type = 'file'
else:
# Estblishes that the file is a sequence if it is not file
input_t... | 91089f4f1247e051565f69c51eb174c1827dc6e6 | 656,865 |
def register_context_processors(app):
"""
Add template context variables and functions
"""
def base_context_processor():
return {"assetPath": "/static"}
app.context_processor(base_context_processor) | 2a62d678072a73f1223e3c53b8bba5e2299cb001 | 656,866 |
import re
def find_name(soup):
"""find student name"""
name=soup.find("div", attrs={"ng-if": re.compile("selectedParticipant.*!selectedGroup")})
if name is None:
raise RuntimeError("student name not found")
return ' ' .join(name.div.text.split()) | a227176af572c96775c850639917b96490088f8f | 656,867 |
def _fabric_intent_map_name(fabric_name, intent_map):
"""Fabric intent map name.
:param fabric_name: string
:param intent_map: string AR intent map name
:return: string
"""
return '%s-%s' % (fabric_name, intent_map) | 08c10285e128bba1a6f2cff531f1973ae623b11c | 656,868 |
def get_score_list(lines, start_index=0):
"""
:param start_index: Optional index where to start the score checking.
:param lines: List of lines containing binary numbers.
:return: List of scores for each line index, score is +1 for '1' and -1 for '0'
e.g. line '101' gets score [1, -1, 1] an... | fc648f26a78e3614f024b257e54a6025f4341c76 | 656,869 |
def getFingerPrintOnCount(A):
"""
Input:
Iterable having boolean values 0 or 1
Output:
Count of number of 1 found in A
"""
count = 0
for i in A:
if(i == 1):
count += 1
return count | d5cfebcd440826c0502b46e0cc75cc434efb1c7b | 656,870 |
def correctPBCjump(deltaPost, box_size):
"""Correct for possible PBC wrapping of a bead - that would cause a jump in delta cords."""
assert len(deltaPost) == len(box_size)
for i in range(len(deltaPost)):
chalfsize = box_size[i] / 2.0
if deltaPost[i] > chalfsize:
deltaPost[i] = de... | fd00ad8820b489b82baa01337e80a67d9cf11497 | 656,871 |
def mix(color1, color2, pos=0.5):
"""
Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos)
"""
opp_pos = 1 - pos
red = color1[0] * pos + color2[0] * opp_pos
green = color1[1] * pos + color2[1] * opp_pos
blue = color1[2] * pos + color2[2] * opp_pos
... | 62a6c6edd3c69aec77fc0674171c3f49a5cc4de5 | 656,873 |
import inspect
def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
"""
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod | ab6d5c9e0d08be21057b41ce447be60b6bef1ad9 | 656,875 |
def compare_test_prod(sp, st):
"""
dfp: % increase in test over prod counts
"""
dfm = (
sp.to_frame()
.rename(columns={"n": "np"})
.join(st.to_frame().rename(columns={"n": "nt"}))
.fillna(0)
.assign(df=lambda x: x.nt - x.np)
.assign(dfp=lambda x: (x.df / x... | 60287e7150c30c5e290dc1fd258f141ac24605ac | 656,876 |
def fill_matrix(matrix: list[list[int]]):
"""
Return a new list of lists (matrix) where inner lists all have the same
length. Inner lists that are short elements have the element 0 added.
"""
result = []
lengths = [len(row) for row in matrix]
maxlen = max(lengths)
for (i, row) in enumera... | 19f97a46f7e2d7cc0b656a30def55451f7fa0d23 | 656,878 |
from typing import Tuple
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subcla... | 6e5d77854a540e59f657f02e28576409e366739c | 656,879 |
def z_to_seq( z ):
"""Return a 4-element sequence (re, -im, im, re)
Parameter
---------
z : complex
"""
z = complex(z)
re,im = z.real,z.imag
return (re, -im, im, re) | c83bf624de2eabd91c2ec025085452c7d5b7d67a | 656,880 |
def recycling(vs, plankton, nutrient, ratio):
"""Plankton or detritus is recycled into nutrients
Parameters
----------
ratio
Factor for adjusting nutrient contribution. Typically a Redfield ratio.
"""
return {plankton: - vs.recycled[plankton], nutrient: ratio * vs.recycled[plankton]} | 7e5c08240f0d7de3c6dc97dac06a36b968bbe853 | 656,881 |
def milli_2_readadble(msecs):
"""Function: milli_2_readadble
Description: Converts milliseconds into days, hours, minutes and seconds.
Returns values with appropriate tags.
Arguments:
(input) msecs -> Milliseconds.
"""
data = msecs / 1000
seconds = data % 60
data /= 60... | b3d7137b8987321d161b1c8a51e89330a6c15387 | 656,882 |
def design_node_dict_update(design_node_map):
"""
make one level dictionary for design map for easy processing
:param design_node_map: design node map content
:return: dict
"""
d = {}
for item in design_node_map:
if item["DesignNode"] == "Switch-A" and item.get('PhysicalNode'):
... | 5d5ddefd71acc39dbb78cef0135f8483c99db31b | 656,884 |
def fetch(clean, matchSet, session, default):
"""
Takes the values in the existing parameter.
If all the tests in matchset pass, it returns
the object related to it.
if the params in default refer to an instance that exists,
return it!
"""
for keys in matchSet:
cleanCnt = sessio... | e67e22b4043d40092cd1fa05a6750211365c5cb7 | 656,885 |
def macTolist(hexMac):
"""
converts hex MAC string to list
:param hexMax: MAC address to convert (string)
:returns: list of MAC address integers
"""
return [int(i,16) for i in hexMac.split('-')] | bb0215987590f062d90e9354a519e29f6c809869 | 656,886 |
def reaction_splitter(reaction):
"""
Args:
reaction (str) - reaction with correct spacing and correct reaction arrow `=>`
Returns (list):
List of compounds in the reaction
Example:
>>>reaction_splitter("c6h12o6 + 6o2 => 6h2o + 6co2")
['c6h12o6', '6o2', '6h2o... | cd20e8a3e0f15b236d49834b864513f7bbdb99e5 | 656,888 |
import math
import numpy
def rotateZ(nodes, theta):
"""
theta in radians
"""
theta = math.radians(theta)
c = math.cos(theta)
s = math.sin(theta)
T = numpy.array([(c, -s, 0, 0), (s, c, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)])
data = numpy.array([nodes, numpy.ones((nodes.shape.append(1)))])
data = numpy.dot(T, data... | 345c761eb1d866fc5d94de19a4b24a0baa342df9 | 656,889 |
def expand_iupac(base: str, fill_n: bool=False) -> (str):
"""
Expand the IUPAC base
:param base: the IUPAC base to expand
:param fill_n: should we fill N or leave it empty
:return: a string with all the primary
bases that are encoded by the
IUPAC bases
"""
if base =... | 4e8f53ffddceca0eacacd8b7c1a70d22965ff3e3 | 656,890 |
import torch
def simple_diff(frame_true, frame_hat, flow_true, flow_hat, aggregation=False):
"""
"""
assert frame_true.shape == frame_hat.shape
assert flow_true.shape == flow_hat.shape
frame_true = frame_true.squeeze(0).detach()
frame_hat = frame_hat.squeeze(0).detach()
flow_true = flow_t... | 9d96ab878cc5276d0af2b841d883d664e5212a8a | 656,891 |
def es_vocal_if(letra: str) -> bool:
"""Toma un string y devuelve un booleano en base a si letra es una vocal o
no.
Restricción: Utilizar un if para cada posibilidad con la función lower().
Referencia: https://docs.python.org/3/library/stdtypes.html#string-methods
"""
letra = letra.lower()
... | ef66acc012714bc2281155e718b3e30a2052cc60 | 656,892 |
def size(self):
""" Return the size or length of the linked list. """
size = 0
node = self.head
while node:
size += 1
node = node.next
return size | 5d5f1ba5c385946ede96c6a503f310d12af91e7a | 656,893 |
def to_loxone_level(level):
"""Convert the given HASS light level (0-255) to Loxone (0.0-100.0)."""
return float((level * 100) / 255) | 9004c0eaa2ade4c664d30a0c79288d2f11a1362a | 656,894 |
def _getfield(history, field):
"""
Return the last value in the trace, or None if there is no
last value or no trace.
"""
trace = getattr(history, field, [])
try:
return trace[0]
except IndexError:
return None | b81339c94f53aa757e25a115dc0068cb38a58dc9 | 656,895 |
def frequency_difference(frequency_1, frequency_2):
"""Returns a list of tuples containing an n-gram and the difference in
relative frequency between the ironic and non-ironic tweets.
:param frequency_1: A list of n-gram, frequency tuples.
:param frequency_2: A list of n-gram, frequency tuples.
"""... | d1ed9cd87f685a6093f6b94e561183c6749480b7 | 656,896 |
def remove_model_prefix(uid):
"""
Removes the optional model prefix from the given primary ID. For example, given the biosample
record whose primary ID is 8, and given the fact that the model prefix for the Biosample model
is "B-", the record ID can be specified either as 8 or B-8. However, the model pr... | f02012996669367ab3363902ebe692efef116309 | 656,897 |
import os
def get_project_id():
"""Get application project access."""
return os.environ.get('project') | 81ca6fbafded1a88d102e09866314e1234709dac | 656,898 |
import re
def pct_arg_to_int(arg):
"""Parse a numeric string that represents a percentage in units of 0.1%. 1000 == 100%"""
pat = re.compile("[0-9]{4,4}$")
m = pat.match(arg)
if m is None:
raise ValueError(f"Invalid percent string: {arg!r}")
pct = int(m.group(0))
if pct < 0 or pct > 1... | f398377e23b0bbe82b0eb8da05960ef70020f72d | 656,899 |
import pathlib
def themes_dir() -> pathlib.Path:
"""Return the directory where the themes are located."""
here = pathlib.Path(__file__).parent
return here.joinpath('themes') | b7a9868387abe572af6babe9fa0120346914381c | 656,900 |
from math import cos, pi, sqrt
def linear_dist_sphere(radius: float, surf_dist: float, depth_a: float, depth_b: float) -> float:
"""
The purpose of this function is to find the actual, linear distance between the hypocenter of
and earthquake and the bottom of a fracking well. It's a more general proble... | 3439798e11805e5b6d60530211248d8df66cd9a5 | 656,901 |
import numpy as np
def dye_pH_df(x):
"""
pH of sample
% function es = dye_pH_df(x[i,0], x[i,1], x[i,2], x[i,3], x[i,4], x[i,5], x[i,6], x[i,7]),
%- INPUT:
%- 1) Absorbance at 578 nm
%- 2) Absorbance at 434 nm
%- 3) Absorbance at 730 nm
%- 4) Volume of dye added in micro liters
... | 5dfe2555675b08230c88d07451d4938f71c0e85b | 656,902 |
def pad_sequence(seqs, max_len):
"""
填充序列,0
:param seqs: 序列
:return: 返回填充好的序列
"""
padded = [seq + [0] * (max_len - len(seq)) for seq in seqs]
return padded | d448c6ae2a1fe33c8cec12fce3a3cf9578caaf59 | 656,903 |
def is_maximum_in_period(cube):
"""Check if cube contains maximum values during time period."""
for cell_met in cube.cell_methods:
if cell_met.method == 'maximum' and 'time' in cell_met.coord_names:
return True | 5e8253e0ffc97f085fc72263e55cc3afae76b23d | 656,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.