content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from io import StringIO
import contextlib
def format_check(file_or_dir):
"""Perform format and return True if changes were made (False otherwise)."""
capture = StringIO()
with contextlib.redirect_stderr(capture):
format(file_or_dir)
output = capture.getvalue()
made_changes = any(["file ref... | c3e17c4c45ca05ee2a67614d444b89a1fbd4c489 | 629,988 |
from typing import Iterable
import functools
import operator
def _prod(vs: Iterable[float]) -> float:
"""Product function."""
return functools.reduce(operator.mul, vs, 1) | a5339920abe99d190579e06102e1ae6831380093 | 629,990 |
def sizeof_fmt(size, binary=True, separator=' ', suffix='B', digits=2):
"""
takes a *size* (in bytes) and convert it in a human readable format.
:param size: size in bytes
:param digits: amount of decimals for any number
:param binary: `True` for binary (:math:`2^x`) or `False` for decimal (:math:`... | e98f4783e85388a7695e5a8b5d527b1cb63cdd66 | 629,992 |
def sort_numbers(nums):
"""
Sorts an array of numbers.
:param nums: array of integers.
:return: sorted array.
"""
if nums:
return sorted(nums)
return [] | 2c3785cddc275f8d1cf5f66e0ef95e1f8841a8cc | 629,995 |
def split_array_half(array):
"""
Splits an array like object in half, into two arrays.
If of an odd length, the first half will be larger by 1.
:param array: array like object to be split in half
:return: Two arrays (first_half and second_half)
"""
midpoint = len(array) // 2
first_half ... | 8d69e738b51740966bb35b45cc502129d0e5548d | 629,998 |
def clean_stix_data(data):
""" Clean stix data from unwanted characters """
return data.replace("\n", "")\
.replace("{", "{{")\
.replace("}", "}}")\
.replace("”","\"")\
.replace("“","\"") | 0f2a73012e25b103f24292a1722f11139217657a | 630,000 |
def contains_no_complete_reductions(reductions):
"""Checks whether reductions contains a reduction with the empty word."""
for reduction in reductions:
if reduction[-1] == "":
return False
return True | 7fc3b6f032762d238861839d2b10ca9873ee0884 | 630,001 |
import copy
def clone(obj):
"""Clone the object
@param obj: object to be cloned
@return object cloned.
"""
return copy.copy(obj) | d0b2ac2fed8e26a42f72da7e154d3f8a021e4709 | 630,010 |
def quaternionMsgToTuple(msg):
"""Helper function for converting a quaternion msg to a tuple"""
return (msg.x, msg.y, msg.z, msg.w) | a80c72ea4beea3a58be15f101a56c8b5e6248eb6 | 630,012 |
def _do_magick_convert_enlighten_border(width, height):
"""
Build the command line arguments to enlighten the border in four regions.
:param int width: The width of the image.
:param int height: The height of the image.
:return: Command line arguments for imagemagicks’ `convert`.
:rtype: list
... | 314fefe6c78fa865d82d2f7ec33709ad2b41fe52 | 630,013 |
from typing import Union
def any_to_int(any: Union[None, str]) -> int:
"""
Convert int string to integer. if this value is `None`, return `0`
Args:
any (Union[None, str]): value to convert
Returns:
int: converted integer
"""
if any is None:
return 0
return int(any) | 64ee3bd2efd610132d1a44c9bf7caa531b0869e3 | 630,016 |
def args_dict_split(all_arguments):
"""
This functions split the super set of arguments to smaller dictionaries
all_arguments: Dictionary
All input arguments parsed
return: Dictionary, Dictionary, Dictionary
We return four dictionaries for init, script, spark arguments, singlenode arguments
... | 109b328f3f3495952fc820a53b76f0a915acfbf8 | 630,018 |
def fake_urldelete(c_client, url, headers):
"""
A stub delete_status() implementation that returns True
"""
return True | 8c2a24b618ea1be5376a0fd2af3659ab4b1054f5 | 630,019 |
def fn1Test(string, outputFile):
"""
Function appends the next character after the last character in the given
string to the string, writes the string to a file, and returns it. For
example, if string is "AB", we will write and return "ABC".
"""
rV = string + chr(ord(string[-1]) + 1)
with o... | 5f292d3383e9efb1a38f20cf8a5ac9dd71cd914a | 630,020 |
def _get_attention_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [False, [False, True], [True, False], False],... | 8d3f3faf19883b36b7b1fc2535f688132acec5f7 | 630,022 |
def load_sum(sum_file):
"""
*.sum file is the catalog summary file after Hyperinverse.
This function returns a dict:
-key is event id
-value is an array with below component:
--Str format event time "yyyymmddhhmmss**", also the event folder.
--event longitude
... | e7488c70f9eab35f52b4884c365497c529ca500e | 630,024 |
def echo(**kwargs):
"""Can take any keyword argument and prints its name and value"""
for k, v in kwargs.items():
print('**', k, '=', v)
return kwargs | 74a417cddfbd1962f52a6503715688bf3c20874a | 630,025 |
from datetime import datetime
def parse_datetime(s, fmt='%Y%m%d%H%M%S'):
"""
>>> parse_datetime('20170403153428')
datetime.datetime(2017, 4, 3, 15, 34, 28)
>>> parse_datetime('2017-04-03T15:34:28', fmt='%Y-%m-%dT%H:%M:%S')
datetime.datetime(2017, 4, 3, 15, 34, 28)
"""
return datetime.strp... | cfbd9303e25554cd24897162b2c87b9a957c3a44 | 630,026 |
def _str_to_bool(string):
"""
Converts command line boolean string to python boolean
:param string: The command line string
:return: The boolean interpretation of the string
"""
return string.lower() in ("yes", "true", "t", "1") | 5428bd1bf1b05ccec6613ecf382bac3399009cec | 630,028 |
def go_environment_vars(ctx):
"""Return a map of environment variables for use with actions, based on
the arguments. Uses the ctx.fragments.cpp.cpu attribute, if present,
and picks a default of target_os="linux" and target_arch="amd64"
otherwise.
Args:
The skylark Context.
Returns:
A dict of envir... | fd22dfa05d3601143193835c7f1ea26ff9aac8b2 | 630,030 |
import re
def _triple_under_to_dots(astring):
"""Convert all instances of '___' to '.'."""
return re.sub(r'___', '.', astring) | 4601813747dd9d06401e28ffd6c5703a86c0d74a | 630,031 |
def generate_codex(lexicon, inverse_codex=False):
"""
Given a list of words, creates a codex of unique numeric keys assigned to the words.
Example:
input: ['boy', 'apple', 'dog', 'cat']
output: {'apple': 0, 'boy': 1, 'cat': 2, 'dog': 3}
Input:
lexicon: (list) List of strings, c... | 3d7cd7eb67d85ee1536f2daa45481224287e7386 | 630,032 |
import math
def LinEx(y: int, est: int):
"""
A function that return the error for a given estimation of the number of calls
:param y: truth
:param est: estimation (ŷ in the folowing formula)
:return: LinEx(y, ŷ) = exp[α(y − ŷ)] − α(y − ŷ) − 1
"""
alpha = 0.1
prod = alpha * (y - est)
... | 469c23fd3d732ff7cba9778afef137492b10ea65 | 630,035 |
import copy
import random
def nx_color_spread(init_pt, graph,maxtsteps):
""" Function to perform the random simulation of spreading the GHZ state on
a weighted graph
Parameters
----------
init_pt, any type:
Label for the initial point we are spreading from. Should be present in
th... | 7602912060402feca5ff69bbd56f685a6c5dc1fd | 630,036 |
def AZ2pdg(A, Z):
"""Conversion of nucleus with mass A and chage Z
to PDG nuclear code"""
# 10LZZZAAAI
pdg_id = 1000000000
pdg_id += 10*A
pdg_id += 10000*Z
return pdg_id | 3dfd4dc46d57d92ed18fb7911b1679e80b557fb2 | 630,038 |
import torch
def farthest_point_sample(x, npoint):
"""
Input:
xyz: pointcloud data, [B, N, C]
npoint: number of samples
Return:
centroids: sampled pointcloud data, [B, npoint, C]
"""
B, N, C = x.shape
S = npoint
y = torch.zeros(B, S, C).cuda()
distance = torch.o... | 6d79458253d0242e87b11ddf3f172269af2a71f5 | 630,046 |
import inspect
def _get_frame_args(frame):
"""Get the formatted arguments and class (if available) for a frame"""
arginfo = inspect.getargvalues(frame)
try:
if not arginfo.args:
return '', None
# There have been reports from the field of python 2.6 which doesn't
# return a na... | 268631995c8c0b48b74728ed5fba7951b91b1f8c | 630,049 |
def attribute(key, value):
"""
Makes an attribute for lxml.
"key"="value"
:param str key: key of the attribute
:param str value: value of the attribute
:return dict attr: attribute for lxml
"""
attr = {key: value}
return attr | 1134c1e8e13b1cea554cd9d4c3d459eb582fa6aa | 630,051 |
from textwrap import dedent
def map_strings_to_line_numbers(module):
"""
Walk ``module.ast``, looking at all string literals. Return a map from
string literals to line numbers (1-index).
:rtype:
``dict`` from ``str`` to (``int``, ``str``)
"""
d = {}
for field in module.block.string... | 29733d59f48ff92b893cb9bcc2826addba0b06e9 | 630,053 |
def _match_authorizables(base_authorizables, authorizables):
"""
Method to check if authorizables (entity in CDAP) is contained (the children) of base_authorizables
If so, base_authorizables should be exactly the same as the leading part of authorizables
:return: bool: True if match else False
"""
return au... | 3af027793c3e39600f74a97216a3566b69ff6213 | 630,054 |
def processor(document: dict) -> dict:
"""
The default document processor for job documents. Transforms projected job documents to a structure that can be
dispatches to clients.
1. Removes the ``status`` and ``args`` fields from the job document.
2. Adds a ``username`` field.
3. Adds a ``create... | 5471be9ed0ae4d5fd20d0172b7d0411ff5337f88 | 630,059 |
def is_solvable_seed(seed):
"""Returns True if the given seed would generate a solvable pirellone instance, False otherwise."""
# We reserve those seed divisible by 3 to the NOT solvable instances
return (seed % 3) != 0 | 8ea7a6e7f0b859a09217bba1fc71bbd40f38b391 | 630,062 |
def clean_string(string: str) -> str:
"""
Removes control characters from a string.
>>> clean_string('This is a sentence\\r with newline.')
'This is a sentence with newline'
>>> clean_string('')
''
>>> clean_string(' This is a sentence\\r with. newline. ')
'This is a sentence with. n... | 55d6be1d4b3c47ca38a6dcbd300c755f8c7090c1 | 630,065 |
import sqlite3
def fetch_naming_prefix(database):
""" Get naming prefix from the database run_info table """
conn = sqlite3.connect(database)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT value FROM run_info WHERE item = 'idprefix'")
prefix = cursor.fetchone()[0]... | 5a61bc6863c42b88abafc5211c1b51970ae8d44f | 630,070 |
def call_sig(args, kwargs):
"""Generates a function-like signature of function called with certain parameters.
Args:
args: *args
kwargs: **kwargs
Returns:
A string that contains parameters in parentheses like the call to it.
"""
arglist = [repr(x) for x in args]
arglist... | a66af732966f5bfc613d105076363424891aaa90 | 630,071 |
import cmath
def is_integral(x):
"""Return whether the argument is equal to its integer part."""
if isinstance(x, complex):
if x.imag:
return False
x = x.real
return not cmath.isinf(x) and not cmath.isnan(x) and x == int(x) | 33cb18f84b9778c56e7df1b601458f2404f9075a | 630,073 |
def parse_claim(claim):
"""
Parse a line of input
Example claim:
#1 @ 861,330: 20x10
"""
tokens = claim.split(" ")
claim_id = int(tokens[0][1:])
(offset_x, offset_y) = tokens[2].split(',')
offset_x = int(offset_x)
offset_y = int(offset_y[:-1])
(width, height) = tokens[3].sp... | d534e204f88841b0dfd34c0501cb2dfb545c4fd4 | 630,075 |
import ast
def matches_attr(node, name):
"""Determines if the ``ast.Call`` node points to an ``ast.Attribute`` node with a matching name.
Args:
node (ast.Call): a node that represents a function call. For more,
see https://docs.python.org/3/library/ast.html#abstract-grammar.
name ... | fe76ee845fabc965ba15475c2a6c4098cbeae221 | 630,078 |
def delete_comma(value):
""" Returns a string without its final comma."""
items = value.split(',')
last = items.pop()
return '%s%s' % (','.join(items), last) | 2ddd68851d8cae7883e1ef3802ae07ad08fcfaaf | 630,080 |
import pprint
def _get_column_index(i, inputs):
"""
Taken from https://github.com/onnx/sklearn-onnx/blob/9939c089a467676f4ffe9f3cb91098c4841f89d8/skl2onnx/common/utils.py#L50.
Returns a tuples (variable index, column index in that variable).
The function has two different behaviours, one when *i* (col... | 016cdcee266f36dcaad6a96788d3899348f4155c | 630,088 |
import networkx
def walls_to_graph(walls):
"""Return a networkx Graph object given the walls of a maze.
Parameters
----------
walls : list[(x0,y0), (x1,y1), ...]
a list of wall coordinates
Returns
-------
graph : networkx.Graph
a networkx Graph representing the free squ... | eccfd3d9ca582ee4eafe9cb385c252277b52c3b7 | 630,090 |
def dict2xml(dictionary, root="topsApp", topcomp="topsinsar"):
"""Convert simple dictionary to XML for ISCE."""
def add_property(property, value):
xml = f" <property name='{property}'>{value}</property>\n"
return xml
def add_component(name, properties):
xml = f" <componen... | 76c3cbd64e1118da0391be40448a42990a83cf15 | 630,093 |
def build_args_stdio(settings):
"""Build arguments for calling pylint.
:param settings: client settings
:type settings: dict
:return: arguments to path to pylint
:rtype: list
"""
pylint_args = settings.get('args')
if pylint_args is None:
return []
return pylint_args | 0a1c7fd036220a8cc2c03091f21d742bd3758d77 | 630,095 |
def _list_to_index_dict(lst):
"""Create dictionary mapping list items to their indices in the list."""
return {item: n for n, item in enumerate(lst)} | 38d8b9a963ebdd40b8f14b3052937e3450853fab | 630,097 |
import random
import string
def random_id(length=5):
"""Generate a random ID of 5 characters to append to qsub job name."""
return ''.join(random.sample(string.ascii_letters + string.digits, length)) | c69c5f50e8a913b67eed1f9449b992f87f976552 | 630,099 |
import json
def intrinsics(kinect, path='calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json', write=False):
"""
Retrieve the depth camera intrinsics from the kinect's mapper
and write them at: calibrate/IR/intrinsics_retrieved_from_kinect_mapper.json
:param kinect: kinect instance
:param pa... | 811b4128090a7015d297a0bd85432ad321369e99 | 630,100 |
import requests
def connection_ok(base_url):
"""Check whetcher connection is ok
Post a request to server, if connection ok, server will return http response 'ok'
Args:
none
Returns:
if connection ok, return True
if connection not ok, return False
Raises:
none
... | b4d6bdfe2ec8d511238a65ef359abfbed0b5f86a | 630,101 |
def _display_time(seconds: float, granularity=2) -> str:
"""Return a human readable instruction for some time duration.
Copy and pasted from:
https://stackoverflow.com/questions/4048651/python-function-to-convert-seconds-into-minutes-hours-and-days/4048773
If the number is positive, it returns the tim... | 98ea02ab39ca4394ca15a3e622e0e6df21ccd594 | 630,106 |
import random
import copy
def partition(n,m,minQuota,maxQuota):
"""
Function to partion a particular integer.
Parameters:
n (int) - the number we want to partition.
m (int) - the number of blocks we want.
minQuota (int) - the minimum size of a block.
maxQuota (int) - the m... | 73587a6c4544be9c282d94027c18299bcf29adfc | 630,107 |
def PPV_OR(odd_ratio, power, alpha, verbose=True):
"""
returns PPV from odd_ratio, power and alpha
parameters:
-----------
odd_ratio: float
P(H_A)/(1-P(H_A))
power: float
Power for this study
alpha: float
type I risk of error
Returns:
----------
... | 50f0a18a5b45d7e4d7621fb1ea0c61c7a74cc55d | 630,108 |
def split_by_link(data):
"""
splits PTCF information by link ids (e.g. "ds1_1-ds2_1") to store the data under a given key for easier access (-> focus-on-hover!)
:param data: ptcf data frame
:return: PTCF split by link
"""
split_data = {}
data['cluster_id'] = data['ds1_cluster'] + "-" + data['ds2... | 1d16658057900702c9d367dec2ec11826a217177 | 630,109 |
def extractStationsFromFile(stations_file):
"""
Reads file and extracts stations to a list.
"""
df = open(stations_file)
station_ids = df.read().split()
df.close()
return station_ids | 2d38092fa4afaf91f0de4fd9a5b3e3cbfc65c98b | 630,110 |
def create_violin_plot(df, columns, title):
"""
This method will create violin plots given a DataFrame and columns.
Args:
df (pandas.DataFrame): data that will be displayed
columns (list): list of columns
title (str): violin plot title
Returns:
... | fbe4008b811aa126143f0175da034af5c592e005 | 630,112 |
def safe_ord(character):
"""
Ethereum RLP Utils:
Returns an integer representing the Unicode code point of the character or int if int argument is passed
:param character: character or integer
:return: integer representing the Unicode code point of the character or int if int argument is passed
... | 1a5a1f1c1a758fe3211dbe94caaa70bda9df2534 | 630,117 |
def from_bar(bar):
"""
Generate DbBarData object from BarData.
"""
db_bar = dict(
index = bar.datetime,
volume = bar.volume,
open_int = bar.open_interest,
open = bar.open_price,
high = bar.high_price,
low = bar.low_price,
close = bar.close_price
... | eacb71333234f80bcc3d73264798f928ca1052e6 | 630,120 |
def _lookup_enum_in_ns(namespace, value):
"""Return the attribute of namespace corresponding to value."""
for attribute in dir(namespace):
if getattr(namespace, attribute) == value:
return attribute | 542228608ee601220e9993d073f14dc430c9a8e6 | 630,123 |
def is_instance_or_subclass(x, cls):
"""Return True if ``x`` is either a subclass or instance of ``cls``."""
try:
return issubclass(x, cls)
except TypeError:
return isinstance(x, cls) | 278c6c885b96f2f2acc37662c6a9091f90ef7b6a | 630,124 |
def is_host(ip):
"""
Checks whether an address is a subnet address or a single address
:param ip: ip address or subnet
:return: True if host
"""
r = ip.split("/")
if len(r) > 1:
return False
return True | 2daf11ce81376a1045d11241ffb62e50e1b45817 | 630,128 |
def get_ssa_def(mlil, var):
""" Gets the IL that defines var in the SSA form of mlil """
return mlil.ssa_form.get_ssa_var_definition(var) | 56953dc0d2cbd76d06134322692e3f7e37f00800 | 630,129 |
def __getmappinglabel__(mapping, value):
"""
Gets index of label value in mapping.
:param mapping: mapping dictionary
:param value: value for which the mapping is searched for
:return: index of value in mapping
"""
if value in mapping["labels"]:
return mapping["labels"].index(value)
... | e6911d789cb61064fbd2a286ec659bc48e49bc98 | 630,130 |
def _strip_frbr_section_from_pnx(pnx_xml):
""" We must strip the frbr section from a PNX record before re-inserting it """
for frbr_section in pnx_xml.findall('frbr'):
pnx_xml.remove(frbr_section)
return(pnx_xml) | bcc3f45a0cf8f787602c9b3d861ad8c69d2c198d | 630,132 |
def IsInRangeInclusive(a, low, high):
"""
Return True if 'a' in 'low' <= a >= 'high'
"""
return (a >= low and a <= high) | 08729cc281c3465e37d9e52b1b31935fcd713288 | 630,141 |
def qualify(name, prefix):
"""
Qualify a property name with the given prefix
"""
return "{prefix}:{name}".format(name=name, prefix=prefix) | a32cc1b7544220364eeb74005ed856cf2570619c | 630,143 |
def get_dataset_features(dataset):
"""
Takes in the name of a dataset and returns the relevant parameters
"""
groups_to_drop = []
if dataset == 'COMPAS':
path = 'datasets/compas-scores-two-years.csv'
label = 'two_year_recid' # binary
group = 'race' # 'sex' also an option
... | 1dc0793b4f398c8f8bc88d8c9a6bea5090b41354 | 630,146 |
import string
def preprocess_article(text):
""" Changes an articles text to lowercase, removes punctuation """
return text.encode('ascii', 'ignore').lower().replace("\n", "").translate(None, string.punctuation) | b3a67951ef9c66e7b77041ce2fa0cb7a0223bca6 | 630,147 |
def _break(s, find):
"""Break a string s into the part before the substring to find,
and the part including and after the substring."""
i = s.find(find)
return s[:i], s[i:] | fd4ec716795c971194ffe692682e0dd9f7701fd3 | 630,152 |
import re
from typing import List
def find_arxiv_id(string: str) -> str:
"""
Try to extract an arxiv id from a string.
Looking for one of two forms:
1. New form -- 1603.00324
2. Old form -- hep-th/0002839
Parameters
----------
string : str
String in which to perform t... | a9385980cdbb932fe4c3255c0a00b5bf5555a0bf | 630,158 |
from typing import Union
def soring_date2target(sorting_date: Union[int, float]) -> int:
"""Convert `sorting_date` to `target`.
If `sorting_date` <= 1600 then `target` is 0.
If 1600 < `sorting_date` <= 1700 then `target` is 1.
If 1700 < `sorting_date` <= 1800 then `target` is 2.
If 1800 < `sortin... | 83fb60e99b08579e63d1d6f52d25e4a9991c41a7 | 630,160 |
def _all_in_set_(cands, s):
"""
Test if all elements of 'cands' are in set 's'
"""
if len(cands) == 0:
return False
for c in cands:
if not c in s:
return False
return True | 07ffa7d6d10fe60313c6308374b55802ea9c5ea5 | 630,168 |
def is_post(request):
"""Check request is a POST"""
return request.method == 'POST' | fab3cc2205db7555978fd3e56b404976f89b11b7 | 630,171 |
def increment_bytes(val: bytes) -> bytes:
"""increment a bytes value"""
length = len(val)
int_val = int.from_bytes(val, byteorder="big")
int_val += 1
return int_val.to_bytes(length, byteorder="big") | 4b826322bd63e02e4df38ec2916911e8d6af5e70 | 630,174 |
import torch
def load_state(filename):
"""
Loads the PyTorch files saved at ``filename``, converting them to be
able to run with CPU or GPU, depending on the availability on the machine.
"""
if torch.cuda.is_available():
return torch.load(filename)
else:
return torch.load(filen... | 0ec77e2ab4aae2d54f84ebe37f68487650dcd70e | 630,179 |
def butlast(thing):
"""
BUTLAST wordorlist
BL wordorlist
if the input is a word, outputs a word containing all but the last
character of the input. If the input is a list, outputs a list
containing all but the last member of the input.
"""
if isinstance(thing, str):
return thin... | 4f59c38dc8e79c6d3690ba1b645a3b21ba2c01b1 | 630,185 |
from typing import List
from typing import Tuple
import random
def get_noises(trajectory_len: int, noise_magnitude: float, random_seed: int) -> List[Tuple[float, float]]:
""" Get `trajectory_len` noise values where each noise value is a tuple (noise_0, noise_1),
noise_i is a Gaussian white noise generated fro... | 576fbcdb2996cccfcedf064cf378484f39981b5f | 630,186 |
def bsuccessors(state):
"""Return a dict of {state:action} pairs. A state is a (here, there, t) tuple,
where here and there are frozensets of people (indicated by their times) and/or
the light, and t is a number indicating the elapsed time."""
here, there, t = state
if 'light' in here:
retu... | fa1a585248579a498b0324600217d1616f825a07 | 630,187 |
def chinese_leap(date):
"""Return 'leap' element of a Chinese date, date."""
return date[3] | 4124b3c4a647894e96d3c32cd81113b79da0191a | 630,189 |
def get_starting_model(interaction_dict, verbose=False):
"""Returns as a starting model one of the CustomModel of the chain with more recorded interactions"""
if verbose:
print("Selecting best interaction from where to start modeling...")
max_len = 0
interaction_key = None
for key in interac... | 7747d23883628a17b55c6f73eb9660c63a1e692e | 630,191 |
def scale(X, min=0, max=1):
"""Scale X to given range.
Parameters
----------
X : np.array of shape=(n_samples, n_features)
Data to scale.
min : float, default = 0
Minimum value to scale to.
max : float, default = 1
Maximum value to scale... | b2895bf3b7330c454e5db1baaf627e294d2ff836 | 630,194 |
from typing import List
def _get_abc_from_superclass_name(qualified_superclass_name: str) -> str:
"""
Get the corresponding abstract base class name
"""
qualified_abc_name_list: List[str] = qualified_superclass_name.split(".")
qualified_abc_name_list.insert(1, "abc")
return ".".join(qualified_... | 69ff9e76068ad3ddcc96e21e62e53eba6ff10864 | 630,195 |
def problem_found(status):
"""
Check if there is an Rfam issue.
"""
return str(bool(status["has_issue"])) | d03bae3fd985c9ebf75ef0b605355fc2cd1283a8 | 630,196 |
def get_bin_list(n, nmax):
"""
return a list of digits of the binary representation of n
nmax is the maximum theoretical value of n, used to add 0 at the front of the list if necessary
"""
if n == 0:
return [0 for _ in range(len(bin(nmax))-3)]
n = bin(n)
digits = []
for i in rang... | 3fa8d1a7e7e025f24ccca4fc287f5a96add937fe | 630,197 |
def _unfold_parallel(lists, n_jobs):
"""Internal function to unfold the results returned from the parallization
Parameters
----------
lists : list
The results from the parallelization operations.
n_jobs : optional (default=1)
The number of jobs to run in parallel for both `fit` and... | e62b819965328c143d20fb4db134aeb053e1b2d6 | 630,204 |
def low(self):
"""Low edge of first bin.
:returns: low edge of first bin
:rtype: float
"""
ax = self.GetXaxis()
return ax.GetXmin() | c23c886df8e39ae2fda47e2d28faa5b2d2d42264 | 630,205 |
def make_missing_swift_child(child):
"""
Generates a Swift call to make the raw syntax for a given Child object.
"""
if child.is_token():
token = child.main_token()
tok_kind = token.swift_kind() if token else "unknown"
if token and not token.text:
tok_kind += '("")'
... | a47a6280c8c4c32a92736214a27e3d77b6fad89c | 630,206 |
def is_list(klass):
""" Determine whether klass is a List """
return klass.__origin__ == list | ffb30cb7ff225f4772904eb038bb083951760d5d | 630,210 |
def findclosest(list, value):
"""Return (index, value) of the closest value in `list` to `value`."""
a = min((abs(x - value), x, i) for i, x in enumerate(list))
return a[2], a[1] | e994fb9b421474347de91eea812543d45c370080 | 630,213 |
def true(*ignore, **everything):
"""Give True regardless of the input."""
return True | c4dc5a2e458b8f181798c0923d7a1e8546f94bbd | 630,215 |
import socket
import contextlib
def find_free_port() -> int:
"""
:return: a free port; mind that this is not multi-process safe and can lead to race conditions.
"""
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with contextlib.closing(skt):
skt.bind(('', 0))
_, port = skt... | bc71b9b59e5d0e1e669a311a9b1f4fa95ea47c7f | 630,216 |
def isket(state):
"""Checks whether a state is a ket based on its shape.
Args:
state (:obj:`jnp.ndarray`): input state
Returns:
bool: ``True`` if state is a ket and ``False`` otherwise
"""
return state.shape[1] == 1 | 421587d90657fcc746b88dbac4052ae8bed7c2ca | 630,217 |
def kmerize_orf(orf, k, t):
"""
Creates kmers of certain size and type from provided sequence.
:param orf: nucleotide sequence
:param k: size of a kmer
:param t: type of a kmer, i.e. 'simple', 'all' or 'codon'
:return kmers: list of kmers
"""
kmers = []
if t == 'simple':
sto... | 0b06e21e478db592ed92a97a2e197c34aa9223c3 | 630,218 |
def clean_str(s: str) -> str:
"""
Remove characters the pronouncing library can't handle.
Parameters:
s (str): The string to sanitize.
Returns:
The sanitized string.
"""
DEL_CHARS = ["(", ")", "[", "]", "{", "}", ",", ":", ";", "."]
SWAP_CHARS = [("-", " ")]
for char in DEL_CHARS:
s = s.replace(char,... | 763b897b4a58ab273d72f3577dce5e86aca72879 | 630,222 |
import pkg_resources
import json
def load_vocabularies(project):
"""Load project vocabularies from json file.
Load from project json data files all accepted values for facets.
Args:
project (str): data project
Returns:
a series of lists (list): one for each facets, elements are acce... | 3b960ce13e2c4320349bbfe44d8236338a153ca4 | 630,225 |
def vecs2tuples(vecs):
""" Convert list of vectors into set of tuples """
return set(tuple(v) for v in vecs) | f28eb164032666f65bc9122269520f8b9324089d | 630,228 |
def unliteral(lit_type):
"""
Get base type from Literal type.
"""
if hasattr(lit_type, '__unliteral__'):
return lit_type.__unliteral__()
return getattr(lit_type, 'literal_type', lit_type) | c5d800eb93bc5f9f49ea42539a52a1379e9fefc6 | 630,231 |
def top_basemap_layer_url(layers):
"""Returns the URL of the top map layer if it exists"""
if layers[-1].is_basemap and len(layers) > 1:
return layers[-1].url
return None | 2484b1afb319f3650f24f89487dfda9ffb18864d | 630,236 |
def meters_to_user_units_scale_factor(units: str) -> float:
"""
Return the scale factor to convert meters to user units.
Multiply the meters value by the scale factor to get user units
Args:
units: String containing 'english' or 'meters'
Returns: Scale factor
"""
if units == 'e... | 980cc2eff1f4cc880c9a65eaa98c4cd5b40a1290 | 630,238 |
def execute_query(driver,query):
"""Execute the provided query using the provided Neo4j database connection and driver.
Parameters:
driver A Neo4j bolt driver object
query A Cypher query to be executed against the Neo4j database
"""
with driver.session() as session:
results =... | 9015689fb2bf1674d96de8aee315d002f0f03a9e | 630,239 |
def _get_deploy_iso_name(node):
"""Returns the deploy ISO file name for a given node.
:param node: the node for which ISO file name is to be provided.
"""
return "deploy-%s.iso" % node.name | cae34990e5bc0c94408151b69b8562dc5d4c2432 | 630,242 |
def binary_to_string(input_binary: str) -> str:
"""Convert binary string to Ascii string.
:param input_binary: An input binary encoded string.
:return: The Ascii encoded equivalence of the input binary string.
"""
binary_from_str = int(input_binary, 2)
byte_from_binary = binary_from_str.to_byte... | 9aa324b0c041d03ca8e7e85cd8f339bc670beb3b | 630,243 |
def calculate_enrichment(coverage_values):
"""Calculate TSS enrichment value for a dataset
Parameters
----------
coverage_values
iterable of tuples (tss_center_depth, flank_depth) per TSS
Returns
-------
float
the TSS enrichment value
"""
tss_depth, flank_depth... | 673ee0208dca03e10f92463d5d53c1be73341f0d | 630,244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.