content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def decorator_with_args(decorator_to_enhance):
"""
This is decorator for decorator. It allows any decorator to get additional arguments
"""
def decorator_maker(*args, **kwargs):
def decorator_wrapper(func):
return decorator_to_enhance(func, *args, **kwargs)
return decorator_... | 1af073daf9e9ac9a8834f3a1484bdfa293b1b2bb | 7,951 |
def generate_intervals(nelements):
"""
Generates all possible permutations of lists that access elements from
boths ends of a list without accessing the middle, and one permutation
that accesses ALL elements of a list.
"""
intervals = list()
for i in range(0, nelements):
interval = l... | 06098fbff3342c369b7334e4447cdf9b3ef1a0ab | 7,952 |
import re
def find_subtype(meta_dict):
"""Find subtype from dictionary of sequence metadata.
Args:
`meta_dict` (dict)
dictionary of metadata downloaded from genbank
Returns:
`subtype` (str)
RSV subtype as one letter string, 'A' or 'B'.
"""
subtype = ''
if '... | 130b8ed61f117a786cf5f5ae49fc75e8b074ef2e | 7,953 |
def extract_gff3_fields(primer_info):
"""
The gff3 file is a format to annotate locations on a genome.
The gff3 annotations requires locations on the genome, this was not required for creating the primers.
This function computes these locations and prepares the data for the gff3 file
:param primer_i... | 4e8f0fbfc3bff136b3c03d4a2c35648491d42fba | 7,954 |
from typing import Sequence
from typing import Type
from typing import Union
def unique_fast(
seq: Sequence, *, ret_type: Type[Union[list, tuple]] = list
) -> Sequence:
"""Fastest order-preserving method for (hashable) uniques in Python >= 3.6.
Notes
-----
Values of seq must be hashable!
See... | c41c6b298e52bd3069414206cf9ada4766ea8f4d | 7,955 |
def intersect(s1, s2):
"""
Returns the intersection of two slices (which must have the same step).
Parameters
----------
s1, s2 : slice
The slices to intersect.
Returns
-------
slice
"""
assert (s1.step is None and s2.step is None) or s1.step == s2.step, \
"Only i... | 13841ceddd3bb5c73a29bd4067a751579bc04e9b | 7,958 |
def is_word_guessed(word, guesses):
"""
This function will check if the user has guessed all of the letters in the word.
"""
# Loop through the word.
for letter in word:
# Check if the letter has been guessed.
if letter not in guesses:
# The user has not guessed the letter.
return False
# The user has ... | 7ab3ad07a5588745dc4a9f01dac89c788cc688f5 | 7,959 |
def fitness_function(solution, answer):
"""fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters."""
score =0
for i in range(len(answer)):
score += (abs(solution[i]-answer[i]))
retu... | 059924beb07d0e0e1892783f515061ffcf714d43 | 7,962 |
def adjust_cruise_no(cruise):
"""If shipc should be mapped we map cruise_no as well."""
if len(cruise) > 7:
return '_'.join((cruise[:4], cruise[4:8], cruise[8:]))
else:
return cruise | a83a35cb0a1bad17778f3b39756c431237254a51 | 7,963 |
import argparse
def parse_args():
"""Parse command line arguments.
"""
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg_parser.add_argument('-hca', '--http_cert', default=None,
help='The ca cert of external HTTP Serve... | f2edbc2dbbfdb438198e6f6bb8edba6400982ef0 | 7,964 |
def signature(word: str) -> str:
"""Return a word sorted
>>> signature("test")
'estt'
>>> signature("this is a test")
' aehiisssttt'
>>> signature("finaltest")
'aefilnstt'
"""
return "".join(sorted(word)) | a17e006dcd9f55cfc57d7cd0140489c7be518dc7 | 7,965 |
def getHeaders(lst, filterOne, filterTwo):
"""
Find indexes of desired values.
Gets a list and finds index for values which exist either in filter one or filter two.
Parameters:
lst (list): Main list which includes the values.
filterOne (list): A list containing values to find indexes of in the main list... | 0aa3612b15114b0e0dcdf55eb3643df58157239b | 7,966 |
from typing import Callable
from typing import Any
from typing import Tuple
import inspect
def combine_args_kwargs(
func: Callable[..., Any], *args: Any, **kwargs: Any
) -> Tuple[Any, ...]:
"""
Combine args and kwargs into args.
This is needed because we allow users to pass custom kwargs to adapters,... | 03e5c310462b3d15e3ab69cf6d8717744a95caa4 | 7,967 |
def definers (ioc, name) :
"""Return the classes defining `name` in `mro` of `ioc`"""
try :
mro = ioc.__mro__
except AttributeError :
mro = ioc.__class__.__mro__
def _gen (mro, name) :
for c in mro :
v = c.__dict__.get (name)
if v is not None :
... | f5d90118ca1ad719d47143d0260bfcbda2749124 | 7,969 |
def add_dest(df_conc, dest_labware, dest_start=1):
"""Setting destination locations for samples & primers.
Adding to df_conc:
[dest_labware, dest_location]
"""
dest_start= int(dest_start)
#try:
# dest_labware = dest_labware_index[dest_type]
#except KeyError:
# raise KeyError(... | d3e066148fc07bd5ed47d496d56c39e24062315c | 7,970 |
def top(Q):
"""Inspects the top of the queue"""
if Q:
return Q[0]
raise ValueError('PLF ERROR: empty queue') | 16327db2698fbef4cad1da2c9cb34b71158a2a6c | 7,972 |
def get_valid_handles_domain_only():
"""
Define valid domain handles
"""
return ["cli", "web", "gui", "pub"] | 64dc04fbbecbc442b1fd99279161c04461332a87 | 7,973 |
def qc_board_and_constraints(board, constraints):
"""
Purpose: When the board first comes in, do a check to see if any of the
fixed values are duplicates
@param board The Sudoku board: A list of lists of variable class instances
@param constraints The unallowed values for each cell, list of tuples... | 82c8013c12eda3fd548295be96e713d760587985 | 7,974 |
def spdot(A, x):
""" Dot product of sparse matrix A and dense matrix x (Ax = b) """
return A.dot(x) | b44c9434a42974be54e2c4794b6f063f86836707 | 7,975 |
def translate_user(user):
""" translates trac user to pivotal user
"""
return user | 69a439a12188239a557b69fa9f858473f1509a26 | 7,976 |
import os
def get_target_imagepath(image_path,category_num):
"""
category:
0-userid,
1-isbad,
2-gender: 1 male,0 female,
3-age
"""
basename=os.path.basename(image_path).split(".")[0].split("_")
an=int(basename[category_num])
return an | 131466cea39de6bc1e68b8603c2b065981d3d386 | 7,977 |
def make_snippet(snippets, location):
"""Makes a colored html snippet."""
output = "<br>".join(sentence.replace(
location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets)
return output | 57bebb05df3ae34b45f57e589f6b105425609b8c | 7,981 |
def kid_2():
"""Return a second JWT key ID to use for tests."""
return "test-keypair-2" | c1bbe824ee90470c17ac62cbc3096cff4e3ddb1a | 7,982 |
def move_items_back(garbages):
"""
Moves the items/garbage backwards according to the speed the background is moving.
Args:
garbages(list): A list containing the garbage rects
Returns:
garbages(list): A list containing the garbage rects
"""
for garbage_rect in garbages: # Loop... | 9ffd28c7503d0216b67419009dac6ff432f3b100 | 7,984 |
import re
def _mask_pattern(dirty: str):
"""
Masks out known sensitive data from string.
Parameters
----------
dirty : str
Input that may contain sensitive information.
Returns
-------
str
Output with any known sensitive information masked out.
"""
# DB credenti... | b75ae1e6ea128628dd9b11fadb38e4cbcfe59775 | 7,985 |
def contains_non_ascii_unicode(s):
"""Determine whether the Unicode string 's' contains non-ASCII code-points."""
# Surely there must be a better way to do this? There's nothing I can see in
# the stdlib 'unicodedata' module:
# http://docs.python.org/library/unicodedata.html
#
# Note that list comprehens... | 138d3c298598603f2d0dc24518bbea46a4f8b7e6 | 7,988 |
def __remove_duplicate_chars(string_input, string_replace):
"""
Remove duplicate chars from a string.
"""
while (string_replace * 2) in string_input:
string_input = \
string_input.replace((string_replace * 2), string_replace)
return string_input | 6302bf225fcd5cde822e0640eb7b2c44dcc93fc8 | 7,989 |
import os
import re
def generate_message(username, pr_list):
"""Generates message using the template provided in
PENDING_REVIEW_NOTIFICATION_TEMPLATE.md file.
"""
template_path = '.github/PENDING_REVIEW_NOTIFICATION_TEMPLATE.md'
if not os.path.exists(template_path):
raise Exception(
... | df5538f5d0e47415019977a234f85bedb14bc2c9 | 7,990 |
def clean_data(df):
"""Split the categories column to 36 individual columns and convert their values to 0 / 1.
Drop the original categories column.
Drop duplicated rows.
Args:
df: the dataset
Returns:
DataFrame: the cleaned dataset
"""
# split categories into separate c... | eeeed21b10419f2c3402abecc0710556db979c6c | 7,991 |
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year):
"""Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database."""
formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthd... | 1b4eff67a4073505f9f693f63db6f7c32646bd53 | 7,992 |
import math
def normal_distribution(x: float) -> float:
"""
標準正規分布
f(x) = (1/sqrt(2pi))exp(-x^2/2)
"""
# 係数
coefficient = 1 / math.sqrt(2 * math.pi)
# 指数
exponent = math.exp(-(x ** 2) / 2)
# 標準正規分布
return coefficient * exponent | 2ee740674ddf2a7b95d507aedf1f5453a75f31f1 | 7,993 |
def ceil(number) -> int:
"""
>>> import math
>>> numbers = [-3.14, 3.14, -3, 3, 0, 0.0, -0.0, -1234.567, 1234.567]
>>> all(math.ceil(num) == ceil(num) for num in numbers)
True
"""
return int(number) if number - int(number) <= 0 else int(number) + 1 | 20c3f5cf56cd149e00a76e368729a76012b24375 | 7,994 |
def str_format(s, *args, **kwargs):
"""Return a formatted version of S, using substitutions from args and kwargs.
(Roughly matches the functionality of str.format but ensures compatibility with Python 2.5)
"""
args = list(args)
x = 0
while x < len(s):
# Skip non-start token characters... | addf11c8390c52da7b0f2886d2298bab66a50e49 | 7,996 |
def __private_function_example():
"""This is a private function example, which is indicated by the leading
under scores.
:return: tmp_bool"""
tmp_bool = True
return tmp_bool | be8d0309dc3a52d4f128e2e113046c1c79efe457 | 7,997 |
from typing import Iterable
def any_true(iterable) -> bool:
"""Recursive version of the all() function"""
for element in iterable:
if isinstance(element, Iterable):
if not any_true(element):
return True
elif element:
return True
return False | 67b4ea1e3c9da9c92a2ed8a26f346d67825e62fd | 7,998 |
import math
import numpy
def getMatrix3(eulerdata, inplane=False):
"""
math from http://mathworld.wolfram.com/EulerAngles.html
EMAN conventions - could use more testing
tested by independently rotating object with EMAN eulers and with the
matrix that results from this function
"""
#theta is a rotation about th... | 365b158cd6d5f3150c725a6f8df0d14160168dae | 8,000 |
import json
def unknown_method_request():
"""Sample unknwon/invalid method request for testing purposes."""
return json.dumps(
{
"method": "some_random_method",
"params": {},
}
) | 50fcfda030df632a0d1275bcb55c58e2f80e8c6b | 8,003 |
def pcy(series, n=1):
"""Percent change over n years"""
return (series/series.shift(n*series.index.freq.periodicity)-1)*100 | a18bff66c60bf2620f524e104cf0b9842a85acf4 | 8,005 |
def to_eval_str(value):
"""
Returns an eval(str(value)) if the value is not None.
:param value: None or a value that can be converted to a str.
:return: None or str(value)
"""
if isinstance(value, str):
value = eval(str(value))
return value | 4cb13ad95095b8a6ee494265e600f989d98be05e | 8,006 |
import sys
def _encodehack(s):
"""
:param s: input string
:type s: :class:str or :class:bytes: or :class:unicode
Yields either UTF-8 decodeable bytestring (PY2) or PY3 unicode str.
"""
if sys.version_info[0] > 2:
if type(s) == str:
return s # type(s) is PY... | 471d80c5bf35ade97d82b77eb7d628e86924643f | 8,009 |
def read_float(field: str) -> float:
"""Read a float."""
return float(field) if field != "" else float('nan') | ce6f862c9696e3f84ba20b58a0acdce5c1e212b0 | 8,010 |
def get_trigger_name(operation, source_table, when):
"""Non-PostgreSQL trigger name"""
op_initial = operation.lower()[0]
when_initial = when.lower()[0]
return f"trigger_{source_table}_{when_initial}{op_initial}r" | 4e67005512fee99dd1bf5ed8b5d979e747d27b9f | 8,011 |
def get_deprt(lista):
"""Add together from row with same index."""
base = []
for item in lista:
base.append(item)
resultado = set(base)
return resultado | ecc3026d7674fcd90100db7d0b82cbc4376f1e4e | 8,012 |
def get_dummy_image_name():
"""
Returns the name of the dummy image
"""
return "python-logo.jpeg" | 0a3a3664d06449641eb5ca32e03edd64d31eb63b | 8,013 |
def check_punctuation(words):
"""Check to see if there's a period in the sentence."""
punctuation = [".", ",", "?"]
return [word for word in words if word in punctuation] | 4de89db149924ae3d457e57a3f9edac5dd4ae18a | 8,014 |
from typing import Iterable
from typing import Union
from typing import List
from typing import Tuple
import os
import hashlib
def get_hashed_combo_path(
root_dir: str,
subdir: str,
task: str,
combos: Iterable[Union[List[str], Tuple[str, str]]],
) -> str:
"""
Return a unique path for the given... | b81b5d9d3b17a43daf4023200f7b7e40a26eb21e | 8,016 |
def make_word(parts, sub, i):
"""Replace a syllable in a list of words, and return the joined word."""
j = 0
for part in parts:
for k in range(len(part)):
if i == j:
part[k] = sub
return ' '.join(''.join(p for p in part) for part in parts)
j +=... | 869aa94f60b819b38ad7ddc315b65d862cf525e0 | 8,017 |
import locale
import math
def format_col(df, col_name, rounding=0, currency=False, percent=False):
"""Function to format numerical Pandas Dataframe columns (one at a time). WARNING: This function will convert the column to strings. Apply this function as the last step in your script.
Output is the formatted ... | a049c3a5f0ce28c3ec54ad0988e2679d512c6135 | 8,018 |
def tab_clickable_evt() -> str:
"""Adds javascript code within HTML at the bottom that allows the interactivity with tabs.
Returns
-------
str
javascript code in HTML to process interactive tabs
"""
return """
<script>
function menu(evt, menu_name) {
var i, tab... | bc15f819ef615200d09a356e250bc2d41710b36a | 8,019 |
def validate_input_config(config):
"""Validate that the input source is valid"""
input_manifest_s3_uri = config.get("inputManifestS3Uri")
chain_from_job_name = config.get("chainFromJobName")
if input_manifest_s3_uri and not chain_from_job_name:
return None
if not input_manifest_s3_uri and ... | 4a2788c421225b7c38ec9414285e38d3323ac1ab | 8,020 |
def reverse_complement(string):
"""Returns the reverse complement strand for a given DNA sequence"""
return(string[::-1].translate(str.maketrans('ATGC','TACG'))) | bd033b9be51a92fdf111b6c63ef6441c91b638a3 | 8,022 |
def _parse_seq(seq):
"""Get a primary sequence and its length (without gaps)"""
return seq, len(seq.replace('-', '')) | f02c6f316e3bc56d3d77b6ca6363aa1e0a6b4780 | 8,023 |
def reverse_digit(x):
"""
Reverses the digits of an integer.
Parameters
----------
x : int
Digit to be reversed.
Returns
-------
rev_x : int
`x` with it's digits reversed.
"""
# Initialisations
if x < 0:
neg = True
else:
neg ... | d7358f5778897262b8d57c6dd3e2eb4acb05a2d1 | 8,025 |
def yyyymmdd(d, separator=''):
"""
:param d: datetime instance
separator: string
:return: string: yyyymmdd
"""
month = d.month
if month < 10:
month = '0' + str(month)
else:
month = str(month)
day = d.day
if day < 10:
day = '0' + str(day)
else:
... | a5b765ea9b740ac26b03fd16def62c7d84389e8e | 8,026 |
def ping(value=0):
"""Return given value + 1, must be an integer."""
return {'value': value + 1} | 487902e19decd04f2d1b7a75da6a9ca6bb2714d7 | 8,027 |
def f(x):
"""
Quadratic function.
It's easy to see the minimum value of the function
is 5 when is x=0.
"""
return x**2 + 5 | 7469225fd7d864c96ca957caa51bec924a81d599 | 8,030 |
def dropLabels(events, minPct=.05):
"""
# apply weights, drop labels with insufficient examples
"""
while True:
df0 = events['bin'].value_counts(normalize=True)
if df0.min() > minPct or df0.shape[0] < 3:
break
print('dropped label: ', df0.argmin(), df0.min())
... | cbfc6de91be685d6e5309a490c455badd7596093 | 8,031 |
def hammingDistance(str1, str2):
""" Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`.
Args
---
`str1 : string` The first string
`str2 : string` The second string
Returns
---
`differences : int` The differences between `str1` and `str2`
... | ad35cc79f89171c75a16a13ec6862a2a4abdbd61 | 8,032 |
def pedirOpcion():
"""Pide y devuelve un entero en el rango de opciones validas"""
correcto = False
num = 0
while not correcto:
try:
num = int(input("Elige una opcion -> "))
if num < 0 or num > 3:
raise ValueError
correcto = True
excep... | a758254110e0d39fc8b1b4cab91b95799311fdcf | 8,034 |
from typing import OrderedDict
def _order_dict(d):
"""Convert dict to sorted OrderedDict"""
if isinstance(d, dict):
d = [(k, v) for k, v in d.items()]
d = sorted(d, key=lambda x: x[0])
return OrderedDict(d)
elif isinstance(d, OrderedDict):
return d
else:
raise E... | 94b3e9e0c5b34e466c913c46683c752ca9560a12 | 8,035 |
def display_get_rule_name():
"""display function to prompt for the name of the rule to add"""
return input("Name of the rule to add: ") | e6df6b4df7aecb289d56d65c35de78eb1a8ab591 | 8,036 |
import sys
def in_virtualenv() -> bool:
"""Return True when pype is executed inside a virtual env."""
return (
hasattr(sys, 'real_prefix')
or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
) | 3b7e7b8f21b2a988e0190219c8d26a503929d5af | 8,037 |
import ast
def collect_args(args: ast.arguments):
"""Collect function arguments."""
all_args = args.args + args.kwonlyargs
all_args += [args.vararg, args.kwarg]
return [arg for arg in all_args if arg is not None] | b8fdd180259aadd6a8d31a83503cf7da2b2c0bae | 8,039 |
import shutil
from pathlib import Path
def clean_build():
"""Remove build directory and recreate empty"""
shutil.rmtree("site_build", ignore_errors=True)
build_dir = Path("site_build")
build_dir.mkdir(exist_ok=True)
return build_dir | 121e6ba5f06243654a3a38946a332efae43ce6c2 | 8,040 |
def clean_toc(toc: str) -> str:
"""Each line in `toc` has 6 unnecessary spaces, so get rid of them"""
lines = toc.splitlines()
return "\n".join(line[6:] for line in lines) | 40a22200d04c12865e4bffae9cdd3bdc4ea827be | 8,042 |
import pickle
def pickle_load(file_path):
""" data = pickle_load(file_path)
Load data from a pickle dump file
inputs:
file_path: str, path of the pickle file
output:
data: python object
"""
with open(file_path, 'rb') as file_ptr:
data = pickle.load(file_ptr)
r... | c9112881facc7a6a135893168fa9abf63309b392 | 8,043 |
def versiontuple(v):
"""Return the version as a tuple for easy comparison."""
return tuple(int(x) for x in v.split(".")) | 422d49818e2d6d34d0591c1c450d0c92b7fabc82 | 8,044 |
import re
def find_checksum(s):
"""Accepts a manifest-style filename and returns the embedded
checksum string, or None if no such string could be found."""
m = re.search(r"\b([a-z0-9]{32})\b", s, flags=re.IGNORECASE)
md5 = m.group(1).lower() if m else None
return md5 | f0d9735833e257a3f133d2d51b01775e35408755 | 8,045 |
def sum_up_nums(*nums):
"""(int or float) -> int or float
Adds up as many numbers(separate arguments) as the caller can supply.
Returns the sum of <*nums>
"""
cntr = 0 # Init sum zero
for num in nums:
cntr += num
return cntr | 8ed03f16d624ea24a90a20d42df30328b119edd7 | 8,046 |
def get_expts(context, expts):
"""Takes an expts list and returns a space separated list of expts."""
return '"' + ' '.join([expt['name'] for expt in expts]) + '"' | 76cd216662a6f7a248b70351f79b52e3c47871aa | 8,048 |
def create_filename(last_element):
"""
For a given file, returns its name without the extension.
:param last_element: str, file name
:return: str, file name without extension
"""
return last_element[:-4] | 3faaf647ed6e3c765321efb396b2806e7ef9ddf9 | 8,050 |
from typing import Union
def is_number(value: Union[int, str]) -> bool:
"""
Is thing a number
"""
return isinstance(value, int) or (isinstance(value, str) and value.isnumeric()) | e69de261a45398eb970c00e9a5997a615c6fc7e6 | 8,051 |
def normalization(vector):
"""
Normalize scores in this vector
"""
x = vector[vector>0]
beta = x.quantile(0.9)
updated_vector = vector/beta
return updated_vector | dfe403e8ec73ca3fab5492ce42a6390f1963f840 | 8,052 |
import os
import sqlite3
def get_default_db():
"""Get the default database for the crawler.
Returns:
DB API v2 compliant connection to the crawler's default database.
"""
parent_dir = os.path.dirname(os.path.realpath(__file__))
loc = os.path.join(parent_dir, 'articles.db')
return sqli... | 77c589ecb51379fff937c84579e8a30313352b29 | 8,054 |
import os
def dispatch_repl_commands(command):
"""Execute system commands entered in the repl.
System commands are all commands starting with "!".
"""
if command.startswith('!'):
os.system(command[1:])
return True
return False | 96b7f7783c8579b2717fef2a160094bf2e7dc86e | 8,055 |
def simplify_numpy_dtype(dtype):
"""Given a numpy dtype, write out the type as string
Args:
dtype (numpy.dtype): Type
Returns:
(string) name as a simple string
"""
kind = dtype.kind
if kind == "b":
return "boolean"
elif kind == "i" or kind == "u":
return "in... | c2370b2a08e58c9614ca43e3f14864782eef4100 | 8,056 |
def GetNetworkPerformanceConfig(args, client):
"""Get NetworkPerformanceConfig message for the instance."""
network_perf_args = getattr(args, 'network_performance_configs', [])
network_perf_configs = client.messages.NetworkPerformanceConfig()
for config in network_perf_args:
total_tier = config.get('total... | 2b2f0773fb01b7bbcda30af38d03ed845331f10c | 8,057 |
def OpenFace(openface_features, PID, EXP):
"""
Tidy up OpenFace features in pandas data.frame to be stored in sqlite
database:
- Participant and experiment identifiers are added as columns
- Underscores in column names are removed, because sqlite does not like
underscores in column names.
... | 684e74c159a3551e3fd6d9a80b134c2474759056 | 8,059 |
def check_issue(name, checks, controls):
"""
Checks if a certain RWT issue needs to be suggested.
Returns: list
"""
rwt = []
is_issue = False
total_reasons = []
total_offenders = []
for check in checks:
for control in controls:
if control != []:
f... | 7e16b5d7fe2e674a4e91ccec70ca6a5f47784c49 | 8,060 |
def get_binary_result(probs):
"""
将预测结果转化为二分类结果
Args:
probs: 预测结果
Return:
binary_result: 二分类结果
"""
binary_result = []
for i in range(len(probs)):
if float(probs[i][0]) > 0.5:
binary_result.append(1)
elif float(probs[i][0]) < 0.5:
binary... | df0375b05abe2807a1568133f8ed0aa4a5fe3736 | 8,061 |
def _load_transforms():
"""
Load the transform pairs into the module level variable for later lookup.
Returns
-------
:class:`dict`
"""
return {
f: (globals().get(f), globals().get("inverse_{}".format(f)))
for f in globals().keys()
if "inverse_{}".format(f) in global... | 45ef7c50aee54e6daa344809e603f7abf7bbe836 | 8,062 |
import copy
def deep_merge_dict(base, priority):
"""Recursively merges the two given dicts into a single dict.
Treating base as the the initial point of the resulting merged dict,
and considering the nested dictionaries as trees, they are merged os:
1. Every path to every leaf in priority would be re... | 5c527f45d4ddee00f1e905b09165bcd3551412f6 | 8,063 |
def get_convert_label_fn(odgt):
"""
A function that converts labels to expected range [-1, num_classes-1] where -1 is ignored.
When using custom dataset, you might want to add your own function.
"""
def convert_ade_label(segm):
"Convert ADE labels to range [-1, 149]"
return segm - 1... | dd87a1cc889faf5874eaec45db51804b20fb46ff | 8,064 |
def _get_span(s, pattern):
"""Return the span of the first group that matches the pattern."""
i, j = -1, -1
match = pattern.match(s)
if not match:
return i, j
for group_name in pattern.groupindex:
i, j = match.span(group_name)
if (i, j) != (-1, -1):
return i, j
... | 8feec723d5a09e70f000c6fcdf58269dd6ea9330 | 8,065 |
from pathlib import Path
def guess_format(path):
"""Guess file format identifier from it's suffix. Default to DICOM."""
path = Path(path)
if path.is_file():
suffixes = [x.lower() for x in path.suffixes]
if suffixes[-1] in ['.h5', '.txt', '.zip']:
return suffixes[-1][1:]
... | 70f463ef28adc2c65346ec8b5b87294494a9ee0f | 8,066 |
import numpy
def cartesian_to_polar(u, v):
"""
Transforms U,V into r,theta, with theta being relative to north (instead of east, a.k.a. the x-axis).
Mainly for wind U,V to wind speed,direction transformations.
"""
c = u + v*1j
r = numpy.abs(c)
theta = numpy.angle(c, deg=True)
# Convert... | ee35ca5d5201b10e31b6f0eea0471b0b97ada5fb | 8,067 |
def get_samples(profileDict):
"""
Returns the samples only for the metrics (i.e. does not return any
information from the activity timeline)
"""
return profileDict["samples"]["metrics"] | 06b273e7499e9cb64e38b91374117de6bd3f6c3e | 8,069 |
def dobro(n):
"""
Dobrar número
:param n: número a ser dobrado
:return: resultado
"""
n = float(n)
n += n
return n | fe17270b7a3373545986568657cf6755dc88638f | 8,070 |
def aoi_from_experiment_to_cairo(aoi):
"""Transform aoi from exp coordinates to cairo coordinates."""
width = round(aoi[1]-aoi[0], 2)
height = round(aoi[3]-aoi[2], 2)
return([aoi[0], aoi[2], width, height]) | 40986aeaf5bb1e5d8295289ce310b4c7cf7f4241 | 8,071 |
def rec_dfs_edges(graph):
""" recursive way for above
Note: a-b and b-a are different in this case..
"""
nodes = graph.nodes # type: dict
visited = set()
start = list(nodes.keys())[0]
edges = []
def _rec_dfs(graph, _start, _nodes):
for _node in nodes:
if _node in vi... | c4801cb45d09602cef65f20d5612d8c0e0fc8a49 | 8,072 |
def palindromic(d):
"""Gets a palindromic number made from a product of two d-digit numbers"""
# Get the upper limit of d digits, e.g 3 digits is 999
a = 10 ** d - 1
b = a
# Get the lower limit of d digits, e.g. 3 digits is 100
limit = 10 ** (d - 1)
for x in range(a, limit - 1, -1):
... | d4324d6c2de3dff46e14b754627bb551e03e957f | 8,073 |
import sys
def getArguments():
"""
Get argumments from command-line
If pass only dataframe path, pop and gen will be default
"""
dfPath = sys.argv[1]
if(len(sys.argv) == 4):
pop = int(sys.argv[2])
gen = int(sys.argv[3])
else:
pop = 10
gen = 2
return dfPa... | cc1248746a82bed597c2cc5564b35a9a241f9360 | 8,074 |
import requests
import os
import tarfile
def status(jobid, results_dir_path=None, extract=False, silent=False,
host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest",
jpred4="http://www.compbio.dundee.ac.uk/jpred4"):
"""Check status of the submitted job.
:param str jobid: Job id.
... | 98931b8af31cea66c602fa5c6a48a58c2f5a42e0 | 8,075 |
def markup(pre, string):
"""
By Adam O'Hern for Mechanical Color
Returns a formatting string for modo treeview objects.
Requires a prefix (usually "c" or "f" for colors and fonts respectively),
followed by a string.
Colors are done with "\03(c:color)", where "color" is a string representing a
... | 7ef910aa3b057e82c777b06f73faf554d9c4e269 | 8,079 |
def response2dict(response):
"""
This converts the response from urllib2's call into a dict
:param response:
:return:
"""
split_newlines = response.split('\r\n')
split_tabs = [s.split('\t') for s in split_newlines if s !='']
return split_tabs | d0bcfaca4ed00c74a1a10838881dac8e80f5d479 | 8,080 |
from bs4 import BeautifulSoup
def get_person_speech_pair(file_name):
"""
XML parser to get the person_ids from given XML file
Args:
file_name(str): file name
Returns:
person_id_speech_pair(dict): Dict[person_id(int) -> speech(str)]
"""
person_id_speech_dict = dict()
with op... | 0751ed8d46c39027c0503dcd94d8c324c700c1a5 | 8,084 |
import pandas
def get_df(a: int) -> pandas.DataFrame:
"""
Generate a sample dataframe
"""
return pandas.DataFrame(data={"col1": [a, 2], "col2": [a, 4]}) | 56008e78d68110e8f12463b37368d0be7f3e4c9a | 8,085 |
import os
def random_key_generator(key_length):
"""
Creates a random key with key_length written
in hexadecimal as string
Paramaters
----------
key_length : int
Key length in bits
Returns
-------
key : string
Key in hexadecimal as string
"""
return bytes... | 80c8e9e6949cfd1e5ead274c0b89bc0d40e1f926 | 8,086 |
from datetime import datetime
def utc2local(utc_dtm):
"""
UTC 时间转本地时间( +8:00 )
:param utc_dtm:
:return:
"""
local_tm = datetime.fromtimestamp(0)
utc_tm = datetime.utcfromtimestamp(0)
offset = local_tm - utc_tm
return utc_dtm + offset | 0070c3ae1e37071cbf57806ca18576f81abb64e0 | 8,087 |
def get_hash_hex(raw_hash):
"""Creates a nice hex representation of a raw req"""
return raw_hash.encode('iso-8859-1').encode('hex') | a7c0e873617cae2481fecc32a2051ad1fc6a9519 | 8,088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.