content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from functools import reduce
def shekel(x):
"""
Shekel: The modified fifth De Jong function, Equation (21) of [2]
minimum is f(x)=0.0 at x(-32,-32)
"""
A = [-32., -16., 0., 16., 32.]
a1 = A * 5
a2 = reduce(lambda x1,x2: x1+x2, [[c] * 5 for c in A])
x1,x2 = x
r = 0.0
for i in... | c2dd86b40072cc40dc4bba1a7f5d300d174c4ad8 | 51,800 |
def desitarget_nside():
"""Default HEALPix Nside for all target selection algorithms."""
nside = 64
return nside | 326338bcc9310725f92b74a29416812cebbd7db1 | 51,801 |
def get_best_hands_brute_force(board, hands):
""" get the index of the best holdem hand given a board
:param board: ([str]) list of 5 cards
:param hands: ([set(str)]) list of sets of 4 cards
:return: ([[int]]) indices of `hands` that makes the strongest holdem hand,
--> this is a list because i... | 35b01878ea967b0271741de427c7282aa82d4442 | 51,802 |
def logsig_fn(phi,X):
"""
sigmoid function
static nonlinearity from Rabinowitz et al 2011
"""
a=phi[0] # baseline
b=phi[1] # asymptote
c=phi[2] # inflection point
d=phi[3] # slope
Y=a+b/(1+np.exp(-(X-c)/d))
return(Y) | d13a4295e5e9f210ba8ff41167a23bc1785d4bff | 51,803 |
def get_table_9():
"""表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
Args:
Returns:
list: 表 9 通風の利用に関する区分݈の通風の利用における相当換気回数 NV_l
"""
table_9 = (0.0, 5.0, 20.0)
return table_9 | ed095f6ffd6fb146caed2628d089784ef91d6217 | 51,804 |
def find_nodes(graph, query, data=False):
""" Iterator over all nodes matching the data query.
"""
return ((v, graph.nodes[v]) if data else v
for v in graph if query(graph.nodes[v])) | e8f2e25f843133446c32ca7f012ac2aa1b80d2b9 | 51,805 |
def _SigninUIState(oobe):
"""Returns the signin ui state of the oobe. HIDDEN: 0, GAIA_SIGNIN: 1,
ACCOUNT_PICKER: 2, WRONG_HWID_WARNING: 3, MANAGED_USER_CREATION_FLOW: 4.
These values are in chrome/browser/resources/chromeos/login/display_manager.js
"""
return oobe.EvaluateJavaScript('''
loginHeader = docu... | 355b7ebbaf0010165109c27162ca70f5168abe05 | 51,806 |
import os
def script_overview():
"""
Endpoint serving the overview script
"""
return send_from_directory(
os.path.join(ui_config.CODE_DIR, 'js'),
'overview.js',
mimetype='application/javascript'
) | 0224e660d8790944730ae344bdd0b21e53ae375d | 51,807 |
def make_image(url, title=None, description=None):
"""Creates an image node
Args:
url (string): url to assign to image node
title (string, optional): assign a title to node on creation. Defaults to None.
description (string, optional): set image description on creation. Defaults to ... | 627b6fd368b83341b23378d4f6b5213be3cf3571 | 51,808 |
def get_plat_name():
"""获取所有平台ID与平台名的映射"""
plat_info = {}
res = bk.cc.get_plat_id()
for plat in res:
plat_id = int(plat['plat_id'])
plat_info[plat_id] = plat['plat_name']
return plat_info | f58517dca21a8653b14c2c46bf143600aa62290d | 51,809 |
def cluster_staypoints(staypoints,
method='dbscan',
epsilon=100,
num_samples=1,
distance_matrix_metric=None,
agg_level='user'):
"""Clusters staypoints to get locations.
Parameters
---------... | eda2bad60439cd5a3d585fa50d314a0f2669bd2f | 51,810 |
def word_count(df, new_col_name, col_with_lyrics):
"""
Count the number of words in a dataframe lyrics column, given a column name, process it, and save as new_col_name
Parameters
----------
df : dataframe
new_col_name : name of new column
col_with_lyric: column with lyrics
... | 6900e892a0f9fbc94c8c4ade24e12b7910b3c80c | 51,811 |
def prepare_target(data, close_index=3, classes=6):
"""
Hello (=
uniform classes
"""
# TODO
# while const
classes = 6
data = np.array(data)
new_target = data[1:, close_index] / data[:-1, close_index]
new_target = np.insert(new_target, obj=0, values=[1.0])
n, bins = ... | ac3f8775b39196cc24003e30f11bf62b968356d5 | 51,812 |
def ccd_to_list(file_path: str) -> list:
"""Converts a .ccd file into a dict"""
file = open(file_path, 'r')
lines = file.readlines()
file.close()
data = []
for index, line in enumerate(lines):
try:
if line.startswith(' '):
data.append(float(line.split(' ')[... | 12955459def48c12f0b7e6b0b889fd47df690b9d | 51,813 |
def add(a,b):
""" This function adds two numbers """
return a+b | 5dd8bcd4bbd9f610fe632c904bfc45a4ba9e249e | 51,814 |
def get_SSH_forcing(boundary, date):
"""A function that returns the ssh forcing for the month of the date and
boundary indicated.
:arg str boundary: A string naming the boundary. e.g 'north' or 'west'
:arg str date: A string indicating the date of interest. e.g. '01-Dec-2006'.
The... | 09c418e65e419ba71b6fb7bfd0284d6659eddbe0 | 51,815 |
import math
def draw_trial_im(t, epoch, label, n_avg=1, ch_names=None, cls_name=('non-target', 'target'), title='', **kwargs):
"""
Plot epochs trial by trial in an image.
:param t: tuple (start, end, samplerate)
:param epoch: (epochs, channels, time)
:param label:
:param n_avg:
:param ch_n... | b378d7c5e7aa28980ba7e6225d4da7fecdc96089 | 51,816 |
def _convert_imxyzs_to_npidxs(imxyzs, rows=13824, cols=7680, pixel_size=0.012):
"""
image space linear transform
pixel_size = sensor_width/image_cols = 92.16/7680 = sensor_height/image_rows = 165.8885/13824 # unit: mm/px
"""
col_zoomin, row_zoomin = 1/pixel_size, -1/pixel_size
xs, ys = imxyzs.T... | 491eb95a351f6200733057ca84c2131f1d805399 | 51,817 |
import os
def create_env(nzo=None, extra_env_fields={}):
""" Modify the environment for pp-scripts with extra information
OSX: Return copy of environment without PYTHONPATH and PYTHONHOME
other: return None
"""
env = os.environ.copy()
# Are we adding things?
if nzo:
# Add ... | 791c247bf33cc2507842655411a524c79c21c44e | 51,818 |
import hmac
import hashlib
def generate_dendrite_mac(shared_secret: str, username: str, password: str, admin: bool) -> str:
"""
Generate a MAC for using in registering users with Dendrite.
"""
# From: https://github.com/matrix-org/dendrite/blob/master/clientapi/routing/register.go
mac = hmac.new(
... | bed29168d88db0d9b2bd0bf95f493a9d4b5e7a3f | 51,819 |
import json
def create_snake_environment4eat(level_filename):
""" Create a new Snake environment from the config file. """
with open(level_filename) as cfg:
env_config = json.load(cfg)
return EnvironmentAttackRandomPoison(config=env_config, verbose=1) | 41856cc2d1811726f02c5a92bb43a6f1c1dfedb3 | 51,820 |
def Search(request):
"""Course search view handler."""
search_context = views_impl.Search(request)
template_name = 'search_results.html'
context = template.RequestContext(request, search_context)
return shortcuts.render_to_response(template_name, context_instance=context) | 5295e0e8fdacc29dba9de9b335aec58e872148a7 | 51,821 |
def _function_entry_stack_ops(op, to_pop):
"""Computes a set of stack operations for the entry to a FunctionCallOp.
The function calling convention is
- Push the arguments to the formal parameters
- Pop any now-dead arguments so they're not on the stack during the call
- Jump to the beginning of the function... | 6240a1ebaf0b00591a4f24648ab58bba3010ca56 | 51,822 |
def flash(light, color, p_on, p_off):
"""
flashes color for [on] seconds, then off for [off] seconds, repeating.
"""
def ret(ticks, elapsed_time):
if isinstance(p_on, Parameter):
on = p_on.get()
else:
on = p_on
if isinstance(p_off, Parameter):
... | 8b9dcff67504647dd8ff0a4a8c4b357353560875 | 51,823 |
import subprocess
def get_revision() -> str:
"""return the git revision of current directory as a human-readable string.
:raises OSError: Couldn't get revision from git.
"""
try:
job = subprocess.run([GIT_PATH, 'log', '-1', '--pretty=oneline'],
stdout=subprocess.P... | 7de32721e50b2fc89e56a385033ddc6b0737ad50 | 51,824 |
def solver_problem2(init_state, day):
"""
input initial state, day and output fish
a more efficiet way that only record a fish library with {timer: fish number}
"""
fish_lib = {timer: init_state.count(timer) for timer in set(init_state)}
for _ in range(day):
fish_lib = update_fish(fish_l... | 6f52b79659eba941f47844367686d2dec57707a4 | 51,825 |
def print_nodes_name(graph):
"""
input:
-------
graph: (tf.Graph() or tf.GraphDef()) graph in which prints only the nodes' name
return:
-------
None
"""
if isinstance(graph, graph_pb2.GraphDef):
for n in graph.node:
logger.info(n.name)
return [n.na... | 4e01f059ef646f98a6bc469f0b3c27add330a9c0 | 51,826 |
def _tvos_dynamic_framework_impl(ctx):
"""Experimental implementation of tvos_dynamic_framework."""
# This rule should only have one swift_library dependency. This means len(ctx.attr.deps) should be 2
# because of the swift_runtime_linkopts dep that comes with the swift_libray
swiftdeps = [x for x in c... | 154cc886a943652914e974d0b5a7c8ef53f2168a | 51,827 |
from typing import OrderedDict
def order_nested_object(nested_object):
"""
Simply recursively order the item. To be used for standardizing objects for JSON dumps
"""
if isinstance(nested_object, list):
if len(nested_object) > 0 and isinstance(nested_object[0], dict):
# Lists of dic... | 640fb552ebb714fa3489939198d282906cec05d3 | 51,828 |
def add_header(r):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
# clear browser cache
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Ca... | ddf4b82b853947919535712c4ffe7bbed196a6cd | 51,829 |
def id_feat_meas_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'):
"""
id_feat_meas_mz_rt
description:
identifies a feature on the basis of measured m/z and retention time
parameters:
cursor (sqlite3.Cursor) -- cursor for querying lipids.db
mz (float) -- m/z t... | 4d82194eb024f736ee56dec7aa6bb4d32cb62b9a | 51,830 |
import uuid
def generate_guid():
""" Generate a GUID
"""
return uuid.uuid4().hex | 11370892bd2e8b66d874c7e64ebda7ab41ac0d37 | 51,831 |
def get_data_ch7():
"""Get the data set used in Chapter 7"""
data = np.genfromtxt('../data/airfoil_self_noise.dat', delimiter='\t')
data = (data - data.mean(axis=0)) / data.std(axis=0)
return nd.array(data[:, :-1]), nd.array(data[:, -1]) | de1e706c62b8266390e04e4cff352ef211ffbea1 | 51,832 |
from cirq._import import wrap_module_executions # type: ignore
from typing import List
import time
import sys
import os
import collections
def verify_import_tree(depth: int = 1, track_others: bool = False, timeit: bool = False) -> bool:
"""Locates imports that violate cirq's submodule dependencies by
instrum... | a5b2873d7e017b59b6c3c2f9b5fc28cdcb61b518 | 51,833 |
def is_iterable(obj) -> bool:
"""
Test if argument is iterable.
"""
return isiterable(obj) | c24323082b3ad290301e390b02ceb781e4c9104b | 51,834 |
def concat_name(name: str, *comp_names):
"""Add comp_name to name, e.g. ('dist', 'a2', 'a1')-->'a1__a2___dist'."""
comp_name = concat_comps(*comp_names)
if comp_name:
return f'{comp_name}{SPLITTER}{name}'
return name | 53ead1a50c6b87b26951bc9d613ab1d96528a9e1 | 51,835 |
def demedian_parcellate_func_combine_hemis(lh_func, rh_func, lh_parcel_path, rh_parcel_path):
"""
#Function that takes functional data in the form <num_verts, num_timepoints> for
#both the left and right hemisphere, and averages the functional time series across
#all vertices defined in a given par... | baea9d5e9c561c5cd8f806cf4c69c552c4398f54 | 51,836 |
import os
def get_pdf_upload_to():
"""
This function returns the absolute path to the folder for uploading PDFs
2019-10-22
:return: the absolute path to the folder for uploading PDFs
"""
pdf_upload_to = getattr(settings, 'OCR_PDF_UPLOAD_TO', ocr_default_settings.PDF_UPLOAD_TO)
if not os.pa... | 267f1827d42efde7feb795f1ad80ba7d639c70a3 | 51,837 |
def _cmpPair2(a, b):
"""Auxiliary comparision for sorting lists of pairs. Sorting on the second member of the pair."""
(x, y), (z, w) = a, b
if y < w:
return -1
elif y > w:
return 1
elif x < z:
return -1
elif x > z:
return 1
else:
return 0 | 5567ddc006756e224dde545503c427a3524c3c90 | 51,838 |
def linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):
""" Create a schedule with a learning rate that decreases linearly after
linearly increasing during a warmup period.
"""
def lr_lambda(current_step):
if current_step < num_warmup_steps:
r... | b7109843869de325a03273a8245bbd04a5244fb4 | 51,839 |
def chooseStatic(schedule, staticDict, priorityQueue, modulo=24):
"""
given a scheudule and a priority queue,
it takes the next highest priority item and checks for conflicts and the event is added to the schedule only if there's no confict
if the duration of the event is less than the time... | 09616c2887172b7de1e5e8af2456af5ca2acafd0 | 51,840 |
import glob
def prepare_corsika_from_blacklist(path, oldEnding='', newEnding='nomissing'):
"""Takes the path of the corsika files (there should be only corsika files in a single directory)
and removes unuseable and too short keys and writes new hdf5 files"""
oldCorsika = [h5.File(file, 'r') for file in so... | a2bc2bef076d1010201bf1c7879b5e9b5a7b499f | 51,841 |
def toExport8F8(op):
"""Converts number to exportable 8.8 signed fixed point number."""
return int(round(op * 256.0)) | 3364703913e1c87223ffb11bdaf3b622db7eef1c | 51,842 |
def mkminim(grid, baseuri=None):
"""
Generate minim graph from supplied grid
Returns (status,mgr) where mgr is RDF graph containing minim description,
or None.
"""
# Decode the grid
try:
(d,(r,c)) = checklist_template.checklist.match(grid, 0, 0)
except Exception, e:
prin... | cb88bbc052378290d11ba1d49fd9c6531b40946a | 51,843 |
import os
def get_serializables_from_comp_xml(comp_xml):
"""
Returns list containing all serialized types found from
component xml and its imported files... NOTE: Must add
check for serial types found outside imported serial files
"""
serial_imports = comp_xml.get_serializable_type_files()
... | bce6815c5d113e9efc35f6776acc5aa24f7b4b5f | 51,844 |
import math
def LogRegressNomalize(value):
"""Uses log regress to normalize (-inf, inf) to [0, 1]."""
value_exp = math.exp(value)
return value_exp / (value_exp + 1) | a5d30077df70b3795754d62c6534781e61482f13 | 51,845 |
def test_prob_wires_and_hermitian(hermitian):
"""Test that we can cannot give simultaneously wires and a hermitian."""
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def circuit():
qml.PauliX(wires=0)
return qml.probs(op=qml.Hermitian(hermitian, wires=0), wires=1)
with... | 39f6b8ea07824063d4956290459838407d442cd2 | 51,846 |
def guess(intcos, geom, Z, connectivity=False, guessType="SIMPLE"):
""" Generates diagonal empirical Hessians in a.u. such as
Schlegel, Theor. Chim. Acta, 66, 333 (1984) and
Fischer and Almlof, J. Phys. Chem., 96, 9770 (1992).
"""
dim = len(intcos)
H = np.zeros((dim, dim), float)
for i... | 64e3466eb08ec8b80d72a1cd579de9da20bdc7d8 | 51,847 |
def get_cmap(n, name='Set1'):
"""
Source: https://stackoverflow.com/questions/14720331/how-to-generate-random-colors-in-matplotlib
Colormaps: https://matplotlib.org/tutorials/colors/colormaps.html
:param n: Number of classes.
:param name: The color map to be selected from.
:return: a function th... | e70c6d6cb9e86bdf2d4874cce1d54fee3da49254 | 51,848 |
def toy_classification(return_X_y=True, n=5000):
"""toy classification dataset with irrelevant features
fitting a logistic model on this data and performing a model summary
should reveal that features 2,3,4 are not significant.
Parameters
----------
return_X_y : bool,
if True, returns ... | d00ced30fc36047448f0c72737137e63d2e43c26 | 51,849 |
def describe_frameworks(serv, args, blueprint_name):
"""
Function used to answer to DescribeFrameworks requests
:param serv: Service object
:param args: parameters of the TJS request
:return: request response
"""
exceptions = []
arg_version = args.get("version")
# TOD... | a9d9629e9f2f45b243662b5acb5a7727eda9c5f0 | 51,850 |
async def client_get_configuration(response: Response,
request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST),
configname:str=Query(..., title=opasConfig.TITLE_ADMINCONFIGNAME, description=opasConfig... | d9c8e2cb13446834ed414f487b35cdc2d9bbc99a | 51,851 |
def cross_entropy_seq(logits, target_seqs, batch_size=None):
"""Returns the expression of cross-entropy of two sequences, implement
softmax internally. Normally be used for fixed length RNN outputs, see `PTB example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_ptb_lstm.py>`__.
P... | a8b7382337228d7910b0e4d99540d626645e900f | 51,852 |
def recurse_files(dir: PathLike, *, channel: Channel = None) -> Channel:
"""
Starts a worker thread that finds all files in `dir` (recursively) and
writes them to a :obj:`Channel`. Each file found is written as a
:obj:`pathlib.Path` object.
:param dir: The directory to search.
:param channel: C... | 705b6a6f4f9d90970490f7e9b5de17425d2aa336 | 51,853 |
from typing import Union
def _choose_prior(
fun_params0: Union[pn.RandomVariable, np.ndarray, None]
) -> pn.RandomVariable:
"""
Initialize the prior distribution over the parameters.
Sets up a prior distribution if no prior or only a point estimate for the parameters
of the latent quadratic funct... | 7d4c363192d55d5a2946829bfa0586f093cd9dd5 | 51,854 |
import warnings
def write_stems(
path,
data,
sample_rate=44100,
writer=StreamsWriter(stem_names=None)
):
"""Write stems from numpy Tensor
Args:
path: str
Output file_name of the stems file. Note that the extension of the
path determines the used output containe... | 60cbb49fb1674b850927019dec0a291840bb12f6 | 51,855 |
import numpy
def njit_accumulated_matrix(s1, s2, mask):
"""Compute the accumulated cost matrix score between two time series.
Parameters
----------
s1 : array, shape = (sz1,)
First time series.
s2 : array, shape = (sz2,)
Second time series
mask : array, shape = (sz1, sz2)
... | 210d1d4554dfc470c4c3a37b2dc74a334a36b0ed | 51,856 |
def configuration_path():
"""File created by bin/combine."""
return 'config/swagger-combine.yml' | 3d75a3630bf56dcb51cf776a609fe3d21c111ead | 51,857 |
def padlist(container, size, default=None):
"""Pad list with default elements.
Examples:
>>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3)
('George', 'Costanza', 'NYC')
>>> first, last, city = padlist(['George', 'Costanza'], 3)
('George', 'Costanza', None)
... | 26c7cf9a106a5f58a385260c934323980cec598f | 51,858 |
def _conv1(in_channels, out_channels, bias=False):
"""point-wise convolution"""
return nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=bias) | 0ad133715072687e1369a75c85cb49c344778da8 | 51,859 |
def pad_to_length(sequences, length, value=0):
"""Pads sequences to being the same length, truncating right if they are longer.
Attributes
----------
sequences
the sequences to pad
length : int
the length to pad to
value
the value to use to pad
Returns
-------
... | fa67e3cb1d3ccd04a526b04370d2b86b09eabd32 | 51,860 |
def comp_pca(usnap, n_trunc, detrend=True):
"""Perform Principal Component Analysis on data.
Parameters
----------
usnap : array
Data array, size (n_pts, n_dim).
n_trunc : integer
The number of PCA dimensions to be retained.
detrend : boolean, optional
Whether or not to... | a6111e14f750818da47f30764bf38fea5a072ad7 | 51,861 |
def generate_thickness_gradient(ri, ro, T1, T2, Tdot_hot, hold,
Tdot_cold = None, hold_together = 0.0, delay = 0.0):
"""
Generate our usual through-wall temperature gradient
Parameters:
ri inner radius
ro outer radius
T1 initial temperature
... | 27ca14bc660264fc3dd33fab17ec9dbceddff280 | 51,862 |
def output_to_firrtl(open_file, rom_blocks=None, block=None):
""" Output the block as FIRRTL code to the output file.
:param open_file: File to write to
:param rom_blocks: List of ROM blocks to be initialized
:param block: Block to use (defaults to working block)
If ROM is initialized in PyRTL cod... | 29bd2d1e489ae0584d59262711e9075aeddc68e1 | 51,863 |
def Fk(shear_stress, temperature, Tath=700, Uk=0.33 * 1.60217657e-19, sigmap=900*1e6):
"""
Parameters
----------
shear_stress : ndarray of shape (N,)
CRSS or maximum shear stress (in Pa or Nm-2)
temperature : float
Temperature (in Kelvin)
Tath : float
The athermal tempera... | ebb63ce29ca6549e41eaef514e65c14982cc7fd0 | 51,864 |
def increment(lhs, ctx):
"""Element ›
(num) -> lhs + 1
(str) -> replace spaces with 0s
"""
ts = vy_type(lhs)
return {
NUMBER_TYPE: lambda: lhs + 1,
str: lambda: lhs.replace(" ", "0"),
}.get(ts, lambda: vectorise(increment, lhs, ctx=ctx))() | e373ee47d8d28edfec895d7e173537d0433fe757 | 51,865 |
def _indices_3d_numba(f, y, x, py, px, t, nt, interp=True):
"""Compute time and space indices of parametric line in ``f`` function
using numba. Refer to ``_indices_3d`` for full documentation.
"""
tdecscan = f(y, x, t, py, px)
if not interp:
sscan = (tdecscan >= 0) & (tdecscan < nt)
else... | 656b409448849d7e30ef5adac87654a5bb40982d | 51,866 |
import jinja2
def render():
"""
Render cron file
:return: a str representation of the cron file
"""
j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(resources.TEMPLATES_PATH))
tpl = j2_env.get_template(resources.CRON_TPL_YAML)
# TODO obtain cron urls from validation.main/app_bas... | 189dd29020e4239d89423e42dabe8f9959a4328f | 51,867 |
import requests
import json
def request_url(URL):
"""HTTP GET request and load into json"""
r = requests.get(URL)
if r.status_code == requests.codes.ok:
return json.loads(r.text)
else:
r.raise_for_status() | e237408de0fecb93ebededc66909ef49ada6b957 | 51,868 |
def getMultiTenantPath(api_name, method, app_name):
"""
This function will return the invoke path for a given api and http method (for a multi tenant setup)
:param api_name: Name of the API
:param method: Method of the API
:param app_name: Name of the application
:return: Invoke path
"""
... | fa369d325feb3ad3300d26e350f2cd73af898bfc | 51,869 |
import requests
import json
def get_txs_list(count=100, skip=0, filter={}):
"""
Fetch list of txs
"""
response = requests.post(
httpprovider,
data=json.dumps(
{
"jsonrpc": "2.0",
"id": 8,
"method": "tx_list",
... | 4b54f1059b2ab26a492cccbcb84f3376a224aa4c | 51,870 |
import math
def deep_tissue_segmentation( x, template=None, registration_map=None ):
"""
modified slightly more efficient deep atropos that also handles the
extra CSF issue. returns segmentation and probability images. see
the tissues csv available from get_data.
x: input image
template: MN... | 7efa1a12d8128884e4bc51adfeedbadb9173f533 | 51,871 |
import argparse
def parse_command_line_arguments():
"""Parse command line arguments, checking their values."""
parser = argparse.ArgumentParser(description='')
parser.add_argument('--model', default="./results/bert", help="the name of the model/checkpoint to be used for the classifier (e.g. ./results/che... | df9962306fac84261353fc90c61c6d2584078ff5 | 51,872 |
def beta_utility_gen(X, x_max, a, b):
"""
Beta distribution over utility value
X : value of Vertical Illuminance (EV) at which to find the utility function value
x_max : max value of EV to be considered for getting the proper Beta distribution
a: Beta distribution parameter
b : Beta distribution... | feefd63d1e859d5643c6c74787a5a0b6d70c05ea | 51,873 |
def question(conversation):
"""Counts whether each utterance in the given conversation contains a question (yes: 1, no: 0)"""
num_turns = len(conversation)
is_question_in_utterance = np.zeros(num_turns)
for i, utterance in enumerate(conversation):
if any(question_word in utterance for question_... | 98aea41cbcdbdf229a6d6a6bf42d24a20958b176 | 51,874 |
def insert_new_artist(cursor, name, is_vocalist, is_composer):
"""
Insert a new artist in the database
"""
sql_insert_artist = "INSERT INTO artists(name, vocalist, composer) VALUES(?, ?, ?);"
run_sql_command(cursor, sql_insert_artist, [name, is_vocalist, is_composer])
return cursor.lastrowid | 02955ac38edb7f16d622ff86a3ebff58daf14fda | 51,875 |
import argparse
def parse_arguments(argv):
"""Command line parse."""
parser = argparse.ArgumentParser()
parser.add_argument('--fig_mode', type=str, default=None, help='Plot experiment figures.')
return parser.parse_args() | ccae96d32b2351961909212e0300eeec08dece55 | 51,876 |
def predict(notes, onsets, n_tracks, states):
"""Predict the labels."""
# Create the prediction array
predictions = np.zeros(len(notes), int)
# Initialize states (recording the time until when each track is active)
track_states = np.zeros(n_tracks, int) if states else None
# Initialize last pi... | 2a3d901507e38ff3bd7804c667c84bd729a0da3f | 51,877 |
def getTower(creep, maxEnergyPercentage = 0.7):
"""
Gets the closest tower in the same room as a creep
:param creep: The creep to run
:param maxEnergyPercentage: The max energy percentage of total that the tower is allowed to have, between 0 and 1. 0 means only totally empty towers, 1 means only full to... | 349eea9902cbf7b096a347ec737066d7c00c3ef2 | 51,878 |
def png_encode(input, compress_level=3):
"""
Encode the image with PNG encoder.
Args:
img (:class:`numpy.ndarray`): uint8 color image array
quality (int): quality for JPEG compression
Returns bytes: encoded image data
"""
assert len(input.shape) == 3 and input.shape[2] in [3, 4... | 17694f5d6ec8803db8c10f5ed9d863bca21cbc3d | 51,879 |
import urllib
def _send_command(params, settings):
"""Send a command to the NVP API."""
params["VERSION"] = "64.4"
params["USER"] = settings["USERID"]
params["PWD"] = settings["PASSWORD"]
params["SIGNATURE"] = settings["SIGNATURE"]
keys = params.keys()
keys.sort()
pairs = [(k,params[k]... | 8dd40006b1c4d2e4c2c30a24577ba2fea39a4de3 | 51,880 |
def find_chimera_indices(G):
"""Attempts to determine the Chimera indices of the nodes in graph G.
See the `chimera_graph()` function for a definition of a Chimera graph and Chimera
indices.
Parameters
----------
G : NetworkX graph
Should be a single-tile Chimera graph.
Returns
... | becad5e96aa879662bd893932527cc34f7f4fa5a | 51,881 |
import io
import os
import json
def ini_to_json(in_file, out_file=None):
"""
Convert Deltares ini to json file.
If out_file is left empty, it returns the json as dictionairy
"""
# print("Script directory : %s" % _script_dir)
# print("Start directory : %s" % start_dir)
# print("Workin... | 9d1ac41e030f8b4ba2bbf719ce00db5141b722f4 | 51,882 |
def namespace(prefix):
"""Decorator that prefixes named variables.
Args:
prefix (str): Prefix to prepend to the name of named variables.
"""
def decorator(f_):
@wraps(f_)
def wrapped_f(*args, **kw_args):
# Replace all variable containers with their namespace variant... | f99d4014fc1be5894de0274176b5a74d7822e858 | 51,883 |
def serialize_representacion(declaracion):
"""
# $ref: '#/components/schemas/representaciones'
"""
representaciones = declaracion.representaciones_set.all()
to_be_add = []
for represent in representaciones:
titular = serialize_tipo_relacion(represent.cat_tipos_relaciones_personales)
... | e20c30b537c5089afa7f87208365279c76ca8f35 | 51,884 |
def calc_area(l, w):
"""
params: l and w are both real positive numbers representing the length and width of a rectangle
"""
if l <= 0 or w <= 0:
raise ValueError
return l * w | baf22572e8dcd9bf5c4c0fbe35c6d9aad82f6df5 | 51,885 |
def settings(request): # pylint: disable=unused-argument
"""Settings context_processor."""
db_settings = {}
default_settings = {
'title': 'Just another blog',
'tagline': '',
}
options = Option.objects.all()
for option in options:
db_settings[option.name] = option.value
... | bd1a226b967b13fae80963e7a8ceaedcc0ec847b | 51,886 |
from bs4 import BeautifulSoup
def get_games(soup=None):
"""Uses bs4 to get list of games on Steam Marketplace.
Argument:
(Optionally) soup: bs4 object to search on.
Returns:
Array of objects, containing all games on marketplace.
"""
if not isinstance(soup, BeautifulSoup):
... | 9dd5811ef5665a01691c105a8d751e95a49c2bc7 | 51,887 |
def print_summary(targets):
"""
Return 0 if all test passed
Return 1 if all test completed but one or more failed
Return 2 if one or more tests did not complete or was not detected
"""
passed = 0
failed = 0
tested = 0
expected = 0
return_code = 3
print("---------------------... | 47d38ba3dd9fb91b1384aa6e7fcbdfe71d560261 | 51,888 |
def get_names(line):
""" достаем из строки имена наташей """
names = []
matches = EXTRACTOR(line.title())
for match in matches:
fact = match.fact.as_json
if "first" in fact.keys() and "middle" in fact.keys() and "last" in fact.keys():
name = fact["first"][0].upper() + "." + f... | 1915eddf30e3a17310f44b9df93777187f69e4bc | 51,889 |
def logical_or(a, b):
"""A version of tf.logical_or that eagerly evaluates if possible."""
a_value = get_static_value(a)
if a_value is not None:
if np.isscalar(a_value):
if a_value:
return a_value
else:
return _maybe_static(b)
else:
return a_value | _maybe_static(b)
els... | 691eecb0b815806e2b2a30973ec983321fdba4c5 | 51,890 |
def massProperties(vertices, faces=None, factor=1.):
"""Compute the mass, center of mass, and inertia tensor of a polygon or polyhedron
Args:
vertices (list): List of (x, y) or (x, y, z) coordinates in 2D or 3D, respectively
faces (list): List of vertex indices for 3D polyhedra, or None for 2D.... | a4c66a407e83e96c5ad66ef88d30bede810aa184 | 51,891 |
def isDKA(filename):
"""
Checks whether a file is ASCII DKA k value format.
AAA
Geographical latitude: 43.250 N
Geographical longitude: 76.920 E
K-index values for 2010 (K9-limit = 300 nT)
"""
ok = False
try:
... | 2b9ba8ae53a701d47b26140de0427834f73a7a7c | 51,892 |
from typing import List
from typing import Tuple
from typing import Set
import ast
def getBuggyMethodsFromFile(
project_root: str, file: PatchedFile, is_target_file: bool
) -> List[Tuple[str, Set[int], ast.FunctionDef]]:
"""
Get a set of modified methods from a unidiff PatchedFile object
:param projec... | 6312c1a241f6eed095fe9be81005dfa6bbfabce0 | 51,893 |
def delate_materialslot_duplicate(arg_object:bpy.types.Object) -> bool:
"""指定オブジェクトのマテリアルスロットをソートする
Args:
arg_object (bpy.types.Object): 指定オブジェクト
Returns:
bool: 実行正否
"""
# オブジェクトがメッシュであるか確認する
if arg_object.type != 'MESH':
# 指定オブジェクトがメッシュでない場合は処理しない
return None
... | f2b87ae7ad99bbc9ab39af6664ae82253e09e33c | 51,894 |
def from_DataFrame(df,df_func=None,index_func=None,force_sharex=None):
"""
Create a sharex Pdata.Pdata object from pandas DataFrame
Parameters:
-----------
df_func: function that applies on DataFrame before feeding data into Pdata.
index_func: index function that will be applied before using th... | d5ac9e4e0146be1a85ba6007e092f465871f1c77 | 51,895 |
def run_dials_refine(experiments, reflections, params):
"""Functional interface to tasks performed by the program dials.refine.
This runs refinement according to the PHIL parameters in params, using
taking the initial experimental geometry from experiments, and the
observed reflection centroids from re... | 848aebc53483da9a9a87054e13110af29fce8cbb | 51,896 |
def clean_input(text):
"""
텍스트 정제 함수
:param text: 사용자가 입력한 텍스트
:return: ASCII 이외의 문자를 제거한 정제된 텍스트
"""
# 간단하게 시작하기 위해서 ASCII 문자만 사용합니다
return str(text.encode().decode("ascii", errors="ignore")) | a06f49cc5cc43516865a2b3a0b769e0802775e24 | 51,897 |
import sympy
def nearest_prime(lhs, ctx):
"""Element ∆p
(num) -> nearest prime to a
(str) -> python code from expression
"""
ts = vy_type(lhs)
if ts == NUMBER_TYPE:
if lhs < 2:
return 2
elif is_prime(lhs, ctx):
return lhs
return {
(NUMBER_TY... | 1411e3f79840c4039a95a467ef7f01f9fdcc2a5f | 51,898 |
def make_node2ancestors_recursively(node, node2ancestors):
"""
key=node, value=keyの全祖先のノードのセット
となる辞書を作る。
Args:
node: 全祖先を知りたいノード
node2ancestors: key=ノード, value=keyの全祖先のセット
Return:
nodeにターゲットが存在しない:要素がnodeのみのセット
nodeがnode2ancestors.keys()に存在する:node2ancestors[node]
... | cc48caf9af05bf906ac463af704c1522867ee986 | 51,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.