content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
def doLogLikelihoodTest( complex_ll, complex_np,
simple_ll, simple_np,
significance_threshold = 0.05):
"""perform log-likelihood test between model1 and model2.
"""
assert complex_ll >= simple_ll, "log likelihood of complex model smaller than... | 0d5858de204366e19c41704a83a37c2c9b04a45c | 65,389 |
def get_num_from_user(str_info, lower, upper):
"""Ask and returns a integer inputted by the user from a set range.
:param str_info: Text shown to the user
:param lower: Inferior range limit
:param upper: Superior range limit
:return: Integer from the user
"""
flag_finish = False
aux_inp... | cd5d30f4dfa3b340c92580e8d40fe9eca62efc1d | 65,390 |
def _import_resource(fixture_name, editor_group=None):
"""
Imports the XML resource description with the given file name.
The new resource is published and returned.
"""
result = test_utils.import_xml('{0}/repository/fixtures/{1}'
.format(ROOT_PATH, fixture_n... | 2640f38337e3cfd17e55f8b8c471577719188824 | 65,391 |
def edit_distance(s1: str, s2: str) -> int:
"""The minimum number of edits required to make s1 equal to s2.
This is also known as the Levenshtein distance.
An edit is the addition, deletion, or replacement of a character.
"""
if not s1:
return len(s2)
if not s2:
return len(s1)
M = [[0 for _ in... | bd433f8b52dd9826032ced7ece0fb7df8b5ad8cc | 65,392 |
def parse_seed(secret):
"""Your Stream secret is a seed from which the true private key can
be derived.
The ``Seed.parse_json()`` method of stm-lib supports different
ways of specifying the seed, including a 32-byte hex value. We just
support the regular base-encoded secret format given to you by t... | d91b182f4db7ee2399cd15e1297a13385d489489 | 65,393 |
import requests
def suggest_username(query: str) -> list:
"""
Function suggest the username for the
Instagram Accounts by Instagram
"""
with requests.session() as s:
response = s.get(home_url)
token = response.cookies["csrftoken"]
headers["x-csrftoken"] = token
dat... | 194339ade1afcc65999d9242ac8a0264cc0c062c | 65,394 |
def removeTags(text):
"""
"""
# {} wrapper generates a set instead of list to deal with repeated tags
tags = {tag.strip('#') for tag in text.split() if tag.startswith("#")}
text = text.replace('#', '')
return (text, tags) | 30e267e22da210d48b3271a2e57562b6bff92820 | 65,395 |
def _remap_cortex_out(cortex_out, region, out_file):
"""Remap coordinates in local cortex variant calls to the original global region.
"""
def _remap_vcf_line(line, contig, start):
parts = line.split("\t")
if parts[0] == "" or parts[1] == "":
return None
parts[0] = contig... | 03357f276c6733508f17197a3300f1d55271e486 | 65,398 |
def to_base(base: t.Literal[2, 8, 16], number: int) -> str:
"""Convert any passed integer into given base as string."""
if base == 2:
return bin(number).replace("0b", "")
elif base == 8:
return oct(number).replace("0o", "")
elif base == 16:
return hex(number).replace("0x", "") | 478a1fdda832601c5f17aecdd1f4e716bf50d793 | 65,399 |
def get_serial_model(session_obj):
"""Get device serial number and model"""
global session
session = session_obj
serial = None
model = None
show_inventory = send_command('show inventory')
for i in show_inventory.splitlines():
if i.rfind('Chassis') != -1:
model = i.sp... | e8fe8f4fb7ec45b1107f70e18d9e01886f6b020f | 65,400 |
def find_nearest(known_array, test_array):
"""Find closest value in `known_array` for each element in `test_array`.
Parameters
----------
known_array : numpy array
consisting of scalar values only; shape: (m, 1)
test_array : numpy array
consisting of scalar values only; shape: (n, 1)... | 49a6351250c5ef61818cfb385de645a27bcf736e | 65,402 |
import array
def ReadNormalTag(tag):
"""
Read the raw data stored in Normal Tag.
:param tag: The Normal Tag to read the data from.
:type tag: c4d.NormalTag
:return: A list with all the raw data.
:rtype: list[int]
"""
# Retrieves the read buffer array
buffer = tag.GetLowlevelDataAd... | 211faf4cd2bceacdc7a13e93addbb82f851ffd0c | 65,403 |
def power_out_time(value):
"""
0 - 32767 seconds
"""
return "Seconds:{}".format(value) | 1f1efb91a9163ad0f6fb920985edb84809c38c5a | 65,404 |
def _album_is_reviewed(album, user_key):
"""Check if an album has been reviewed.
Args:
album: An Album entity
user_key: A stringified user key, or None.
Returns:
If user_key is None, returns True if and only if the album has
any reviews at all.
If user_key is not None, retu... | fd3b495ccdbc7a61398bc63a28fd5ab8378152f0 | 65,405 |
def cubehandler(f):
"""
Wrap a function from metpy.calc submodule to pass iris cubes as arguments
and get cubes as output.
Copies coordinates from the first cube among the arguments.
Only copies `dim_coords` and `aux_coords`.
May not work with some units.
"""
@wraps(f)
def wrapper(... | 71fafc8049a40145d143de26025f133ab243de2d | 65,406 |
def read_argv(argv):
"""Reads the config and source file from argvs"""
try:
config_file = argv[0]
source_file = argv[1]
return config_file, source_file
except:
Corrector.exit(
"Invalid arguments when running corrector. e.g python corrector.py settingsPath sourcePa... | 0eed23937e2c0506dccdd19a40a83274719661c6 | 65,407 |
def position_encoding_init(n_position, d_pos_vec):
"""
Generate the initial values for the sinusoid position encoding table.
"""
position_enc = np.array([[
pos / np.power(10000, 2 * (j // 2) / d_pos_vec)
for j in range(d_pos_vec)
] if pos != 0 else np.zeros(d_pos_vec) for pos in rang... | ae6abd373c4841b15771464a8c9bc073d3865e1d | 65,409 |
def _require_auth(fnc):
"""Authentication decorator."""
@wraps(fnc)
@_assure_identity
def _wrapped(*args, **kwargs):
if not identity.authenticated:
msg = "Authentication required before calling '%s'." % fnc.__name__
raise exc.NotAuthenticated(msg)
return fnc(*args... | 17e3dd050aed75a9d5b1e0005de9f7d07bdf690c | 65,410 |
def get_random_word(alphabet: str, length: int):
"""Generate a random word on alphabet with given length"""
random_word = ''
for i in range(length):
random_word += alphabet[randint(0, len(alphabet) - 1)]
return random_word | ec51b52f6643a0a975a60f986761dfe7efeb45e2 | 65,411 |
import sqlite3
def load_history_db(history_db):
""" Load simulation history from provided db.
In case no db is given, returns an empty history
:param history_db:
:return:
"""
history = {}
if history_db is not None:
conn = sqlite3.connect(history_db)
cursor = conn.cursor()
... | 06055c6c48f8757513808e44d85f802ab0acd456 | 65,412 |
import functools
def compute_network_criticality(
parameters,
module_objective_fn,
init_loop_variables_mapping,
final_loop_variables_mapping,
):
"""Compute the criticality of a network parameterized by `parameters`."""
def _module_criticality_by_ref(layer_ref):
return compute_module_criticali... | f0098368708ffe0814848cf07c111179c3a574bf | 65,413 |
import shutil
def async_get_engine(hass, config):
"""Set up macOS speech component."""
if shutil.which("say", path="/usr/bin") is None:
_LOGGER.error("'/usr/bin/say' not found")
return False
if shutil.which("reattach-to-user-namespace", path="/usr/local/bin") is None:
_LOGGER.error... | 97487b4eca354ed7b962a6ab90c6448c1da17af4 | 65,414 |
def validate_data(first_name, age,investment_amount,risk_level, intent_request):
"""
Validates the data provided by the user.
"""
# Validate that the user is over 0 and less than 65
if first_name is None:
# first_Name validation
# age=parse_int(age)
return build_validatio... | d14a366499d52accc3b2d8059b3ee93add2f275c | 65,415 |
def get_targets(data, n_groups):
"""
In order to obtain our final set of labels for the data,
this function transforms the data first using PCA,
then Agglomerative Hierarchical Clustering. It returns
the target labels as a pandas dataframe.
Parameters:
data: The dataset in question.
n_g... | a7c9a326cc08e649ca52dc322c5b8677a5bcbdd3 | 65,417 |
def string_to_datetime(timestamp_string):
"""Convert string timestamp to datetime instance."""
try:
return dt.datetime.strptime(timestamp_string, "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
return dt.datetime.strptime(timestamp_string, "%Y-%m-%dT%H:%M:%SZ") | 32716adeea77ada8c07f144422c7b2075f5afa1b | 65,418 |
from typing import Any
def _filter_keep(value: Any, keep_always: bool) -> bool:
"""Determine whether we should keep a value in serialized output."""
if keep_always:
return True
return value is not MISSING | 373ba5179e315dc76cb8b19d3ef7f3d51e8b9e00 | 65,420 |
def GetScopedName(scope, type_defn):
"""Gets the prefix string to reference a type from a given scope.
This function returns a concatenation of C++ scope operators such as, in the
context of the given scope, when prefixing the name of the given type, it
will reference exactly that type.
For example, given:
... | ec8259de1be11563d8ddf67abe071941b6195aa3 | 65,421 |
def SNR(info, magnitude=24.5, exptime=565.0, exposures=3, galaxy=True, background=True, diginoise=False):
"""
Calculates the signal-to-noise ratio for an object of a given magnitude in a given exposure time and a
number of exposures.
:param info: instrumental information such as zeropoint and backgroun... | 5001fc83307b52b93bcb98e5337beeb76132e86c | 65,422 |
def ipusage(request):
"""Lists all assets."""
inventory = netspot.NetSPOT(collection=netspot_settings.COLL_IP)
search_result = inventory.search('', key='ip', sort=[("date", 1), ("time", 1)], limit=20)
return render(
request,
'ipusage.htm',
context={'filter': '', 'ips': search_result,},
) | 3ad2a424a9e43036be40c2bbb215e68bdeef5559 | 65,423 |
def max_employment(countries, employment):
"""
Fill in this function to return the name of the country
with the highest employment in the given employment
data, and the employment in that country.
"""
i = np.argmax(employment)
max_value = employment[i]
max_country = countries[i]
ret... | e023ecd2819f7300046a53999473723c5bb5bebc | 65,424 |
def dB_to_amplitude(SNR):
"""Returns the amplitude ratio, converted from decibels.
Arguments
---------
SNR : float
The ratio in decibels to convert.
Example
-------
>>> round(dB_to_amplitude(SNR=10), 3)
3.162
>>> dB_to_amplitude(SNR=0)
1.0
"""
return 10 ** (SNR ... | 92fa3cb5d40e8f0ac68a447e3eef976ec9853139 | 65,429 |
def upload_location(instance, filename, **kwargs):
"""Upload location for profile image"""
return f"accounts/{instance.username}/{filename}" | c662bbb095f8180aa330a2566c9d9aaf372712b0 | 65,430 |
def v9_tail(iterable, n):
"""Return the last n items of given iterable.
This solution uses deque, a double-ended queue class, from the
collections module...
We're setting the maximum size of our deque to n. When you append to a
deque which has reached it's maximum length, it will efficiently remov... | 89358971690adcb4f32005ee09b2f3ca4a63277e | 65,431 |
import operator
def add(n_in: int = 2) -> Foldl:
"""Creates an addition combinator.
>>> from redex import combinator as cb
>>> add = cb.add()
>>> add(4, 2) == 6
True
Args:
n_in: a number of inputs.
Returns:
a combinator.
"""
return foldl(func=operator.add, n_in=n... | f7b7e1e66654e30da14dc112abed3e95884e5020 | 65,432 |
import base64
def base64url_to_hex(data):
"""
Converts a base64url encoded string to a hex encoded string
Args:
data (str): The base64url encoded string
"""
data = data.replace("-", "+").replace("_", "/")
missing_padding = len(data) % 4
if missing_padding:
data += "=" * (... | db56f4c9e1335b9a4a8f0e0a794c7468122666dc | 65,433 |
def read_release_version():
"""Read version information from VERSION file"""
try:
with open(VERSION_FILE, "r") as infile:
version = str(infile.read().strip())
if len(version) == 0:
version = None
return version
except IOError:
return None | 1de778f67235b31c3a349b8016fe29e2f3c113f8 | 65,434 |
def read_rpg_header(file_name):
"""Reads header from RPG binary file.
Supports Level 0/1 and version 2/3/4.
Args:
file_name (str): name of the file.
Returns:
tuple: 2-element tuple containing the header (as dict) and file position.
"""
def read(*fields):
block = np.fr... | c2b97981e96555c3cc02d5e6ad071cd1d35b81cd | 65,435 |
def quantize(dt, *, resolution=timedelta(minutes=15)):
"""Get the period from a fixed-size grid which contains the given time"""
# The grid is zeroed at midnight, so resolution must fit into a day without leaving a remainder.
assert not Period.DAY % resolution
from_midnight = timedelta(hours=dt.hour, mi... | 4ff8388594bd884c81102fbf34a85122386247f5 | 65,436 |
def validate_redirection_target(path):
"""Checks if login can safely redirect to a path.
For example, if instead of a path a full url is used (with a
domain part), the redirect could leak a login token in the Referer
header (not an obvious problem since token is intended to be one
time, but better ... | 4401d9f723bdaccb27256f405b0de31dec855a35 | 65,437 |
import sqlite3
def create_connection(db_file) -> sqlite3.Connection:
"""
This method connects to the database and returns the connection
"""
connection = None
try:
connection = sqlite3.connect(db_file)
except Error as e:
print(e)
return connection | 2d00bdc2f86fd04b0d77f542ec177232a49e97aa | 65,438 |
def kldiv2(s, t):
""" Kullback-Leibler divergence with base 2 """
return kldiv(s, t, log="2") | 4822f19600c3ce91b5e91fd30dc6ca690e3697ea | 65,441 |
def get_meta(number):
"""
Retrieve the level 3 classname and official RGB value for each clc class.
Parameters
----------
number: int
CLC_CODE of the class
Examples
--------
>>> get_meta(111)
Returns
-------
Official RGB colors as (r,g,b)
Level 3 name of t... | 2cebc9dd50bad28de5c122a51ca19f5ef97f6414 | 65,442 |
def submat(X,ii,jj):
""" Pick a block submatrix from block matrix X by rows ii and cols jj """
return {(ix,jx): X.get((i,j), None)
for (ix,i),(jx,j) in product(enumerate(ii),
enumerate(jj))} | 33fafb2b4e2daeedd51cd4fb8aa5e6d705e8bf36 | 65,443 |
import csv
def corpus_maker(f_name):
"""
Takes a csv file and creates a set of decklists in list of lists,
DataFrame, and tomotopy Corpus objects.
Parameters:
f_name: .csv file
Term-document matrix: columns are card names, rows are decks,
and each cell is the co... | 6dd5d0c4a1f3a66e72421eea2c69418fa9c94248 | 65,444 |
def summed_area_table(img):
"""
Use summed_area_table_fast() instead. Leaving this for reference.
"""
# Convert to numpy array if necessary
if not isinstance(img, np.ndarray): img = np.array(img)
table = np.zeros(img.shape)
# Raster scan
#---- Do top and left edges
table[0, 0] = im... | a7e29e667f031dd5b2256fd13dcbbd2e9a92eb4c | 65,445 |
def find_omp(verbose=False):
"""
Find omp in environment.
Parameters
----------
verbose : bool
to print paths to include and library directories
Returns
-------
tuple(list(str), list(str))
path to include directory, path to library directory
"""
omp_include, omp... | e627ca182ce824342be2423ea72a28d6920a0c56 | 65,446 |
def safe_filename(infilename):
"""
Take a filename and remove special characters like the asterisk and slash which mess things up. Warning: if you
pass a directory path to this function, it will remove the slashes. Do not do that.
:param infilename: filename to be processed.
:type infilename: strin... | 0e46972696f8d7b10bc6bc61efcdd2dfbca9e909 | 65,447 |
import collections
from typing import Mapping
def namedtuple(typename, field_names, default_values=()):
"""
Overwriting namedtuple class to use default arguments for variables not passed in at creation of object
Can manually set default value for a variable; otherwise None will become default value
""... | b0fba5ba73037e7bdb5db05d10a8b96f953fc829 | 65,448 |
import warnings
import json
def _validate(nodes_fname, meta_fname, streamlines_fname):
"""
Run checks to ensure requirements and warns of inconsistencies.
Parameters
----------
nodes_fname : str
Full path to nodes table CSV file
meta_fname : str
Full path to metadata CSV fil... | c6ef766be628088e1bef90c0ac81ebcc444cc304 | 65,449 |
def _truncate_log(log_txt):
"""
Truncate the ``log_txt`` in case it exeeds the max. log size.
:param log_txt:
A ``str``.
"""
max_log_bytes = config.getint('job_runner_worker', 'max_log_bytes')
if len(log_txt) > max_log_bytes:
top_length = int(max_log_bytes * 0.2)
botto... | a3be928a29c32a73b10ca45cb14da768b28d9bda | 65,450 |
def length_along_path(pp, index):
""" Get the lenth measured along the path up to the given index.
"""
index = min(index, len(pp) - 1) # beware of the end
diff_squared = (pp[:index] - pp[1:index+1]) ** 2
distances = diff_squared.sum(1)
return (distances ** 0.5).sum()
# == sum(pp[j].distance... | a7eea4b411860c51fb5f64a690a9d4832c8b98a9 | 65,452 |
def generate_background(options):
"""
Fonction permettant d'ajouter un background
:return: etree.Element
"""
width = options.width
height = options.height
background_group = etree.Element('g')
etree.SubElement(background_group, 'title').text = 'background'
background = etree.SubEle... | 72c9db05d72b5dcd64bfad907e5b74e5c25c0a04 | 65,453 |
import re
def get_generators(cmakePath=findexe("cmake"), as_list=False):
"""get available CMake generators
Parameter:
as_list str: True to return a list of dict of all generators. Each entry
consists of 'name', 'desc', and 'default'
Returns: str if as_list==False else dic... | f2603dc1a366822b4e1040b7e10db614332c8ad7 | 65,454 |
import calendar
def _get_month_info(localtime):
"""获取月相关的信息"""
now_day = localtime.tm_mday
now_year = localtime.tm_year
now_month = localtime.tm_mon
now_month_max_day = calendar.monthrange(now_year, now_month)[1]
left_day = now_month_max_day - now_day
month_percent, progress_bar = _get_pro... | d7d619528d36c75d56d5c36360876bd328e36a24 | 65,455 |
def init(cfg: GenomeConfig):
"""Random initialized weight value, calculated via a normal distribution."""
return clip(gauss(cfg.weight_init_mean, cfg.weight_init_stdev),
a_min=cfg.weight_min_value,
a_max=cfg.weight_max_value) | f18314d905822bf3e30204c4168c8952edefaa1d | 65,456 |
def tokenize_and_tag(filepath):
"""Load the book's text, tokenize and tag in memory."""
with open(filepath+'.txt', 'r') as f:
book = f.read()
return pos_tag(word_tokenize(book)) | 5f543c98cc9d59c91d82921d2dd6c1e81daf10c2 | 65,457 |
import json
def output():
"""Prints out the first 10 rows in the database"""
my_query = get_database_data("SELECT * FROM Data LIMIT %s", (10,))
json_output = json.dumps(my_query, default=str)
return json_output | 6e35b5fca72171680bec5da87a38a0fd59a4c9e4 | 65,458 |
def get_user_env_var() -> str:
"""returns the environment variable "USER", if it doesn't exists, return a default value"""
user_var = ps.get_env_var( 'USER' )
if user_var == None:
user_var = 'USER'
return user_var | 165df68af82708d3d7d15c1a5eecdf863ce0c854 | 65,459 |
def RFile():
"""Return a raman data file for testing."""
return 'examples/testdata/1/0001.txt' | cb9bf96aa3dab11f27322b4587f3e36f89a59f31 | 65,460 |
def zzX_mul(f, g):
"""Multiply polynomials in Z[X]. """
if poly_univariate_p(f):
return zzx_mul(f, g)
if f == g:
return zzX_sqr(f)
if zzX_zero_p(f):
return f
if zzX_zero_p(g):
return g
df = zzX_degree(f)
dg = zzX_degree(g)
h, l = [], poly_level(f)-1
... | a7288d2ee59415acf46a5fea30913bd23e45f33b | 65,461 |
def compute_performance_easy(trials):
"""
Compute performance on easy trials (stimulus >= 50 %) from trials object
:param trials: trials object that must contain contrastLeft, contrastRight and feedbackType
keys
:type trials: dict
returns: float containing performance on easy contrast trials
... | 6859f79f5fae635fc08261f7906dbc05e9140aa6 | 65,462 |
import math
def check_transcript_eir_tc_state(tr_id, exid2cov_dic, trid2exc_dic,
filter_ei_ratio=1.0,
min_ei_cov=20,
min_ei_cov_sum=False,
exid2isrn_dic=False,
... | 3e20da95ec5e463fb68fb8619d0063701b453217 | 65,465 |
def find_node(_node_number, geometry):
"""
Check if node number exist in the f2u model
"""
_node = []
for _number in _node_number:
try:
_test = geometry._mesh.nodes[_number]
_node.append(_number)
except KeyError:
continue
return _node | 17e5a3c21529298e19ee424539a83ccea1b8acf6 | 65,466 |
def confidence_score(classifier, X: np.ndarray) -> np.ndarray:
"""Measure the confidence score of a model for a set of samples.
Args:
classifier: The classifier for which the labels are to be queried.
X: The pool of samples to query from.
Returns:
The confidence score for each samp... | 4af8ff0df27392e9f809a5a4fdc9c8c8e7f64900 | 65,468 |
import random
def roll_die():
"""Returns a random int between 1 and 6"""
return random.choice([1,2,3,4,5,6]) | 664add4a7345268e68d0c6941aa42d71be581606 | 65,469 |
def report(uid):
""" Render object report for verify """
database = DataProvider()
# get checklist and show it in edit mode
item = first_or_default(database.checklists, lambda x: x.uid == uid)
item.visit_by(session['user_name'])
database.update_checklist(item)
questions = database.checklist
... | 02ac3a002f3134f99ba3643a7e3edc5f14345e74 | 65,470 |
def convert_to_HSV(image):
"""convert RGB(BGR in opencv numpy) to HSV color space"""
hsv_image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
return hsv_image | 62be9e73ef76d426d4572d71ad5925a236cb549c | 65,472 |
def size(input, name=None, out_type=dtypes.int32):
# pylint: disable=redefined-builtin
"""Returns the size of a tensor.
Returns a 0-D `Tensor` representing the number of elements in `input`
of type `out_type`. Defaults to tf.int32.
For example:
```python
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3,... | 6e8ece9fb4ca73f114642ece0a249a05882177ba | 65,473 |
def find_part(part_id):
"""
This function is defined as an abstraction barrier,
in case we want to use a different storage object for
BoM, such as perhaps a read/write database.
:part_id: the ID of the part specified
:return: part object specified by part_id, else None if DNE
"""
return... | de9f6332d8a7926a0f5b96983b8d2cdf2b3acefe | 65,474 |
import random
def Transform(depth_image: np.array, ir_image: np.array, boxes: np.array, labels: np.array, train: bool):
"""
Apply transformation.
:param depth_image: np.array(uint16), Depth image
:param ir_image: np.array(uint16), IR image
:param boxes: np.array(np.float), a list of N boxes of th... | 98d24bb44c979e3cd344de67bacf0052284240a5 | 65,475 |
def FormatScoreTimes(score_times):
"""Provide a color-coded formatting of the output of ScoreLogFile."""
ok = '\033[94m'
warn = '\033[93m'
fail = '\033[91m'
result = []
for name, score_time in score_times.iteritems():
if score_time < 0.2:
color = ok
elif score_time < 2.0:
color = warn
... | 67c7456974d907f8f87eb9cde409083693a08118 | 65,477 |
def isWithin(rect1, rect2):
"""Checks whether rectangle 1 is within rectangle 2
Parameters:
rect1: list of coordinates [minx, maxy, maxx, miny]
rect2: list of coordinates [minx, maxy, maxx, miny]
Returns:
True if rect1 within rect2 else False
"""
minx1, maxy1,maxx1, miny1 = r... | d7adca34b7cfb4294316090e18c164db0a34e818 | 65,478 |
import numpy
import itertools
import six
from operator import concat
def n_step_lstm(
n_layers, dropout_ratio, hx, cx, ws, bs, xs, train=True,
use_cudnn=True):
"""Stacked Long Short-Term Memory function for sequence inputs.
This function calculates stacked LSTM with sequences. This function g... | 419cca3181f910bc0c93d8e9bd46d9a3f818ea9b | 65,479 |
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = request.forms.username
# Izračunamo MD5 has gesla, ki ga bomo spravili
password = password_md5(request.forms.password)
# Preverimo, ali se je uporabnik pravilno prijavil
... | f2e43f4d25d2020ab959375f10acd9e060bcc9c3 | 65,481 |
def doolittle(matrix_a):
""" Doolittle's Method for LU-factorization.
:param matrix_a: Input matrix (must be a square matrix)
:type matrix_a: list, tuple
:return: a tuple containing matrices (L,U)
:rtype: tuple
"""
# Initialize L and U matrices
matrix_u = [[0.0 for _ in range(len(matrix... | 03ba90c29dfb67ffe1edf939b49f3ab537931831 | 65,483 |
def is_form_submitted():
"""
Check if current method is PUT or POST
"""
return request and request.method in ("PUT", "POST") | de260ecbd0eb48ae5d49029e858a41e558a03009 | 65,484 |
import random
def randFunc():
"""
Rand # generating func
:return: int
"""
return random.randint(1,3) | f2b2501dcc1acede3d99d36b55587b6e97f8ae5a | 65,485 |
def hilbert(w):
"""
Take the Hilbert transform of some function to get the analytic signal
:type w: np.array
:param w: signal data, must be real
"""
return np.imag(analytic(w)) | 2f40fc448e3dd9a1d212567abdebaeb83de83896 | 65,488 |
def get_model_list():
"""Get the entire list of model names in model_zoo.
Returns
-------
list of str
Entire list of model names in model_zoo.
"""
return _models.keys() | 27aae6873272af4ba20b227f74669c79583cae37 | 65,489 |
def get_delay_queue_max_size():
"""Returns max allowed number of "waiting" messages in the delay queue.
:return: Positive integer number or None if infinite
:rtype: int
"""
if 'replica' not in settings.CQRS:
return None
return settings.CQRS['replica']['delay_queue_max_size'] | b056ac58b50ec33179e0a4d1b076ef3c068bdd74 | 65,490 |
def getRequest(request):
"""
Get an openid request from the session, if any.
"""
return request.session.get('openid_request') | f6ebcb13e631365f53ae3a362eaf2dba614d7344 | 65,492 |
from typing import Tuple
def make_networks(
spec: specs.EnvironmentSpec,
hidden_layer_sizes: Tuple[int, ...] = (256, 256)) -> ValueDiceNetworks:
"""Creates networks used by the agent."""
num_dimensions = np.prod(spec.actions.shape, dtype=int)
def _actor_fn(obs):
network = hk.Sequential([
h... | fecba5196fb09f81c9cba1da82f238f69d32af09 | 65,493 |
def pad_to_longest(vals: AnyList) -> StringList:
"""Pad all strings to length of longest in list
Arguments:
strs {StringList} -- string list
Returns:
StringList -- list of strings
"""
strs = [str(x) for x in vals]
pad_len = max([len(x) for x in strs])
pad_str = ' ' * pad_le... | 07ea446153ba6d8d37cb7b3729171fad98effa36 | 65,494 |
def histogram_widget(value, title=None, description=None, footer=None, read_only=False,
buckets=20, weight=1):
"""Helper function for quickly creating a histogram widget.
Histogram widgets display the distribution of a numeric attribute, in buckets, to group
ranges of values in your da... | 823cc4948bacb073fa6b9e0e5eee89d5f0a0b3ca | 65,495 |
def generate_process_tag(slug):
"""Generate test tag for a given process."""
return '{}.{}'.format(TAG_PROCESS, slug) | 58cdac7b226ffd042faadd65f9e2700cc0d935e0 | 65,496 |
def artificialNeuralNetwork(obj, weights):
"""
obj is a list of values (like [0.5, 6.0, 0]. Keep away
from inf and nan and stuff).
weights is a vector where the first element is the number
of hidden layers. (Call it N)
Then there should follow N integers that show how many n... | 1324f78759dcd3f0296d1557b04adc5ff2266cbb | 65,497 |
def run(adj_list, node_mappings, games=50):
"""
Function: run
-------------
Runs the simulation on a graph with the given node mappings.
adj_list: A dictionary representation of the graph adjacencies.
node_mappings: A dictionary where the key is a name and the value is a array
list of seed... | d87c70eb2044d676350b431fa2d4e6e3b2e610d9 | 65,498 |
def filter_staged(position_name, position_annotations, timepoint_annotations):
"""Filter-function for filter_annotations() to return worms that have been
stage-annotated fully and are noted as "dead"."""
stages = [tp.get('stage') for tp in timepoint_annotations.values()]
# NB: all(stages) below is True ... | 14e7f12fa100da4ef9a26496f7f9fc83e2988d3d | 65,499 |
def feature_importance_mad(clf,
alpha=0.05,
ignored_percentile=None):
"""This function fetches the feature importance values and runs a
criteria using the median absolute deviation. If a feature
importance difference to the median importance is greater t... | fc803527cb1be8eefd7ea62be916aa00b0be637f | 65,500 |
import math
def parse_sizes(raw: dict) -> dict:
"""Pass."""
parsed = {}
parsed["disk_free_mb"] = math.floor(raw["disk_free"] / 1024 / 1024)
parsed["disk_used_mb"] = math.ceil(raw["disk_used"] / 1024 / 1024)
parsed["historical_sizes_devices"] = raw["entity_sizes"].get("Devices", {})
parsed["his... | 491169f74ff6393da33b3c436e2aba2a87c26a1f | 65,501 |
def associated_polynomials(cos_theta, sin_theta, max_n, max_m, k=None):
"""
Specific legendre legrende_polynomials for application in geomagnetic calculation
Recursion Constants (k) can be pre-calculated to improve performance, otherwise the
function will perform this for you
"""
if k is None:
... | 810bca7f858138864a02d4d3f98ed2ed306788ec | 65,502 |
def cov(x, y, pi):
"""Covariance of two discretized random variables with supports x and y common probability mass function pi."""
return np.sum(pi * (x - mean(x, pi)) * (y - mean(y, pi))) | 0fc31e652f59253aa168d38dc016075fef6d8a13 | 65,503 |
def color_validator(input_str):
"""
A filter allowing only the particular colors used by the Google Calendar
API
Raises ValidationError otherwise.
"""
try:
assert input_str in VALID_OVERRIDE_COLORS + ['']
return input_str
except AssertionError:
raise ValidationError(... | e5e5c6c3818e1b33cec4b8327bdedc729353f846 | 65,504 |
def getError(cur_pose, prev_pose, cur_gt, prev_gt):
"""
Computes the error of the transformation between 2 poses
"""
error_t = np.linalg.norm((prev_pose[:3, -1] - cur_pose[:3,-1]) - (cur_gt[:3,-1] - prev_gt[:3,-1]))
gt_prev_qt = quaternion.from_rotation_matrix(prev_gt[:3, :3])
gt_qt = quaternion.from_rot... | 83cdc05b8f9a81223742e403d7b9da752a102a74 | 65,505 |
def Oxygen():
"""Create a `PureFluid` object using the equation of state for oxygen."""
return PureFluid('liquidvapor.xml','oxygen') | d641b7e6247192795063120dfeaf837f32848888 | 65,506 |
from typing import List
from typing import Tuple
from typing import Iterator
import itertools
def find_best_worst_lists(sequence_of_lists: List[SpreadingRatio]) -> BestAndWorstLists:
"""
This function finds the "best" and "worst" lists from a set of lists. See explanation below.
:param sequence_of_lists: ... | 0840b9ec6105c97244d4ef38217e0ed6bdd59d78 | 65,507 |
def computeSumAbsPerPolarity(jz, jz_err, bz, bz_err, conf_disambig, bitmap, nx, ny, rsun_ref, rsun_obs, cdelt1_arcsec, munaught):
"""function: computeSumAbsPerPolarity
This function computes the sum of the absolute value of the current per polarity. It is defined as follows:
The sum of the absolute value... | dee89697cce2a98eb240840c2b1d6f4a1f1dbb80 | 65,508 |
def clang_describe_function(func):
"""Describe the function at the given clang AST node."""
assert func.kind == CursorKind.FUNCTION_DECL
sig, defaults = clang_describe_args(func)
signatures = {sig: {'return': clang_describe_type(func.result_type, func.location),
'defaults': defau... | 3f18952f562af7b9d14c76cff90dde28bfad17a9 | 65,509 |
import hashlib
def password_hash(password, password_salt=None):
"""Hashes a specified password"""
password_salt = password_salt or oz.settings["session_salt"]
salted_password = password_salt + password
return "sha256!%s" % hashlib.sha256(salted_password.encode("utf-8")).hexdigest() | 9cde58047239e0c770f14b5c803b529dacb651de | 65,510 |
def allowed_file(filename):
"""Determine if a file has an allowed extension."""
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] | 7a1093a53a7a7a049a95d1018ab83e3b32dd3c37 | 65,511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.