content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
def render_orchestrator_inputs() -> Union[Driver, None]:
""" Renders input form for collecting orchestrator-related connection
metadata, and assembles a Synergos Driver object for subsequent use.
Returns:
Connected Synergos Driver (Driver)
"""
with st.sidebar.... | d67f3a40347a2f247183e2b9092429ca118bc739 | 22,852 |
def type_assert_dict(
d,
kcls=None,
vcls=None,
allow_none: bool=False,
cast_from=None,
cast_to=None,
dynamic=None,
objcls=None,
ctor=None,
desc: str=None,
false_to_none: bool=False,
check=None,
):
""" Checks that every key/value in @d is an instance of @kcls: @vcls
... | 8a5590a86a0f2e1b4dbef5218c4a294dde3675e1 | 22,854 |
def get_missing_ids(raw, results):
"""
Compare cached results with overall expected IDs, return missing ones.
Returns a set.
"""
all_ids = set(raw.keys())
cached_ids = set(results.keys())
print("There are {0} IDs in the dataset, we already have {1}. {2} are missing.".format(len(all_ids), len... | cb380c12f26de8b4d3908964f4314bc7efe43056 | 22,855 |
import collections
def _spaghettinet_edgetpu_s():
"""Architecture definition for SpaghettiNet-EdgeTPU-S."""
nodes = collections.OrderedDict()
outputs = ['c0n1', 'c0n2', 'c0n3', 'c0n4', 'c0n5']
nodes['s0'] = SpaghettiStemNode(kernel_size=5, num_filters=24)
nodes['n0'] = SpaghettiNode(
num_filters=48,
... | 93b98a29654f8a838f39d6bfa59f78719ff6c42c | 22,856 |
def instance_of(type):
"""
A validator that raises a :exc:`TypeError` if the initializer is called
with a wrong type for this particular attribute (checks are perfomed using
:func:`isinstance` therefore it's also valid to pass a tuple of types).
:param type: The type to check for.
:type type: t... | 2d41d457e9f7e60fa5e5d77f83454ca75dc112f7 | 22,857 |
def ass(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#ass"""
return filter(stream, ass.__name__, *args, **kwargs) | 7f9d88fe1fdeb2337acce25e8b40db94d59f8748 | 22,859 |
def resultcallback(group):
"""Compatibility layer for Click 7 and 8."""
if hasattr(group, "result_callback") and group.result_callback is not None:
decorator = group.result_callback()
else:
# Click < 8.0
decorator = group.resultcallback()
return decorator | 1eb938400c90667eb532366f5ca83d02dd6429e1 | 22,860 |
from licensedcode import cache
def get_license_matches(location=None, query_string=None):
"""
Return a sequence of LicenseMatch objects.
"""
if not query_string:
return []
idx = cache.get_index()
return idx.match(location=location, query_string=query_string) | 5d2891d36dd10e6c4d1c24280df86d1bf39e464a | 22,861 |
def compute_corrector_prf(results, logger, on_detected=True):
"""
References:
https://github.com/sunnyqiny/
Confusionset-guided-Pointer-Networks-for-Chinese-Spelling-Check/blob/master/utils/evaluation_metrics.py
"""
TP = 0
FP = 0
FN = 0
all_predict_true_index = []
all_gol... | 1f86b5f7cd91aba9a50007493d83cd3480eb9e20 | 22,862 |
def nonzero_sign(x, name=None):
"""Returns the sign of x with sign(0) defined as 1 instead of 0."""
with tf.compat.v1.name_scope(name, 'nonzero_sign', [x]):
x = tf.convert_to_tensor(value=x)
one = tf.ones_like(x)
return tf.compat.v1.where(tf.greater_equal(x, 0.0), one, -one) | 1955f37bece137537d53cde6681a8f56554cafea | 22,863 |
def tls_control_system_tdcops(tls_control_system):
"""Control system with time-dependent collapse operators"""
objectives, controls, _ = tls_control_system
c_op = [[0.1 * sigmap(), controls[0]]]
c_ops = [c_op]
H1 = objectives[0].H
H2 = objectives[1].H
objectives = [
krotov.Objective(... | b94f438291671e863bb759ce024a0e42e6230481 | 22,864 |
def create_new_credential(site_name,account_name, account_password):
"""Function to create a new account and its credentials"""
new_credential = Credentials(site_name,account_name, account_password)
return new_credential | 127335a31054d1b89521a1bc8b354ad51e193be6 | 22,865 |
from typing import Dict
def prepare_request_params(
request_params: Dict, model_id: Text, model_data: Dict
) -> Dict:
""" reverse hash names and correct types of input params """
request_params = correct_types(request_params, model_data["columns_data"])
if model_data["hashed_indexes"]:
request... | c7aee17db83e96cb3bcf6ce75ea650414035654a | 22,867 |
from typing import List
def get_all_listening_ports() -> List[int]:
"""
Returns all tcp port numbers in LISTEN state (on any address).
Reads port state from /proc/net/tcp.
"""
res = []
with open('/proc/net/tcp', 'r') as file:
try:
next(file)
for line in file:
... | cfc1b4b93358954ad802ce3727bd9d424ef9d136 | 22,869 |
async def mock_race_result() -> dict:
"""Create a mock race-result object."""
return {
"id": "race_result_1",
"race_id": "190e70d5-0933-4af0-bb53-1d705ba7eb95",
"timing_point": "Finish",
"no_of_contestants": 2,
"ranking_sequence": ["time_event_1", "time_event_2"],
... | 33a2889bcb2665642a3e5743128a478bb103a82b | 22,870 |
import re
import binascii
def qr_to_install_code(qr_code: str) -> tuple[zigpy.types.EUI64, bytes]:
"""Try to parse the QR code.
if successful, return a tuple of a EUI64 address and install code.
"""
for code_pattern in QR_CODES:
match = re.search(code_pattern, qr_code, re.VERBOSE)
if... | 91ec3f90385e95b94c47c338f56b26315ff12e99 | 22,871 |
def vwr(scene, analyzer, test_number, workbook=None, sheet_format=None, agg_dict=None):
"""
Calculates Variability Weighted Return (VWR).
:param workbook: Excel workbook to be saved to disk.
:param analyzer: Backtest analyzer.
:param sheet_format: Dictionary holding formatting information such as co... | 7fa8c9794e443be91d0cf246c209dfdc86e19f54 | 22,872 |
def dec2hms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
fhour = dec*(HOUR/DEGREE)
hour = int(fhour)
fminute = (fhour - hour)*MINUTE
minute = int(fminute)
second = (fminut... | 4c2c564631d431d908f66486af40e380598f2724 | 22,873 |
def logfpsd(data, rate, window, noverlap, fmin, bins_per_octave):
"""Computes ordinary linear-frequency power spectral density, then multiplies by a matrix
that converts to log-frequency space.
Returns the log-frequency PSD, the centers of the frequency bins,
and the time points.
Adapted from Matlab... | cf9a9ee3a248760e6bfa36a82ae782d607269b10 | 22,874 |
def ppg_dual_double_frequency_template(width):
"""
EXPOSE
Generate a PPG template by using 2 sine waveforms.
The first waveform double the second waveform frequency
:param width: the sample size of the generated waveform
:return: a 1-D numpy array of PPG waveform
having diastolic peak at the... | 9c04afb7687e19a96fb84bf1d5367dc79ce6ceea | 22,875 |
def str_input(prompt: str) -> str:
"""Prompt user for string value.
Args:
prompt (str): Prompt to display.
Returns:
str: User string response.
"""
return input(f"{prompt} ") | ac6c3c694adf227fcc1418574d4875d7fa637541 | 22,877 |
def action(ra_deg, dec_deg, d_kpc, pm_ra_masyr, pm_dec_masyr, v_los_kms,
verbose=False):
"""
parameters:
----------
ra_deg: (float)
RA in degrees.
dec_deg: (float)
Dec in degress.
d_kpc: (float)
Distance in kpc.
pm_ra_masyr: (float)
RA proper motion... | 0e707bff67cee3c909213f14181927a14d5d5656 | 22,878 |
def getProcWithParent(host,targetParentPID,procname):
""" returns (parentPID,procPID) tuple for the procname with the specified parent """
cmdStr="ps -ef | grep '%s' | grep -v grep" % (procname)
cmd=Command("ps",cmdStr,ctxt=REMOTE,remoteHost=host)
cmd.run(validateAfter=True)
sout=cmd.get_re... | 77f4f13eb381dc840eee26875724cd6e1cdf1e57 | 22,879 |
def temporal_autocorrelation(array):
"""Computes temporal autocorrelation of array."""
dt = array['time'][1] - array['time'][0]
length = array.sizes['time']
subsample = max(1, int(1. / dt))
def _autocorrelation(array):
def _corr(x, d):
del x
arr1 = jnp.roll(array, d, 0)
ans = arr1 * ar... | 69640da51fa94edd92e793f2c86ac34090e70a28 | 22,880 |
import json
def kv_detail(request, kv_class, kv_pk):
"""
GET to:
/core/keyvalue/api/<kv_class>/<kv_pk>/detail/
Returns a single KV instance.
"""
Klass = resolve_class(kv_class)
KVKlass = Klass.keyvalue_set.related.model
try:
kv = KVKlass.objects.get(pk=kv_pk)
except KVKlas... | bd8961c25e39f8540b57753b8f923229e77ae795 | 22,881 |
from typing import Protocol
import json
def opentrons_protocol(protocol_id):
"""Get OpenTrons representation of a protocol."""
current_protocol = Protocol.query.filter_by(id=protocol_id).first()
if not current_protocol:
flash('No such specification!', 'danger')
return redirect('.')
i... | 3a8cc4355763f788f01bb1d95aa43f5cb249a68f | 22,882 |
def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: `comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.... | e0997313c13446150ed3a0f402b2df74089aa4e9 | 22,884 |
from typing import List
def get_nodes_for_homek8s_group(inventory, group_name) -> List[str]:
"""Return the nodes' names of the given group from the inventory as a list."""
hosts_dict = inventory['all']['children']['homek8s']['children'][group_name]['hosts']
if hosts_dict:
return list(hosts_dict.keys())
el... | 806394259816ec4311e69dcd46e7b111c7ca0652 | 22,885 |
def is_blank_or_none(value: str):
"""
Returns True if the specified string is whitespace, empty or None.
:param value: the string to check
:return: True if the specified string is whitespace, empty or None
"""
try:
return "".__eq__(value.strip())
except AttributeError:
retur... | 062e1ab33fc5043435af9e97cdf2443ffc4625bd | 22,886 |
import typing
def __get_play_widget(function: typing.Any) -> typing.Any:
"""Generate play widget.
:param function: Function to associate with Play.
:return: Play widget.
"""
play = widgets.interactive(
function,
i=widgets.Play(
value=0,
min=0,
m... | 5bb63256f84f1c6f50e2ae007a08e6e794535bc5 | 22,887 |
def add_data_to_profile(id, profile_id, read_only, tree_identifier, folder_path=None, web_session=None):
"""Shares data to user group
Args:
id (int): The id of the data
profile_id (int): The id of profile
read_only (int): The flag that specifies whether the data is read only
tre... | 489d246b90506b7581ee8aef66c7f5f2ba6b9b88 | 22,888 |
def get_activation_function(activation):
"""
Gets an activation function module given the name of the activation.
:param activation: The name of the activation function.
:return: The activation function module.
"""
if activation == 'ReLU':
return nn.ReLU()
elif activation == 'LeakyR... | ae5d8e91667e2dc4fe34eb1ac96cff329d542103 | 22,889 |
def get_value_from_time(a_node="", idx=0):
"""
gets the value from the time supplied.
:param a_node: MFn.kAnimCurve node.
:param idx: <int> the time index.
:return: <tuple> data.
"""
return OpenMaya.MTime(a_node.time(idx).value(), OpenMaya.MTime.kSeconds).value(), a_node.value(idx), | 77c6cb47c4381df3537754dc66e03ef4366557de | 22,890 |
def getrinputs(rtyper, graph):
"""Return the list of reprs of the input arguments to the 'graph'."""
return [rtyper.bindingrepr(v) for v in graph.getargs()] | bb0f8861a29cd41af59432f267f07ff67601460c | 22,891 |
def mars_reshape(x_i):
"""
Reshape (n_stacks, 3, 16, 112, 112) into (n_stacks * 16, 112, 112, 3)
"""
return np.transpose(x_i, (0, 2, 3, 4, 1)).reshape((-1, 112, 112, 3)) | d842d4d9b865feadf7c56e58e66d09c4a3389edf | 22,893 |
def Rz_to_coshucosv(R,z,delta=1.):
"""
NAME:
Rz_to_coshucosv
PURPOSE:
calculate prolate confocal cosh(u) and cos(v) coordinates from R,z, and delta
INPUT:
R - radius
z - height
delta= focus
OUTPUT:
(cosh(u),cos(v))
HISTORY:
2012-11-27 -... | f01ed002c09e488d89cfd4089343b16346dfb5fd | 22,894 |
import ast
import numpy
def rpFFNET_createdict(cf,ds,series):
""" Creates a dictionary in ds to hold information about the FFNET data used
to gap fill the tower data."""
# get the section of the control file containing the series
section = pfp_utils.get_cfsection(cf,series=series,mode="quiet")
... | 60646de63106895eeb716f763c49195b9c5459e8 | 22,895 |
def svn_client_relocate(*args):
"""
svn_client_relocate(char dir, char from_prefix, char to_prefix, svn_boolean_t recurse,
svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t
"""
return _client.svn_client_relocate(*args) | 55e78e311d461e5a20e5cd04778e6c8431a6d990 | 22,896 |
def get_pairs(image1, image2, global_shift, current_objects, record, params):
""" Given two images, this function identifies the matching objects and
pairs them appropriately. See disparity function. """
nobj1 = np.max(image1)
nobj2 = np.max(image2)
if nobj1 == 0:
print('No echoes found in ... | 5013764c7e2a1d5e12abc2107ffdbfca640f1423 | 22,897 |
def getComparedVotes(request):
"""
* @api {get} /getComparedVotes/?people_same={people_same_ids}&parties_same={parties_same_ids}&people_different={people_different_ids}&parties_different={parties_different_ids} List all votes where selected MPs/PGs voted the same/differently
* @apiName getComparedVotes
... | e49b2e1b181761e56795868a3dd6ff5a0452cd05 | 22,898 |
def get_bits(register, index, length=1):
"""
Get selected bit(s) from register while masking out the rest.
Returns as boolean if length==1
:param register: Register value
:type register: int
:param index: Start index (from right)
:type index: int
:param length: Number of bits (default 1... | 0663d925c2c74ece359a430392881cf24b75a575 | 22,899 |
def addactual():
"""Add actual spendings"""
if request.method == "POST":
allPayments = []
# Current user that is logged-in saved in variable
userId = session["user_id"]
month = request.form.get("month")
housing = request.form.get("housing")
housing = float(housin... | ccf7d9c362aa1f250959dce51032e43b00ffe412 | 22,900 |
def parse_move(line):
""" Parse steps from a move string """
text = line.split()
if len(text) == 0:
raise ValueError("No steps in move given to parse. %s" % (repr(line)))
steps = []
for step in text:
from_ix = alg_to_index(step[1:3])
if len(step) > 3:
if step[3] ... | 660374a82c19da61df3e0f8468f09c5df7d3be5e | 22,901 |
def get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Args:
node_name: Name of the node that outputs the tensor, as a string.
output_slot: Output slot index of the tensor, as an integer.
Returns:
Name of the tensor, as a string.
"""
return "%s:%d"... | d563a3e4be696fc1109aa7a60fb4dd140ec65431 | 22,903 |
def EstimateMarriageSurvival(resp):
"""Estimates the survival curve.
resp: DataFrame of respondents
returns: pair of HazardFunction, SurvivalFunction
"""
# NOTE: Filling missing values would be better than dropping them.
complete = resp[resp.evrmarry == 1].agemarry.dropna()
ongoing = resp[... | 06f7d307662a70ef4c77073e4202f69ec68ee9e4 | 22,904 |
def get_cowell_data():
"""
Gets Cowell data.
:return: Data and headers.
"""
n = 10000
Y = np.random.normal(0, 1, n)
X = np.random.normal(Y, 1, n)
Z = np.random.normal(X, 1, n)
D = np.vstack([Y, X, Z]).T
return D, ['Y', 'X', 'Z'] | bd2084b889e8e9068d11b0f49c1d00226bfc6a1f | 22,905 |
def is_str_str_tuple(t):
"""Is this object a tuple of two strings?"""
return (isinstance(t, tuple) and len(t) == 2
and isinstance(t[0], basestring)
and isinstance(t[1], basestring)) | e568821ee2d7a3926744b93eaf11356744ca4538 | 22,906 |
def g(dist, aq):
"""
Compute function g (Lemma 5) for a given full parent isntantiation.
Parameters
----------
dists: list ints
Counts of the child variable for a given full parent instantiation.
aq: float
Equivalent sample size divided by the produc... | 505f5c0857f97579bcb1be9e812a90c31ecf4e5e | 22,907 |
def order_tweets_by_polarity(tweets, positive_highest=True):
"""Sort the tweets by polarity, receives positive_highest which determines
the order. Returns a list of ordered tweets."""
reverse = True if positive_highest else False
return sorted(tweets, key=lambda tweet: tweet.polarity, reverse=reverse... | 996c0aa6c374716f10d4d7a890162fe1bb87eef1 | 22,909 |
from scipy.stats import beta
from params import VoC_start_date, use_vaccine_effect
def read_in_Reff_file(file_date, VoC_flag=None, scenario=''):
"""
Read in Reff h5 file produced by generate_RL_forecast.
Args:
file_date: (date as string) date of data file
VoC_date: (date as string) date f... | 219118c333f14ba9f7a44416bd30e38c66b3d5d9 | 22,911 |
def string_with_fixed_length(s="", l=30):
"""
Return a string with the contents of s plus white spaces until length l.
:param s: input string
:param l: total length of the string (will crop original string if longer than l)
:return:
"""
s_out = ""
for i in range(0, l):
if i < len... | 2230a2893913eadb2c42a03c85728a5fe79e1e0f | 22,913 |
def fetch_ref_proteomes():
"""
This method returns a list of all reference proteome accessions available
from Uniprot
"""
ref_prot_list = []
response = urllib2.urlopen(REF_PROT_LIST_URL)
for ref_prot in response:
ref_prot_list.append(ref_prot.strip())
return ref_prot_list | f42c879f78a0e7281df369b40145c5d60aedb32b | 22,914 |
from typing import BinaryIO
def load(fp: BinaryIO, *, fmt=None, **kwargs) -> TextPlistTypes:
"""Read a .plist file (forwarding all arguments)."""
if fmt is None:
header = fp.read(32)
fp.seek(0)
if FMT_TEXT_HANDLER["detect"](header):
fmt = PF.FMT_TEXT
if fmt == PF.FMT_T... | d8445e388b33f69555c1270cebecfd552a34196a | 22,915 |
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())
return wrapper | d1e4f766827c13fa312ce3485daf43be2fc0eda1 | 22,916 |
from typing import Set
def create_affected_entities_description(security_data: SecurityData, limit: int = 5) -> str:
"""Create a description of the entities which are affected by a security problem.
:param security_data: the security details for which to create the description
:param limit: the maximum nu... | 95adc5a6a1fe88e0ec80273deee95e39ee196a55 | 22,917 |
def amac_person_org_list_ext():
"""
中国证券投资基金业协会-信息公示-从业人员信息-基金从业人员资格注册外部公示信息
http://gs.amac.org.cn/amac-infodisc/res/pof/extperson/extPersonOrgList.html
:return:
:rtype: pandas.DataFrame
"""
data = get_data(url=amac_person_org_list_ext_url, payload=amac_person_org_list_ext_payload)
need_... | f84d40a79ae49ebdf5a8ecb6612b37515f5ea676 | 22,918 |
def ele_types(eles):
"""
Returns a list of unique types in eles
"""
return list(set([e['type'] for e in eles] )) | e87ea4c6256c2520f9f714dd065a9e8642f77555 | 22,920 |
def colorful_subgraph(G, colors, k, s, subgraph_type, get_detail=True, verbose=False):
"""Detect if colorful path exists fom s to any node by dynamic programming.
Args:
G (nx.Graph): with n nodes and m edges
colors (list): list of integers represents node colors
k (int): number of colors... | 644a1091bbee9bf79f236a8f815ae4c07fb1f538 | 22,921 |
import itertools
def find_all_combos(
conformer,
delta=float(120),
cistrans=True,
chiral_centers=True):
"""
A function to find all possible conformer combinations for a given conformer
Params:
- conformer (`Conformer`) an AutoTST `Conformer` object of interest
- de... | 1b5c5f44de23524a9392f51e76f46ef0f234648c | 22,922 |
def generate_abbreviations(
labels: tp.Iterable[str],
max_abbreviation_len: int = 3,
dictionary: tp.Union[tp.Tuple[str], str] = "cdfghjklmnpqrstvxz"):
"""
Returns unique abbreviations for the given labels. Generates the abbreviations with
:func:`beatsearch.utils.generate_unique_abbre... | a22e68990147bd973c4a7af8e9e1a8f28fa7b4ac | 22,924 |
def best_hand(hand):
"""Из "руки" в 7 карт возвращает лучшую "руку" в 5 карт """
i = iter(combinations(hand, 5))
best_rank = 0, 0, 0
best_combination = None
for combination in i:
current_rank = hand_rank(combination)
if compare(current_rank, best_rank):
best_rank = curren... | c885625c2b5f60453b6dca59e25003b9f977e9d4 | 22,925 |
def calculate_label_counts(examples):
"""Assumes that the examples each have ONE label, and not a distribution over labels"""
label_counts = {}
for example in examples:
label = example.label
label_counts[label] = label_counts.get(label, 0) + 1
return label_counts | 4c45378c6e29ce3d1b40b4d02a112e1fbd23d8b6 | 22,926 |
def printer(arg1):
"""
Even though 'times' is destroyed when printer() has been called,
the 'inner' function created remembers what times is. Same goes
for the argument arg1.
"""
times = 3
def inner():
for i in range(times): print(arg1)
return inner | 7e3d2033602eaef9ef570c97a058208066073427 | 22,927 |
from bs4 import BeautifulSoup
def from_get_proxy():
"""
From "http://www.getproxy.jp"
:return:
"""
base = 'http://www.getproxy.jp/proxyapi?' \
'ApiKey=659eb61dd7a5fc509bef01f2e8b15669dfdb0f54' \
'&area={:s}&sort=requesttime&orderby=asc&page={:d}'
urls = [base.format('CN'... | b3302b0092eb973022e2d322cc00e1391fe68c8b | 22,928 |
def KORL(a, kappa=None):
""" log rounds k-ary OR """
k = len(a)
if k == 1:
return a[0]
else:
t1 = KORL(a[:k//2], kappa)
t2 = KORL(a[k//2:], kappa)
return t1 + t2 - t1.bit_and(t2) | 2c85f7131dcfe0b35d3bfd8b04b876fad320572f | 22,929 |
import json
import requests
def verify(token):
"""Verifies a JWS token, returning the parsed token if the token has a
valid signature by the key provided by the key of the OpenID
Connect server stated in the ISS claim of the token. If the
signature does not match that key, None is returned.
"""
... | 8d1dac4d1c87de3d2d619f58bdf077f82b54dfda | 22,930 |
def get_listing_panel(tool, ghidra):
""" Get the code listing UI element, so we can get up-to-date location/highlight/selection """
cvs = tool.getService(ghidra.app.services.CodeViewerService)
return cvs.getListingPanel() | f14477cf13cb7eb4e7ede82b0c2068ca53a30723 | 22,931 |
def template_data(environment, template_name="report_html.tpl", **kwds):
"""Build an arbitrary templated page.
"""
template = env.get_template(template_name)
return template.render(**environment) | 6b3c1ea5c280931280b5d6c69f380b9349ac0627 | 22,932 |
def resnet152_ibn_a(**kwargs):
"""
Constructs a ResNet-152-IBN-a model.
"""
model = ResNet_IBN(block=Bottleneck_IBN,
layers=[3, 8, 36, 3],
ibn_cfg=('a', 'a', 'a', None),
**kwargs)
return model | 5cb059910c5442b0df7c08471f75b96fe3fb4c80 | 22,933 |
import scipy
def calibratePose(pts3,pts2,cam,params_init):
"""
Calibrates the camera to match the view calibrated by updating R,t so that pts3 projects
as close as possible to pts2
:param pts3: Coordinates of N points stored in a array of shape (3,N)
:param pts2: Coordinates of N points stored in ... | 5f1fcf55ec934596fd46f129d12e8457173239eb | 22,934 |
import base64
def image_to_base64(file_image):
"""
ESSA FUNÇÃO TEM COMO OBJETIVO, CONVERTER FORMATO DE INPUT (PNG) -> BASE64
O ARQUIVO OBTIDO (PNG) É SALVO NA MÁQUINA QUE ESTÁ EXECUTANDO O MODELO.
# Arguments
file_image - Required : Caminho do arquivo
... | 74e9c46ce48e23fdb5453cb9ce5223dfb8e6004b | 22,935 |
from pathlib import Path
from typing import Set
def get_files_recurse(path: Path) -> Set:
"""Get all files recursively from given :param:`path`."""
res = set()
for p in path.rglob("*"):
if p.is_dir():
continue
res.add(p)
return res | c129ce43130da09962264f6e7935410685815943 | 22,936 |
from typing import List
def img_after_ops(img: List[str], ops: List[int]) -> List[str]:
"""Apply rotation and flip *ops* to image *img* returning the result"""
new_img = img[:]
for op in ops:
if op == Tile.ROTATE:
new_img = [cat(l)[::-1] for l in zip(*new_img)]
elif op == Tile.... | a28f1dbdf7f756c9b8b313d889596797466ab729 | 22,937 |
import functools
import urllib
def authenticated(method):
"""Decorate methods with this to require that the user be logged in.
Fix the redirect url with full_url.
Tornado use uri by default.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
user = self.current... | c4dc18af60b9270d644ed807ea1c74b821ea7bca | 22,938 |
import math
def ring_samp_ranges(zma, rng_atoms):
""" Set sampling range for ring dihedrals.
:param zma: Z-Matrix
:type zma: automol.zmat object
:param rng_atoms: idxs for atoms inside rings
:type rng_atoms: list
"""
samp_range_dct = {}
ring_value_dct = ring_dihedrals... | 6e1958f66f596d9b1230864e3b9a2b73cd01cb35 | 22,939 |
def users_key(group='default'):
""" Returns the user key """
return db.Key.from_path('users', group) | 1912165ff75c39c9fbcb1432f46ef80f9b08c096 | 22,940 |
def VolumetricFlow(self):
"""Volumetric flow (m^3/hr)."""
stream, mol = self.data
m = mol[0]
if m:
c = self.name # c = compound
c.T = stream.T
c.P = stream.P
c.phase = stream._phase
return c.Vm * m * 1000
else:
return 0. | c799c27079494561e30975a6e03b5c1cefe9a907 | 22,941 |
def build_queue_adapter(workflow_client, logger=None, **kwargs):
"""Constructs a queue manager based off the incoming queue socket type.
Parameters
----------
workflow_client : object ("distributed.Client", "fireworks.LaunchPad")
A object wrapper for different distributed workflow types
log... | bbd013fef1095dd4881a8b51561ed4080682141e | 22,942 |
import torch
def pad_sents(sents, pad_token, return_tensor = False):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
... | 3100ef6f1924685f7a46b22753830cdf203e565d | 22,943 |
def _take_along_axis(array, indices,
axis):
"""Takes values from the input array by matching 1D index and data slices.
This function serves the same purpose as jax.numpy.take_along_axis, except
that it uses one-hot matrix multiplications under the hood on TPUs:
(1) On TPUs, we use one-hot ... | 9a926a53341e0fc964fc568474ca29db286ed14e | 22,944 |
import requests
import logging
def send_envelope(
adfs_host: str,
envelope: str,
) -> requests.Response:
"""Send an envelope to the target ADFS server.
Arguments:
adfs_host: target ADFS server
envelope: envelope to send
Returns:
ADFS server response
"""
url = f"ht... | bc59fa99fa28432dd969f1a72bbae00af716b443 | 22,945 |
def display_main(choice):
"""
Link option To main board
"""
return main(choice) | 66b0b0d36d47b4107b5b57dce9ea94787f3fa83b | 22,946 |
import random
def generate_network_table(seed=None):
"""
Generates a table associating MAC and IP addressed to be distributed by our virtual network adapter via DHCP.
"""
# we use the seed in case we want to generate the same table twice
if seed is not None:
random.seed(seed)
# numbe... | d39915c129b2d5a99fc41c90b718fcca17d20cd5 | 22,947 |
import torch
def loss_mGLAD(theta, S):
"""The objective function of the graphical lasso which is
the loss function for the meta learning of glad
loss-meta = 1/B(-log|theta| + <S, theta>)
Args:
theta (tensor 3D): precision matrix BxDxD
S (tensor 3D): covariance matrix BxDxD (dim=D)
... | b056a5c57e681cca40c6a7a0d030dee25049e6de | 22,948 |
def parse_remote_path(remote_path):
""" Wrapper around the utils function - checks for the right protocol """
protocol, bucket, key = utils.parse_remote_path(remote_path)
assert protocol == "s3:", "Mismatched protocol (expected AWS S3)"
return bucket, key | 65c26139d0e28f64ae966a75bf730d1a6b8b2248 | 22,949 |
from typing import Callable
def operations(func: Callable) -> Callable:
"""Allows developers to specify operations which
should not be called in the fuzzing process.
Examples:
Ignoring operations specified by operation ids in lists
>>> @fuzz_lightyear.exclude.operations
..... | ce6d9596ff307f15c86d4823d3ebcfdafa5f4e33 | 22,950 |
def _gen_dfa_table(t: UxsdComplex) -> str:
"""Generate a 2D C++ array representing DFA table from an UxsdComplex's DFA.
The array is indexed by the state and input token value, such that table[state][input]
gives the next state.
"""
assert isinstance(t.content, UxsdDfa)
dfa = t.content.dfa
out = ""
out += "con... | f0bae5dd8f897786a62016b7b807e2c7730f1e89 | 22,951 |
def get_heat_capacity_derivative(Cv, temperature_list, plotfile='dCv_dT.pdf'):
"""
Fit a heat capacity vs T dataset to cubic spline, and compute derivatives
:param Cv: heat capacity data series
:type Cv: Quantity or numpy 1D array
:param temperature_list: List of temperatures used in repli... | 49f27209c9f6387fc25936481d5d35cebdc6523f | 22,952 |
def get_gradients_of_activations(model, x, y, layer_names=None, output_format='simple', nested=False):
"""
Get gradients of the outputs of the activation functions, regarding the loss.
Intuitively, it shows how your activation maps change over a tiny modification of the loss.
:param model: keras compile... | 5cb9234594b867383f92f4e2e7e91e39eb79d120 | 22,953 |
def string_to_screens_and_lines(source, allowed_width, allowed_height, f, pixels_between_lines = None, end_screens_with = (), do_not_include = ()):
"""
Convert a string to screens and lines.
Pygame does not allow line breaks ("\n") when rendering text. The purpose
of this function is to break a str... | f43907fdf47b342b1eac3100c07e9d452b0d865f | 22,954 |
def trim_spectrum(self, scouse, flux):
"""
Trims a spectrum according to the user inputs
"""
return flux[scouse.trimids] | 3f18259986e677f8e8a9718408cdb56352d956e5 | 22,955 |
def test_bitwise_and(a, b):
"""
>>> test_bitwise_and(0b01, 0b10)
0L
>>> test_bitwise_and(0b01, 0b11)
1L
>>> test_bitwise_and(0b01, 2.0)
Traceback (most recent call last):
...
NumbaError: 27:15: Expected an int, or object, or bool
>>> test_bitwise_and(2.0, 0b01)
Tracebac... | 0855921300751368eb0ad3f3cba37b6ddac759fd | 22,956 |
import inspect
def flagFunction(method, name=None):
"""
Determine whether a function is an optional handler for a I{flag} or an
I{option}.
A I{flag} handler takes no additional arguments. It is used to handle
command-line arguments like I{--nodaemon}.
An I{option} handler takes one argument... | 265f92ca52ec4b3c1b6b3955a7ac719f64099bad | 22,957 |
from pathlib import Path
def envnotfound(env):
"""`'Env "my-venv" not found. Did you mean "./my-venv"?'`"""
msg = f'Env "{env}" not found.'
if arg_is_name(env) and Path(env).exists():
msg += f'\nDid you mean "./{env}"?'
return msg | e2437bbf141a841650f33ede5d7fb6489a954f00 | 22,958 |
def random_translation_along_x(gt_boxes, points, offset_range):
"""
Args:
gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]]
points: (M, 3 + C),
offset_range: [min max]]
Returns:
"""
offset = np.random.uniform(offset_range[0], offset_range[1])
points[:, 0] += o... | 6998e463313faeaaf75e96b0374c0bdc5415c8f1 | 22,959 |
import numpy
import scipy
def predband(xd,yd,a,b,conf=0.95,x=None):
"""
Calculates the prediction band of the linear regression model at the desired confidence
level, using analytical methods.
Clarification of the difference between confidence and prediction bands:
"The 2sigma confidence interval is 95% sure to co... | a235548f4593cfc105bba9d7268dba2e14374df7 | 22,960 |
def orient_edges(G):
"""Orient remaining edges after colliders have been oriented.
:param G: partially oriented graph (colliders oriented)
:returns: maximally oriented DAG
"""
undir_list = [edge for edge in G.edges() if G.is_undir_edge(edge)]
undir_len = len(undir_list)
idx = 0
whi... | 958c22b7c7906219bfc52d2cc59945a22e4e1060 | 22,961 |
def _create_deserialize_fn(attributes: dict, globals: dict, bases: tuple[type]) -> str:
"""
Create a deserialize function for binary struct from a buffer
The function will first deserialize parent classes, then the class attributes
"""
lines = []
# For this class bases
for parent in bases:... | e5058b73d47a034323a4ebe65edbf888bdf98321 | 22,962 |
def blck_repeat(preprocessor: Preprocessor, args: str, contents: str) -> str:
"""The repeat block.
usage: repeat <number>
renders its contents one and copies them number times"""
args = args.strip()
if not args.isnumeric():
preprocessor.send_error("invalid-argument", "invalid argument. Usage: repeat [uint > 0]"... | 8dfedd854a68b2fcc33ea4b9714744302fe5934d | 22,963 |
import math
def is_prime(n: int) -> bool:
"""Determines if the natural number n is prime."""
# simple test for small n: 2 and 3 are prime, but 1 is not
if n <= 3:
return n > 1
# check if multiple of 2 or 3
if n % 2 == 0 or n % 3 == 0:
return False
# search for subsequent pri... | e7bd02271681906f9ee4e63305c5a6f630578171 | 22,964 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.