content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_plugin_option(name, options):
"""
Retrieve option name from options dict.
:param options:
:return:
"""
for o in options:
if o.get('name') == name:
return o['value'] | 38720ed9f0a42a543260d75dd043d4d9136b8fef | 3,612,673 |
def run_cc(hf):
"""
Run and return a restricted CCSD calculation on mol,
with HF molecular orbital coefficients in the RHF object hf.
"""
if type(hf) == SCF_TYPES['RHF']:
calc_cls = cc.CCSD
elif type(hf) == SCF_TYPES['UHF']:
calc_cls = cc.UCCSD
else:
raise NotImplemen... | c8a48215891f6c29c54efb6b45f8e8ee8906e97d | 3,612,674 |
async def top_salty():
"""
### Returns top 10 saltiest user
- Takes `/top_salty`
### Response
`id` - userid
`username` - username
`saltiness` - saltiness
`salty_description` = salty description
"""
QUERY = "SELECT * FROM users ORDER BY saltiness limit 10"
pg_conn=db_conec... | 25521a15fd6aac0360de9230b9823b3baa92075d | 3,612,676 |
from datetime import datetime
def thai_strftime(
datetime: datetime.datetime, fmt: str, thaidigit: bool = False
) -> str:
"""
Convert :class:`datetime.datetime` into Thai date and time format.
The formatting directives are similar to :func:`datatime.strrftime`.
This function uses Thai names and ... | 4be7be1e0490c2f7e7b0daec079082bea02f2ccd | 3,612,677 |
def dot_product(t1, t2, keep_dims=False, name=None, reduction_dim=None):
"""Computes the dot product of t1 and t2.
Args:
t1: A rank 2 tensor.
t2: A tensor that is the same size as t1.
keep_dims: If true, reduction does not change the rank of the input.
name: Optional name for this op.
reduction... | 95080d6dfc2845d700c1f57a8501832482065c6d | 3,612,678 |
def assert_boolean(raw_val):
"""
Assert that the value is boolean.
:return The value if it is boolean, otherwise raise an exception
"""
return assert_type(raw_val, bool) | 3d261ac4495a8d911aa828bdf64cd7260cf742db | 3,612,679 |
def classic_vs_bayesian_normal(mu, sigma, num_points, prior):
""" Compute both classical and Bayesian inference processes over the range of
data sample sizes (num_points) for a normal distribution with parameters
mu,sigma for comparison.
Args:
mu (scalar): the mean parameter of the normal distribution
... | 45d461ae62ba6dacff5aa2836a7617c21e4c0a3a | 3,612,680 |
def get_canonical_synonym(key):
"""Returns canonical synonym for key, else just key.
"""
if key == 'SAMPLE':
return MELTED_SCHEMA_KEY__ES_LABEL
return key | 48e86fc48f4d9dd354b17bdf206d5089dd2ec8ab | 3,612,681 |
import torch
def get_batch_pipe(data, neox_args):
"""A modification of get_batch() to work with the latest batch instead of an iterator."""
# Items and their type.
keys = ["text"]
datatype = torch.int64
tokens, labels, loss_mask, attention_mask, position_ids = _get_batch(
neox_args, neox_... | 5f629153bc467cf7ec94e8b5cdc3de17e1debaa4 | 3,612,682 |
def compute_precision(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(k=maxk, dim=1, largest=True, sorted=True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
... | 6986f09ac6385ae1409f998648babd2006bed63d | 3,612,683 |
import torch
def get_landmark_model(output_size) -> torch.nn.Module:
"""Build the convolutional network model with Keras Functional API.
Args:
output_size: the number of output node, usually equals to the number of marks times 2 (in 2d space).
Returns:
a model
"""
model = torch.n... | 20e6796e1a035aa94076de2979bddc449d6ecb37 | 3,612,684 |
def isPerfectSquare(p: int) -> bool:
"""Checks if given number is a perfect square.
A perfect square is an integer that is a square of another integer.
Parameters:
p: int
number to check
Returns:
result: bool
True if number is a perfect square
F... | d9c725193a5100e06825944239fe3442bed17b92 | 3,612,685 |
def frequencies_for_cutoffs(col, cutoffs):
""" Sets cutoffs for the frequencies """
# Sets each frequency to 0 by default
freqs = [0] * len(cutoffs)
for el in col:
for i in range(len(cutoffs)):
if el <= cutoffs[i]:
freqs[i] += 1
break
return freqs | 9784a7a68450d90de79de71804eb08bc796506eb | 3,612,686 |
def find(user_id, session):
"""
Find all the history.
:param user_id: history user_id
:param session: session
:return: history data.
"""
result = []
fetch = session.query(KMHistory)
for history in fetch.filter_by(user_id=user_id).all():
result.append(history)
return resul... | b95aabeec4a017a8e2fa8d6ec115f087a7c979cd | 3,612,687 |
import socket
def fetch(url, data='', agent=None, referrer=None, charset=None, verbose=0,
cookiejar={}, type=None, method=None, accept_language=None):
"""Make an HTTP or HTTPS request.
If 'data' is given, do a POST; otherwise do a GET.
If 'agent', 'referrer' and/or 'accept_language' are given,... | e60eec53733ee7f705df33920ab564481125a0ac | 3,612,688 |
import json
def emolument_new_view(request):
"""
Add new emolument
"""
# Check authorization
if not Utils.has_permission(request, request.registry.settings['affaire_facture_edition']):
raise exc.HTTPForbidden()
params = request.params
data = json.loads(params['data'])
emolumen... | 0a48dc228ce8ecf87f1574a2fc99e8db946d092f | 3,612,689 |
def display(auth_context):
"""
View function for displaying the checkout page.
Parameters:
auth_context (dict): The authentication context of request.
See middlewares/auth.py for more information.
Output:
Rendered HTML page.
"""
products = []
# Pre... | 24ddd9b8b47a0a06d6d11d60f2854625e07eaff4 | 3,612,690 |
def golden_ratio(n):
"""returns the Golden Ratio to an accuracy of `n` decimal places
Examples
--------
>>> print(golden_ratio(20))
1.61803398874989484820
>>> print(golden_ratio(50))
1.61803398874989484820458683436563811772030917980576
"""
x = _sym.symbols('x')
gr = [sol for sol... | 35b95aea80e25d6ff024966c74e9df773ae40e26 | 3,612,691 |
def totalbp(file):
"""Count total number of sequenced base pairs"""
with open(file, 'r') as Infile:
loci = ''
Count = 0
Loci_count = 0
start = False
for line in Infile:
#count first locus
if Loci_count == 0:
... | 0b1f47c379bcb3cb33a6baa82907db4044b5e220 | 3,612,693 |
def oppositeFunction(basef):
""" the opposite of a function """
if isinstance(basef, FitnessEvaluator):
if isinstance(basef, FunctionEnvironment):
''' added by JPQ '''
if isinstance(basef, MultiObjectiveFunction):
res = MultiObjectiveFunction()
else:
... | 7a15e025dc3cfc488a843a974db1d9368930b5a8 | 3,612,695 |
def cell(n):
"""Format a cell"""
return '{:3} {:5}'.format(
n, 'SPACE'
if n == 32 else 'DEL' if n == 127 else chr(n) if n >= 33 else 'NA') | a7696335b1962ab9b6fc661c3884f278e8cc38c9 | 3,612,697 |
def shape_arrays_for_pcolor_plotting(ps, indexing_list_indep_vars, ordered_params, dep_var_mgf):
""" """
X = ps.get_mgf_arr(ordered_params[0].name)[
tuple(indexing_list_indep_vars)]
Y = ps.get_mgf_arr(ordered_params[1].name)[
tuple(indexing_list_indep_vars)]
Z = None
if (np.shape(d... | 5fb92e455459d632690b3cb24dc62a4b837da7f1 | 3,612,698 |
def adoytoymd(year, doy, hour=0, min=0, sec=0):
"""adoytoymd(year, doy, hour, min, sec) -> string
Convert an array time with a day-of-year to a year-month-day time string. The
hour, minute and second parameters are optional. All input parameters must
be of type int."""
#
# validate input values
#
... | e3a8073c527d82a4123abdba97766295b6ad6241 | 3,612,699 |
def file_selector():
"""Function enables the user to select the txt files that they have downloaded.
returns:
"""
layout = [[sg.Text("Choose a file: "),sg.Input(key="-IN2-" ,change_submits=True), sg.FileBrowse(key="-IN-")],
[sg.Button("Submit")]]
window = sg.Window("File... | 8fe699f164ebf8f75eb2bde5a5fd9a52a7f196a5 | 3,612,700 |
import yaml
def connect_cursor(USERPATH):
"""Connect a cursor to database.
Input: Path to authorized user "secrets.yaml" file that is
expected to include connection parameters
Output: Database cursor object
Future consideration:
enable user to input latest year of available data inste... | 4a3869c703f73c21fc205e0cf203bfbeb92edf80 | 3,612,701 |
from typing import Dict
from typing import List
def avoid_other_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
e.g. {"x": 0, "y": 0}
snakes: List of dictionaries containing informa... | 2e2db43353f3bc16c6a064ecd6999c9226931237 | 3,612,702 |
def calculateJitterPercent(data):
"""
calculate jitter in percent
"""
return calculateJitterRatio(data) / 10.0 | 631903f270532b062e62aee8b4f0cebbfb406b4f | 3,612,703 |
def process_tenant(aci_session, tenant, override=False, fetch_endpoints=False):
"""
:param aci_session: ACI session
:param tenant: Cisco Tenant Object
:param override: Purge existing configurations for this Tenant in BAM
:param fetch_endpoints: Boolean - Import endpoints
:return:
"""
if... | 8cf8640848c8830ea9e78f326672965806451483 | 3,612,705 |
def get_supported_formats(request):
"""Return a dictionary of possible conversions between image formats.
CSRF protection is not required on GET request."""
if request.method == "GET":
return JsonResponse(data=SUPPORTED_FORMATS)
else:
return HttpResponse(content="Use GET method", status=... | cf3c2e8341cdd41ef1129eec8603fe222bd43d6c | 3,612,706 |
import functools
def tf_cache_template(function, scope=None, *args, **kwargs):
"""
A decorator for class methods that define TensorFlow operations.
The function is first wrapped in a variable_scope() that allows
us to specify a initializer, regularizer etc.
The result is then wrapped in a make_t... | 8b0d23cc9d249b79c1d7ceb67545fbee45c6b87c | 3,612,707 |
def nms(dets, thresh, soft_nms=False):
"""Dispatch to either CPU or GPU NMS implementations."""
if dets.shape[0] == 0:
return []
elif soft_nms:
return cpu_soft_nms(dets, thresh, method = 1)
else:
return cpu_nms(dets, thresh) | 9a1c67f35a9cdb0ff6cb2e95b97818f2cae90028 | 3,612,708 |
def mean_expression(df, annotation, stage_regex=r".*", normal=False):
"""Return the mean expression values of the subset of samples.
Parameters
----------
df: pandas.DataFrame
Each row is a gene and each column is a sample.
annotation: pandas.DataFrame
A data frame w... | 7e404aa4a69b7b967d830463d21d611e0cd47b36 | 3,612,709 |
def get_contract_stat():
"""
获取合同金额
:return: 合同数、总计金额
"""
mongo_db.connect_db('ext_system')
contracts = do_search('contract_t', {})
_count = len(contracts)
_total = 0.
for _r in contracts:
if (len(_r[u'金额']) > 0) and ((_r[u'金额'].replace('.', '')).isdigit()):
_tota... | 9112fbd59c2637b393d42484ea857b62c03d7815 | 3,612,710 |
from typing import List
def split_env_items(env_string: str) -> List[str]:
"""Splits space-separated variable assignments into a list of individual assignments.
>>> split_env_items('VAR=abc')
['VAR=abc']
>>> split_env_items('VAR="a string" THING=3')
['VAR="a string"', 'THING=3']
>>> split_env... | 2f62989c25987f40cd9515f39092d3ef05375fc6 | 3,612,711 |
def tree2diagram(tree, dom=Ty()):
"""
Takes a depccg.Tree in JSON format,
returns a :class:`discopy.biclosed.Diagram`.
"""
if 'word' in tree:
return Word(tree['word'], cat2ty(tree['cat']), dom=dom)
children = list(map(tree2diagram, tree['children']))
dom = Ty().tensor(*[child.cod for... | bfa5e34ae2c41dfd72e7e8e45758767de7908798 | 3,612,712 |
def intersection_over_box(chips, boxes):
"""
intersection area over box area
:param chips: C
:param boxes: B
:return: iob, CxB
"""
M = chips.shape[0]
N = boxes.shape[0]
if M * N == 0:
return np.zeros([M, N], dtype='float32')
box_area = bbox_area(boxes) # B
inter_... | 52710d712dcb7d5025a8ee29590477916144f4a5 | 3,612,713 |
def get_past_seasons(num_seasons):
"""
Go back num_seasons from the current one
"""
season = CURRENT_SEASON
seasons = []
for i in range(num_seasons):
season = get_previous_season(season)
seasons.append(season)
return seasons | 26f66725ea5fb08b4686a6fbbf2ee6f7ee57312b | 3,612,714 |
from typing import List
import logging
def _CollectGpuSamples(
vm: virtual_machine.BaseVirtualMachine) -> List[sample.Sample]:
"""Run CUDA memcpy on the cluster.
Args:
vm: The virtual machine to run the benchmark.
Returns:
A list of sample.Sample objects.
"""
if not nvidia_driver.CheckNvidiaSm... | 4ebf827517ddd645cf361453401451eaf97f1d6a | 3,612,716 |
def remove_host(config, sync_name, name):
""" remove sync """
sync = get_sync(config, name)
sync['hosts'].remove(get_host(config, sync_name, name))
return True | e14133e6dc174906a3fd35ce975cfc2af3510d57 | 3,612,717 |
import time
def slow_function():
"""
模拟思考过程
:return: 结果
"""
time.sleep(3)
return 43 | ca6b8333f39f497a441ff335670d51a1ca37450f | 3,612,718 |
import random
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorithms.
(http://www.awsarchitectureblog.com/2015/03/backoff.html)
Args:
... | 0a5c233d3e0e58873d29de7e3d878fbcf3d0c47a | 3,612,719 |
def get_lldp_neighbors(device):
"""Get current LLDP neighbor information.
Return a two-level dictionary with the LLDP neighbor information..
The first-level key is the local port (aka interface) name.
The second-level keys are 'system' for the remote system name
and 'port' for the remote port ID. O... | 5ac62b9e29b7e8814a41585ad0db9af85ef80989 | 3,612,720 |
def _get_temporal_concepts(world: owlready2.World) -> set:
"""
Fetches all classes, data and object properties that are used within the definition (equivalence or subclass) of
some temporal criticality phenomenon. Also regards SWRL rules.
:param world: World to get temporal concepts in.
:return: A s... | b29d858bdc155a3ba35453bf72fc59302b042ab7 | 3,612,721 |
def _pathcontains_filter(files, pathcontains):
"""Filtre par chemin"""
filtered_files = []
for file in files:
if pathcontains in file:
filtered_files.append(file)
return filtered_files | 9a37b1e361cc37e8a046b297115a6374c78abd2f | 3,612,722 |
def main():
"""Main function. Set up widgets, calculate, plot."""
st.set_page_config(layout='wide')
# Set up sidebar input widgets
with st.sidebar:
P_des, n_des, p, r, n_max = params()
complementary, inclusive, out_txt = range_cond()
# Proportions of output screen
left_col... | 9039593ee1b807192015e33a7649750a545ed8da | 3,612,725 |
def function_to_be_decorated():
"""This is documentation for function_to_be_decorated."""
return True | ebb9602ba27e98750300e27dedfc9dd2c94f896d | 3,612,726 |
def read_file_utf8(data_file, mode='more'):
"""
读文件, 原文件和数据文件
:return: 单行或数组
"""
try:
with open(data_file, 'r', encoding='utf8') as f:
if mode == 'one':
output = f.read()
return output
elif mode == 'more':
output = f.rea... | 6b0275766783e648ac3f7099a345dbae289dc8a1 | 3,612,727 |
from typing import Optional
from typing import Dict
from typing import Any
async def load_fake_data(quantity: Optional[int] = 0) -> Dict[str, Any]:
"""loading fake data
Returns:
redirect to root path /
"""
await API_functools.insert_default_data(quantity=quantity)
return RedirectResponse(... | 7c7733cf81f4322c65f854cc34aeeecef6063df8 | 3,612,728 |
import requests
def sync_send(msg: SMSMessage, secret: str) -> str:
"""Synchronously send an SMSMessage, using the requests library.
Returns:
The response from the server.
Raises:
SMSSendError if sending failed.
"""
headers = {"X-Profile-Secret": secret}
data = msg.as_dict()
... | 4614bf85898d108dbd7b24eb3fc3ef547fab2fa6 | 3,612,729 |
def expmap(u, x0):
"""
This function maps a vector u lying on the tangent space of x0 into the manifold.
Parameters
----------
:param u: vector in the tangent space
:param x0: basis point of the tangent space
Returns
-------
:return: point on the manifold
"""
if np.ndim(x0)... | 97bf21fc96c0ec3cf8f1b566f7747c764fc4efcc | 3,612,730 |
from typing import Dict
def get_abertura_context(document: Dict, max_size: int = 4000) -> str:
"""Returns the abertura content of the document_text.
"""
document_text = document['text']
max_size = update_max_size(document, max_size=max_size)
context = document_text[:max_size]
return context | 3183ec016606f2781f63809a1416a85b6e76cfd2 | 3,612,732 |
def page(cursor=None, limit=None, user=None):
"""# Retrieve paged Webhooks
Receive a list of up to 100 Webhook objects previously created in the Stark Bank API and the cursor to the next page.
Use this function instead of query if you want to manually page your requests.
## Parameters (optional):
- ... | 84c0fc0861222b85187025399b14006372966be4 | 3,612,733 |
def integer_at_least(actual_value, expected_value):
"""Assert that actual_value is an integer of at least expected_value."""
result = isinstance(actual_value, int)
if result:
result = actual_value >= expected_value
if result:
return result
else:
raise AssertionError(
... | c4f601dd983d96a10372feabd67258a0515ac887 | 3,612,734 |
def calculate_his3p_small_wh_coefficients():
"""
Calculate the Walsh-Hadamard coefficients of the His3p(small) fitness functions.
"""
return _calculate_wh_coefficients_complete('his3p_small') | c6cc09a5719a94dfa38a2998cef03bb75fc15102 | 3,612,735 |
def eq(a, b, n):
"""Euler's quadratic formula"""
## : coefficient: a, b int
## : n int | n >= 0
rst = n**2 + a*n + b
return rst | c5f9619e22d3131b905eba6bfe509020d1f7c917 | 3,612,736 |
import math
def generate_lattice(ltype, volume, minvec=tol_m, minangle=pi/6, max_ratio=10.0, maxattempts = 100, **kwargs):
"""
Generates a lattice (3x3 matrix) according to the space group symmetry and
number of atoms. If the spacegroup has centering, we will transform to
conventional cell setting. If... | 098d028e72b1c66bf7c43d213b6cf1842a4deac1 | 3,612,737 |
def is_unqdn(cfg, name):
"""
Returns True if name has enough elements to
be a unqdn (hostname.realm.site_id)
False otherwise
"""
parts = name.split(".")
if len(parts) >= 3:
return True
else:
return False | 28e530816ea418473858d2cb59e572d25a9f2d81 | 3,612,738 |
def get_proj(geom, proj_list=None):
"""Determine best projection for input geometry
"""
out_srs = None
if proj_list is None:
proj_list = gen_proj_list()
#Go through user-defined projeciton list
for projbox in proj_list:
if projbox.geom.Intersects(geom):
out_srs = proj... | 8d63c8a9642a0b78063f039553c5bcd9072f9958 | 3,612,739 |
def format_vertex(body: Json) -> Json:
"""Format vertex data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
vertex: Json = body["vertex"]
if "_oldRev" in vertex:
vertex["_old_rev"] = vertex.pop("_oldRev")
if "new" in body or "old" in bo... | a0fc806c9bba67b2044fc10e99e5b96a131c0ac1 | 3,612,740 |
def get_tag_list(frmt):
"""
Gets a list of tags from the XML conversion output of a specific document.
:param frmt: format/extension of the input document (document must be present in the tests/in folder)
:return: list of element tags
"""
oxobj = OxGaWrap(f'tests/in/test.{frmt}')
tree = oxob... | 83c4b94c839c0499e57a2bd6f2eb630da253be7a | 3,612,741 |
def haversine(pt, lat2=42.355589, lon2=-71.060175):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
lon1 = pt[0]
lat1 = pt[1]
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])... | 38d5b0ab53485f8267e4e06a15fcd533a158883c | 3,612,743 |
def check_ip(ip):
"""Checks whether given IP address is valid or not.
Implements only basic checking."""
if ip is not None:
iplst = ip.split('.')
if len(iplst) != 4:
return False
for num in iplst:
if int(num) > 255 or int(num) < 0:
return False... | a0342cfb91c1b8759dc22b5ece90f6bf6203f951 | 3,612,745 |
def adcp_earth_vertical(w):
"""
Description:
Wrapper function to compute the Upward Velocity Profile (VELPROF-VLU)
from Earth coordinate transformed velocity profiles as defined in the
Data Product Specification for Velocity Profile and Echo Intensity -
DCN 1341-00750.
Impl... | a80444f3f0585156570d609160245a89873cab23 | 3,612,746 |
import re
def to_comma_type(numpy_type):
"""
convert a single numpy type to comma type
numpy arrays are unrolled and converted to a prefixed comma type
>>> from comma.csv.format import *
>>> to_comma_type('f8')
'd'
>>> to_comma_type('S12')
's[12]'
>>> to_comma_type('3u4')
'3u... | e17ea2da06031643dbf1a5227b4ed7c0e8d44342 | 3,612,747 |
def is_valid_medialive_channel_arn(mlive_channel_arn):
"""Determine if the ARN provided is a valid / complete MediaLive Channel ARN"""
if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn:
return True
else:
return False | c2ddbdef180eabbc4f22399dd895b99555bb05d6 | 3,612,748 |
def Faculty4(request):
"""
Returns the render for the sdg graph
"""
data = dataFrameSDG().drop(columns = "Misc")
data2 = data.T
data3 = data2.reset_index(level = 0)
data4=data3.rename(columns=data3.iloc[0]).drop(data3.index[0])
figure = px.bar(data4, x = "Faculty", y = FacultyIndex["... | 55965277447557f361445b790f1501d900c6ce92 | 3,612,749 |
def est_vega(S, K, r, sigma, T):
""" Define a function to calculate the vega
which is also the derivative of option with respect to sigma
"""
d = (np.log(S/K) + (r + 0.5 * sigma* sigma)* T) / (sigma * np.sqrt(T))
vega = S * np.sqrt(T) * norm.pdf(d)
return vega | 91c1a7c390edeff4ed79028098fd8073481ce2a4 | 3,612,750 |
from typing import Tuple
def generate_a_pair() -> Tuple[int, int]:
"""
Generate private ephemeral a and public key A.
Returns:
Tuple (private a (int), public A (int))
"""
prime = _get_srp_prime()
generator = _get_srp_generator()
a = _to_int(_generate_random_bytes(32)) # RFC-5054... | a806f7fcd89f991881d21862c590d8f6f8234c1a | 3,612,751 |
def perform_data_filtering_q3(data):
"""
Takes the original DataFrame.
Returns the altered DataFrame necessary for Q3.
"""
df = data
angina_presence = df['cp'] <= 2
df['cp'] = np.where(angina_presence, 1, 0)
return df | 1806defe886da659a2f1c34758051720dc7883bc | 3,612,752 |
def reload_config(test_run: RunnerEnvironment) -> dict:
"""Load configuration of test as JSON-object."""
return load(open(test_run.test_env.config_file, 'r')) | f94389fabc8e60d55992d30a176e9c439e1ae9f7 | 3,612,753 |
def generate_random_particle(_id, input_size, neurons):
"""Function to generate random particle to init PSO algorithm"""
position = []
speed = []
n_neurons = sum(neurons)
n_weights = input_size * neurons[0]
for i in range(len(neurons) - 1):
n_weights = n_weights + neurons[i]*neurons[i+1]... | b65f452a396d55ea44c696976894f750ea5719d7 | 3,612,754 |
def convert_tf_to_crowdsourcing_format(images, detections):
"""
Args:
images: dictionary {image_id : image info} (images from Steve's code)
detections: detection output from multibox
Returns:
dict : a dictionary mapping image_ids to bounding box annotations
"""
image_annotation... | ba25ee0cb2eb570f745326dfe85c2bda972a3659 | 3,612,756 |
import scipy
def horn_schunk_flow(img0,img2,lambada,max_iter,epsilon):
"""
:param img0: first frame
:param img2: second frame
:param lambada: hyper parameter
:param max_iter: threshold for iterations
:param epsilon: decay rate
:return: flow and gradient
"""
decay=10000
i=0
... | 5ac1ce6a97389a32bd71ac3469bcf9c217ae3aac | 3,612,757 |
from typing import Any
def true_pred_hist(
y_true: NumArray,
y_pred: NumArray,
y_std: NumArray,
ax: Axes = None,
cmap: str = "hot",
bins: int = 50,
log: bool = True,
truth_color: str = "blue",
**kwargs: Any,
) -> Axes:
"""Plot a histogram of model predictions with bars colored ... | 4d47cbda361f3dde0261ef34880736c77f4131d1 | 3,612,758 |
from typing import List
from typing import Union
def read_typetree(
nodes: List[Union[dict, TypeTreeNode]], reader: EndianBinaryReader
) -> dict:
"""Reads the typetree of the object contained in the reader via the node list.
Parameters
----------
nodes : list
List of nodes... | 4f90326d31c7d11270cf72b798a110bc798118c8 | 3,612,759 |
import sqlite3
from typing import cast
def read_bip32_keys_gap_size(db: sqlite3.Connection, account_id: int,
masterkey_id: int, prefix_bytes: bytes) -> int:
"""
Identify the trailing BIP32 gap (of unused keys) at the end of a derivation sequence.
For now we create keys in a BIP32 sequence sequent... | ab9cbc8445fe1f762420a635d73ece26fa8c8634 | 3,612,760 |
from typing import Optional
from typing import Dict
from typing import Any
def convert_bool_to_0_or_1(
params: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
"""Converts all bool values in dict to "0" or "1".
Slack APIs safely accept "0"/"1" as boolean values.
Using True/False (bool in Pytho... | cfce80e67a7251a2d85506386cc2507dd9702dd0 | 3,612,761 |
def calc_kin_temp(vel, nums, masses, kB):
"""
Calculates the kinetic energy and temperature.
Parameters
----------
kB: float
Boltzmann constant in chosen units.
masses: numpy.ndarray
Mass of each species.
nums: numpy.ndarray
Number of particles of each species.
... | 003231602a831e11befaf891fee46ee2897b0658 | 3,612,762 |
def calc_P_remain(
P_avail: pd.DataFrame,
P_req: pd.Series,
gidx: wio.GearMultiIndexer,
):
"""Return `p_avail - p_req` for all gears > g2 in `gwot`. """
c = wio.pstep_factory.get().cycle
## Drop pandas axis or else substraction would fail with:
# ValueError: cannot join with no overla... | 56bb46c12a861d3f6eb711abe069a655f3efc988 | 3,612,763 |
def load_user(user_id: str) -> User:
"""Return the current JWT user."""
return user_domain_logic.get_user(user_id) | cbf6566e7ceabaac8c5a5cc9293b5650562d7337 | 3,612,765 |
def get_argparser():
"""
Returns an argument parser for this script
"""
parser = ArgumentParser(description='Predict using a U-Time model.')
parser.add_argument("--folder_regex", type=str, required=False,
help='Regex pattern matching files to predict on. '
... | 27cdcfb8f0bd5dc0df6898b4f8e2fddb408d48d1 | 3,612,767 |
from typing import Callable
def remove_empty_routes(operator: Callable[..., Solution]):
"""
Wrapper function that removes empty routes from the returned solution
instance. These routes may come into existence because all customers have
been removed by e.g. a destroy operator.
"""
@wraps(operat... | 4f3ce6731404b1edb76ccfe7dc6f1857576b017b | 3,612,768 |
from typing import Optional
def interleaved_gate_fidelity_bounds(irb_decay: float, rb_decay: float, dim: int,
unitarity: Optional[float] = None):
"""
Use observed rb_decay to place a bound on fidelity of a particular gate with given interleaved
rb decay.
Optionall... | 90c1a2e25770333a510ec0d63bd4ceb0de689b46 | 3,612,770 |
def session_factory_from_settings(settings):
"""
Convenience method to construct a ``MongoSessionFactory`` from Paste config
settings. Only settings prefixed with "mongo.sessions" will be inspected
and, if needed, coerced to their appropriate types (for example, casting
the ``timeout`` value as an `... | b75dd42876bd271da6f1cf0acf0528a91984080c | 3,612,771 |
def f_stock():
"""
Real Name: b'F Stock'
Original Eqn: b'INTEG ( F Acquisition Rate-F Shipment Rate, 400)'
Units: b'SKU'
Limits: (None, None)
Type: component
b''
"""
return integ_f_stock() | 1fc8b905d16543787aab4128d6dc973b8ae19daf | 3,612,772 |
def deep_ensemble_predict(x,
models,
training_setting,
uncertainty_type='entropy'):
"""Deep Ensembles uncertainty estimator.
Args:
x: `numpy.ndarray`, datapoints from input space, with shape [B, H, W, 3],
where B the batch size... | a5fb73b4c1a8e3e3230a612783cad54766f7531f | 3,612,773 |
def tsPredFig(df, item, predictDays):
"""
This function is to predict the community demand using Prophet Time Series Algorithms.
Args:
df (dataframe) : dataset
item (str) : product type that was selected
predictDays(int): days for prediction
Returns:
forecast : da... | 0c7fdedf7fd5de803654b1d5e3754ab4554480ab | 3,612,774 |
from typing import Optional
from typing import Tuple
from typing import Set
def remove_redundant_latents(
graph: nx.DiGraph, tag: Optional[str] = None
) -> Tuple[nx.DiGraph, Set[str]]:
"""Remove redundant latent variables.
:param graph: A latent variable DAG
:param tag: The tag for which variables ar... | 0250b9f01e872b70f277eaa05561e094199382fe | 3,612,775 |
from typing import OrderedDict
def get_chattering_species(atom_followed="C"):
"""
return chattering species
the chatteing reaction infomation is just for reference, will not use it
as long as the paired chattering species is provided, should be fine
better make them in the same order
"""
f... | 264702e1b1ca474c6cfe45035d9d5aad2e653d07 | 3,612,776 |
def word_accuracy(predictions, labels):
"""predictions and labels are of shape Batches x NUM_Digits_Pred and Batches x NUM_Digits_Label
"""
predictions, labels = pad_pred_label(predictions, labels)
predictions.get_shape().assert_is_compatible_with(labels.get_shape())
if labels.dtype != predictions.d... | 0d26ba91fb90ff9d71241b5181bddccad71efce9 | 3,612,777 |
import types
def inherit_doc(cls):
"""
This decorator simply add docstrings from parent class to subclass methods if no documentation
exists on the subclass method.
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent... | c3e35190b9f604e39119c21bd791e699f392f81e | 3,612,778 |
import pickle
def editSearch(request, search_id=None):
"""
Handler for editing an existing search
"""
#load the search passed in
if search_id:
search = Search.objects.get(id=search_id)
if search.user != request.user and search.isPublic == False:
return HttpResponse("<p... | 2df04456a07a5329347a72b0ebcc09193b83beda | 3,612,779 |
def predict_squad(input_file_path, output_file, vocab_file,
doc_stride, predict_batch_size, max_query_length,
max_seq_length, do_lower_case,
version_2_with_negative=False)->int:
"""Makes predictions for a squad dataset."""
eval_examples = read_squad_examples(
... | aef196b459519c1c3a71189b7fec187fa5a40e17 | 3,612,780 |
def solution(A):
"""
This one is a tricky one as the solution requires doing a bit of research on
how to best detect overlapping ranges (a circle projected onto a axis
becomes simply a range from A to B).
The best performance can be achieved with the following approach:
1. First pre-process all... | 05634fef061e7e9f1462614219e976161fd8c675 | 3,612,781 |
def patched_novoed_api(mocker):
"""Patches NovoEd API functionality"""
return mocker.patch("novoed.tasks.api") | 9bd7b15a6b34c9c659755fb36e422698a82be063 | 3,612,782 |
def create_layer_with_task_specific_linear_heads(num_classes_for_tasks):
"""Returns a `pathnet_lib.ComponentsLayer` with linear task specific layers.
This is a small helper function to create a layer of fully connected
components for multiple classification tasks (with possibly different
numbers of classses). ... | 2c064cf350d56188c0c54952b4d74e6e770720ce | 3,612,783 |
from rastervision.pipeline.file_system import download_if_needed
from re import A
def deserialize_albumentation_transform(tf_dict: dict) -> A.BasicTransform:
"""Deserialize an albumentations transform serialized by
`serialize_albumentation_transform()`.
If the input dict contains a `lambda_transforms_pat... | 630e20a612b89f5bc5a3513cda159714d4825bad | 3,612,784 |
def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | 2e76cc90dd8e1967c2ae6be21230746132a2de09 | 3,612,785 |
def fpn_classifier_graph(rois, feature_maps, image_meta,
pool_size, num_classes, train_bn=True):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates... | f34d1fbd9aafa525cb6c892e788870fa1de54871 | 3,612,786 |
def make_matcher(patterns):
"""Returns a function that evaluates if a path match one of the patterns.
The compared paths are first converted to unicode and decomposed.
This is neccesary because the way `os.walk` read unicode paths could vary.
For instance, it might returns a decomposed unicode string r... | abaecdba1f28cbdad53b7afd9d447b7a2bdd5be6 | 3,612,788 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.