content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_axis_formatter(axis, params=None, **kwargs):
"""
Set axis formatter.
:param axis: Matplotlib axis instance.
:type axis: :class:`matplotlib.axes.Axes`
:param params: Axis formatter parameters.
:type params: dict, optional
Example config:
.. code-block:: python
'formatt... | 40,300 |
def convert_tzaware_time(t: time, tz_out: tp.Optional[tzinfo]) -> time:
"""Return as non-naive time.
`datetime.time` should have `tzinfo` set."""
return datetime.combine(datetime.today(), t).astimezone(tz_out).timetz() | 40,301 |
def total_posts():
"""
A simple template tag that shows the number
of posts that have been uploaded so far
"""
return Post.published.count() | 40,302 |
def make_policy_prior_network(
spec: specs.EnvironmentSpec, hidden_layer_sizes: Tuple[int, ...] = (64, 64)
) -> networks.FeedForwardNetwork:
"""Creates a policy prior network used by the agent."""
action_size = np.prod(spec.actions.shape, dtype=int)
def _policy_prior_fn(observation_t, action_tm1, is_trainin... | 40,303 |
def simulate_moment_contributions(params, x, y):
"""Calculate moment contributions for example from Honore, DePaula, Jorgensen."""
y_estimated = x.to_numpy() @ (params["value"].to_numpy())
x_np = x.T.to_numpy()
residual = y.T.to_numpy() - stats.norm.cdf(y_estimated)
mom_value = []
length = ... | 40,304 |
def main():
"""Enter main loop for normal bot operation."""
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s')
config = ImitateConfig()
bot = ImitateBot(config)
try:
bot.handle_messages()
except Exception as error:
print_exception(type(error), error, error.__t... | 40,305 |
def get_app_host_list(app_id):
"""
获取指定业务所有主机信息
:param app_id
:return dict: {"InnerIP": host_info}
"""
cc_result = bk.cc.get_app_host_list(app_id=app_id)
return cc_result | 40,306 |
def staking_product_quota(self, product: str, productId: str, **kwargs):
"""Get Personal Left Quota of Staking Product (USER_DATA)
Weight(IP): 1
GET /sapi/v1/staking/personalLeftQuota
https://binance-docs.github.io/apidocs/spot/en/#get-personal-left-quota-of-staking-product-user_data
Args:
... | 40,307 |
def test_dequeue_size_inherit(dq):
"""Test_dequeue_size_inherit."""
dq.appendleft(3)
dq.appendleft(2)
dq.appendleft(1)
assert dq.size() == 3 | 40,308 |
def run(nbtxt, output=None, view=False):
""" Run a notebook app 100% from JSON (text stream), return the JSON (text stream)
:param nbtxt: JSON representation of notebook app, ready to run
:param view: don't invoke notebook, just view in current form
NOTE: `view` probably isn't useful, si... | 40,309 |
def test_gens_eia860(pudl_out_eia):
"""Sanity checks for EIA 860 generator data."""
logger.info('Reading EIA 860 generator data...')
logger.info(f"{len(pudl_out_eia.gens_eia860())} records found.") | 40,310 |
def softmax(x):
"""
개선된 softmax 함수
"""
max_x = np.max(x)
y = np.exp(x - max_x) / np.sum(np.exp(x-max_x))
return y | 40,311 |
def lambda_handler(event, context):
"""
Event shape:
..code:: json
{
"Name": "layer name",
"Requirements": [
{
"Name": "Requirement Name",
"Details": "Requirement version or other identifying details"
}... | 40,312 |
def _update_config_list(config, list_key, values, insert):
"""
Add or remove items as required to/from a config value which is a list.
This exists in order to avoid clobbering values other than those which we
wish to add/remove, and to neatly remove a list when it ends up empty.
"""
section, li... | 40,313 |
def check_config_changes(db, latest, stored):
"""Yields jobs to update the AuthDB based on detected realms.cfg changes.
Args:
db: a permissions.DB instance with current permissions and roles.
latest: a list of RealmsCfgRev with all fetched configs.
stored: a list of RealmsCfgRev representing all curren... | 40,314 |
def _FloatTraitsBaseClass_write_values_attribute(a, v):
"""_FloatTraitsBaseClass_write_values_attribute(hid_t a, Floats v)"""
return _RMF_HDF5._FloatTraitsBaseClass_write_values_attribute(a, v) | 40,315 |
def get_cifar(root, dataset, transform, mode = 'train'):
"""Get cifar data set
Args :
--root: data root
--dataset: dataset name
--transform: transformation
--mode: 'train'/'test'
"""
assert dataset.count('cifar')
if dataset == 'cifar10':
dataset = ... | 40,316 |
def config(base_config):
""":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests."""
config_file = Path(base_config.file)
with config_file.open("at") as f:
f.write(
textwrap.dedent(
"""\
file group: allen
... | 40,317 |
async def test_client_app_delete_error_handling(
aiohttp_server, config, db, loop, caplog
):
"""For the delete() method of the KubernetesClient, test the handling of response
with a 404 error and with an error with another status.
There are three states:
0. initialisation
1. when deleti... | 40,318 |
def mark_cell_function(fun, mesh, foc, regions):
"""
Iterates over the mesh and stores the
region number in a meshfunction
"""
if foc is None:
foc = calculus.estimate_focal_point(mesh)
for cell in dolfin.cells(mesh):
# Get coordinates to cell midpoint
x = cell.midpoint... | 40,319 |
def process_clients():
"""
Check each client, if client.cmd_ready == True then there is a line of
input available via client.get_command().
"""
for client in CLIENT_LIST:
if client.active and client.cmd_ready:
# If the client sends input echo it to the chat room
chat(... | 40,320 |
def test_initials_regex_3():
"""Test - uppercase initials regex with ABCD"""
from titlecase import UC_INITIALS
assert bool(UC_INITIALS.match('ABCD')) is False | 40,321 |
def incorrect_format():
"""for handling incorrect json format"""
js = json.dumps({'error': 'Incorrect format.'})
return Response(js, status=422, mimetype='application/json') | 40,322 |
def write_file_nc3_64bit_offset(file_path: str):
"""
Create a `NETCDF3_64BIT_OFFSET` data file.
"""
with netCDF4.Dataset(file_path, format="NETCDF3_64BIT_OFFSET", mode="w") as ds:
ds.setncatts({
"title": "Example of NETCDF3_64BIT_OFFSET file",
"Conventions": "CF-1.8",
... | 40,323 |
def start_multiprocessing(function_list, data_list):
"""
Creates and runs a multiprocessing pool for (1..n) functions all of which
use the same data_list (e.g. YouTube video links). Returns a dictionary
of results indexed by function.
"""
with multiprocessing.Pool(initializer=set_global_session... | 40,324 |
def GetNodeProperty(line):
"""
Get node property from a string.
:param line: a string
:return: name, size, and position of the node
"""
name, attr = NameAndAttribute(line)
name = ProcessName(name, False)
position = GetAttributeValue("pos", attr)[:-1].replace(",", "-")
attr = CleanAt... | 40,325 |
def login(request):
"""
Logs in a user.
"""
if request.method != "GET":
return _methodNotAllowed()
options = _validateOptions(request, {})
if type(options) is str:
return _response(options)
user = userauth.authenticateRequest(request, storeSessionCookie=True)
if type(user) is... | 40,326 |
def wavenumber(f, h, g=9.81):
""" solves the dispersion relation, returns the wave number k
INPUTS:
omega: wave cyclic frequency [rad/s], scalar or array-like
h : water depth [m]
g: gravity [m/s^2]
OUTPUTS:
k: wavenumber
"""
omega = 2*np.pi*f
if hasattr(omega, '__len__... | 40,327 |
def test_setitem_rightvalue_ndarray_fails():
"""
Now we don't automatically add dimensions to broadcast
"""
a = numpy.arange(3 * 4 * 5)
a.resize((3, 4, 5))
a = theano._asarray(a, dtype='float32')
_a = cuda_ndarray.CudaNdarray(a)
b = theano._asarray([7, 8, 9, 10], dtype='float32')
_b... | 40,328 |
def command(cmd, label, env={}):
"""Create a Benchpress command, which define a single benchmark execution
This is a help function to create a Benchpress command, which is a Python `dict` of the parameters given.
Parameters
----------
cmd : str
The bash string that makes up the command
... | 40,329 |
def adcp_beam_northward(b1, b2, b3, b4, h, p, r, vf, lat, lon, z, dt):
"""
Description:
Wrapper function to compute the Northward Velocity Profile (VELPROF-VLN)
from beam coordinate transformed velocity profiles as defined in the
Data Product Specification for Velocity Profile and... | 40,330 |
def test_string_format():
"""
String formatting is not ok in logging statements.
"""
tree = parse(dedent("""\
import logging
logging.info("Hello {}".format("World!"))
"""))
visitor = LoggingVisitor()
visitor.visit(tree)
assert_that(visitor.violations, has_length(1))
... | 40,331 |
def _convert_optimization(model: BDF,
xyz_scale: float,
mass_scale: float,
weight_scale: float,
time_scale: float) -> None:
"""
Converts the optimization objects
Limited Support: DESVAR, DCONSTR, DVCREL1... | 40,332 |
def get_text(string):
"""
normalizing white space and stripping HTML markups.
"""
text = re.sub('\s+',' ',string)
text = re.sub(r'<.*?>',' ',text)
return text | 40,333 |
def decode_ia(ia: int) -> str:
""" Decode an individual address into human readable string representation
>>> decode_ia(4606)
'1.1.254'
See also: http://www.openremote.org/display/knowledge/KNX+Individual+Address
"""
if not isinstance(ia, int):
ia = struct.unpack('>H', ia)[0]
retur... | 40,334 |
def show():
""" Show the Add-on Manager's user interface. """
global _manager_window
if not _manager_window:
_manager_window = ManagerWindow()
# Show the manager.
_manager_window.showRaise() | 40,335 |
def dd_to_dms(deg):
"""Return degrees, minutes, seconds from degrees decimal"""
mins, secs = divmod(deg * 3600, 60)
degs, mins = divmod(mins, 60)
return array((degs, mins, secs), dtype='i4') | 40,336 |
def test_feed_from_annotations_html_links():
"""Items should include links to the annotations' HTML pages."""
annotation_url = _annotation_url()
feed = rss.feed_from_annotations(
[factories.Annotation()], annotation_url, mock.Mock(), '', '', '')
item = feed['entries'][0]
assert item['link'... | 40,337 |
def _compare_labels(primary, label1, label2):
"""
Compare two labels disposition
:param primary: the primary label
:param label1: the first label
:param label2: the second label
:return A tuple containing True if there is no difference False otherwise
and the output text
"""
... | 40,338 |
def set_pause(df, index, ts_name):
"""
:param df:
Spark DataFrame object with timestamp data
:param index:
fix index type: 'i1', 'i2', 'i3', 'j1', 'j2', 'j3'
:param ts_name:
column with timestamp data
:return:
Spark DataFrame object with timestamp data
"""
... | 40,339 |
def _validate_magics_flake8_warnings(actual: str, test_nb_path: Path) -> bool:
"""Validate the results of notebooks with warnings."""
expected = (
f"{str(test_nb_path)}:cell_1:1:1: F401 'random.randint' imported but unused\n"
f"{str(test_nb_path)}:cell_1:2:1: F401 'IPython.get_ipython' imported ... | 40,340 |
def _drop_index(index, autogen_context):
"""
Generate Alembic operations for the DROP INDEX of an
:class:`~sqlalchemy.schema.Index` instance.
"""
text = "%(prefix)sdrop_index(%(name)r, "\
"table_name='%(table_name)s'%(schema)s)" % {
'prefix': _alembic_autogenerate_prefix(autogen_... | 40,341 |
def postProcessParser(fname, out_fn=""):
"""Accepts a .ass file with timestamps and adds a second text layer to each dialogue.
This should only be used AFTER the timestampers have added their timestamps
Args:
fname (string): Full path to the .ass file WITHOUT the extension
[out_fn] (str... | 40,342 |
def print_repeat_info(r_dict, num):
"""
r_dict : dict of multiple dna sequence names and sequences
Returns: None
To analyze the repeats in a multi-dna-dict
"""
seqdict, repeatdict = loop_repeats(r_dict, num)
for seq_id in seqdict:
# print(seq_id, *seqdict[seq_id].items(), sep='\n'... | 40,343 |
def add_metabolite_drain_reactions(mod_, metab_list, prefix_id="MDS"):
"""Take in a model and add metabolite drain reactions for a list of metabolites
in the model. These metabolite drain reactions will have the identification
of (MDS)__(metabolite id). (i.e., MDS__atp_c for the atp_c metabolite)
"""
... | 40,344 |
def contract(ctx: Context, public_id: PublicId):
"""Eject an installed contract."""
_eject_item(ctx, "contract", public_id) | 40,345 |
def tax_total(par):
"""
Finds total tax burden in a log normal distributed population
Args:
par: simplenamespace containing relevant parameters
phi (float): C-D weights
epsilon (float): public housing assement factor
r (float): mortgage interest
... | 40,346 |
def _split_uri(uri):
"""
Get slash-delimited parts of a ConceptNet URI.
Args:
uri (str)
Returns:
List[str]
"""
uri = uri.lstrip("/")
if not uri:
return []
return uri.split("/") | 40,347 |
def file_len(fname):
""" Calculate the length of a file
Arguments:
Filename: Name of the file wanting to count the rows of
Returns:
i+1: Number of lines in file
"""
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1 | 40,348 |
def create_initializer(initializer_range=0.001):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.compat.v1.truncated_normal_initializer(stddev=initializer_range) | 40,349 |
def collapse_columns(
df: ContactsTable, names: List[str], new_name: str
) -> ContactsTable:
"""
This function assumes that df has both columns and indexes identified by the same `names`. They will all be added
together to create a new column and row named `new_name`. Eg.:
>>> df = ContactsTable(pd... | 40,350 |
def current_date(pattern="%Y-%m-%d %H:%M:%S"):
"""
获取当前日期
:param: pattern:指定获取日期的格式
:return: 字符串 "20200615 14:57:23"
"""
return time.strftime(pattern, time.localtime(time.time())) | 40,351 |
def test_authorize_code_id_token_flow(flask_client):
"""make sure the authorize redirects user to correct page for the *ID-Token Code Flow*
, ie when response_type=id_token,code
The /authorize endpoint should return an id_token, code and id_token must contain *c_hash*
The /token endpoint must return a ... | 40,352 |
def ubi(funding_billions=0, percent=0):
""" Calculate the poverty rate among the total US population by:
-passing a total level of funding for a UBI proposal (billions USD),
-passing a percent of the benefit recieved by a child and the benefit
recieved by an adult
AND
taking into account that fund... | 40,353 |
def validate_record(valrecord):
""" primary procedure which calls the coder with the parse in valrecord and compares the coded results with the expected
as well as writing assorted intermediate data structures to fout per test_script_ud.py """
def process_event_output(str):
""" from test_scrip... | 40,354 |
def local_disp_centr(x, y, image, disp_n, size_k, mode):
"""
Returns a tuple: (disp_l, centr_l)
"""
border_pixels = image[x-size_k//2 : x+size_k//2+1, y-size_k//2 : y+size_k//2+1]
if mode == 'robust':
percentiles = np.percentile(border_pixels, [75, 50, 25])
disp_l = percentiles[2] ... | 40,355 |
async def get_music_list() -> MusicList:
"""
获取所有数据
"""
async with aiohttp.request("GET", 'https://www.diving-fish.com/api/maimaidxprober/music_data') as obj_data:
if obj_data.status != 200:
raise aiohttp.ClientResponseError('maimaiDX曲目数据获取失败,请检查网络环境')
else:
data ... | 40,356 |
def split_data(data_index,data_dir,amount):
"""
Split data into 'train' and 'test' sets.
Data index = csv filename
Data dir = directory in which data is stored
Amount = percentage of data to be imported ( to reduce memory usage )
"""
lfiles = []
with open(data_index,... | 40,357 |
def isValidPasswordPartTwo(firstIndex: int, secondIndex: int, targetLetter: str, password: str) -> int:
"""
Takes a password and returns 1 if valid, 0 otherwise. Second part of the puzzle
"""
bool1: bool = password[firstIndex - 1] == targetLetter
bool2: bool = password[secondIndex - 1] == targetLetter
... | 40,358 |
def get_fasta(proteinID, disorder, outdir):
"""
Takes uniprot id, save a fasta file with a sequence
and returns sequence length
"""
try:
url = "http://mobidb.bio.unipd.it/ws/entries/" + proteinID + "/uniprot"
response = requests.get(url)
print(url)
if response.status... | 40,359 |
def debug_validator(validator: ValidatorType) -> ValidatorType:
"""
Use as a wrapper around a validator, e.g.
.. code-block:: python
self.validator = debug_validator(OneOf(["some", "values"]))
If you do this, the log will show the thinking of the validator (what it's
trying to validate, a... | 40,360 |
def abort_document_runs_on_delete(sender, instance, using, **kwargs):
"""Any document runs associated with a DocumentUrl should be aborted at CF on delete."""
if instance.cloudfactorydocumentrun_set.exists():
tasks = importlib.import_module('myhpom.tasks')
for run in instance.cloudfactorydocumen... | 40,361 |
def test_Is_To_Explode__No_Disk(score, max_score):
"""Function is_to_explode: no disk at position."""
max_score.value += 2
try:
set_up()
assert not Board.is_to_explode(test_board_6, (1, 3))
score.value += 2
except:
pass | 40,362 |
def read_yaml_or_json(url: str) -> dict:
"""Read a YAML or JSON document.
:param url: URL or path; if `url` ends with '.yaml', the document is interpreted
as YAML, otherwise it is assumed to be JSON.
:return: a dictionary with the document contents.
"""
with open_url(url, decode=True) as fp... | 40,363 |
def diagEst(matFun, n, k=None, approach='Probing'):
"""
Estimate the diagonal of a matrix, A. Note that the matrix may be a
function which returns A times a vector.
Three different approaches have been implemented:
1. Probing: cyclic permutations of vectors with 1's and 0's (defaul... | 40,364 |
def flatten(_list):
"""
Deeply flattens an iterable.
"""
for el in _list:
if isinstance(el, collections.Iterable) and not isinstance(
el, (str, bytes)
):
yield from flatten(el)
else:
yield el | 40,365 |
async def test_four_word_register_precision_is_lost_with_float_params(hass, mock_hub):
"""Test that precision is affected when floating point conversion is done."""
register_config = {
CONF_COUNT: 4,
CONF_DATA_TYPE: DATA_TYPE_UINT,
CONF_SCALE: 2.0,
CONF_OFFSET: 3.0,
CONF_... | 40,366 |
def delete_a_recipe(category_id, recipe_id):
"""Method to handle delete permanently a single recipe"""
user_id = decode_auth_token(request.headers.get("Authorization"))
if isinstance(user_id, int):
recipe = Recipe()
response = recipe.delete_recipe(category_id, recipe_id)
return respo... | 40,367 |
def test_index_get():
"""
GIVEN a Flask application
WHEN the '/' page is requested (GET)
THEN check that the response is valid
"""
with app.test_client() as client:
response = client.get('/')
assert response.status_code == 200
assert response.data == b'Hello World 1' | 40,368 |
def hydrate_datatrust_state(data={}):
"""
Given a dictionary, allow the viewmodel to hydrate the data needed by this view
"""
vm = State()
return vm.hydrate(data) | 40,369 |
def preprocess_data(X, Y):
""" This method has the preprocess to train a model """
X_p = X
# changind labels to one-hot representation
Y_p = K.utils.to_categorical(Y, 9)
return (X_p, Y_p) | 40,370 |
def readLog(logPath):
"""Reads a file containing an array of json objects. \
Used with the 'gcloudformatter' function.
Args:
logPath: file system path to map file
Returns:
An array of json objects
"""
logger.info("Reading log {}".format(logPath))
with open(logPath, 'r'... | 40,371 |
def save_traces_file(traces_file_name, animals_list: List[Animal]):
"""
Saves TRACES compatible import file, based on animals in animals_list
:param traces_file_name:
:param animals_list:
:return:
"""
def save_traces_file_cattles():
fd = open(traces_file_name, 'w')
try:
... | 40,372 |
def get_KNN(X, k):
"""Identify nearest neighbours
Parameters
----------
D : array, [n_samples, n_features]
input data
k : int
number of nearest neighbours
Returns
-------
knn_graph : array, [n_samples, n_samples]
Connectivity matrix ... | 40,373 |
def WriteAbsoluteFileList(filename, file_list):
"""Write a file containing a sorted list of absolute paths in the branch.
Args:
filename: The file to write.
file_list: An unsorted list of file paths, given relative to the WebKit
checkout (e.g., 'WebCore/ChangeLog').
"""
logging.info('Saving %s'... | 40,374 |
def test_alignment_workflow(clean_files):
"""Test that we can solvate CB6-BUT after alignment."""
cb6 = pmd.load_file(
os.path.join(
os.path.dirname(__file__), "../data/cb6-but/cb6-but-notcentered.pdb"
)
)
zalign(cb6, ":CB6", ":BUT", save=True, filename="./tmp/tmp.pdb")
w... | 40,375 |
def createMode():
"""Required to initialize the module. RV will call this function to create your mode."""
return AudioForSequence() | 40,376 |
def pre_process(cpp_line):
"""预处理"""
# 预处理
cpp_line = cpp_line.replace('\t', ' ')
cpp_line = cpp_line.replace('\n', '')
cpp_line = cpp_line.replace(';', '')
return cpp_line | 40,377 |
def actions_db(action_id):
"""
replaces the actual db call
"""
if action_id == 'not found':
return None
elif action_id == 'state error':
return {
'id': 'state error',
'name': 'dag_it',
'parameters': None,
'dag_id': 'state error',
... | 40,378 |
def _safe_clear_dirflow(path):
"""
Safely check that the path contains ONLY folders of png files,
if any other structure, will simply ERROR out.
Parameters
----------
path: str
string to the path to the folders of data images to be used
"""
print("Clearing {}...".format(path))
... | 40,379 |
def parse(argv):
"""
Parse command line options. Returns the name of the command
and any additional data returned by the command parser.
May raise CommandParsingError if there are problems.
"""
# Find the command
if len(argv) < 1:
full = None
cmd = comman... | 40,380 |
def _get_answer_spans(text, ref_answer):
"""
Based on Rouge-L Score to get the best answer spans.
:param text: list of tokens in text
:param ref_answer: the human's answer, also tokenized
:returns max_spans: list of two numbers, marks the start and end position with the max score
"""
max_s... | 40,381 |
def order(list, cmp=None, key=None, reverse=False):
""" Returns a list of indices in the order as when the given list is sorted.
For example: ["c","a","b"] => [1, 2, 0]
This means that in the sorted list, "a" (index 1) comes first and "c" (index 0) last.
"""
if cmp and key:
f = lambd... | 40,382 |
def get_maximum_batch_id(path: Pathy) -> int:
"""
Get the last batch ID. Works with GCS, AWS, and local.
Args:
path: The path folder to look in.
Begin with 'gs://' for GCS. Begin with 's3://' for AWS S3.
Supports wildcards *, **, ?, and [..].
Returns: The maximum ba... | 40,383 |
def save_commits(repo, commits):
"""
Save list of commits
:param repo_url: full github repo URL
:param commits: list of commits
"""
db.commit.insert_many(map(
lambda commit: {
'repositoryURL': repo.url,
'date': commit['commit']['committer']['date']
},
... | 40,384 |
def delete(id: int):
"""Delete a file move setting.
Arguments:
id {int} -- the setting id
"""
deleted_setting = delete_config(id)
if deleted_setting:
regexp, path = deleted_setting
click.echo('Deleted setting: {} => {}.'.format(regexp, path))
exit(0)
else:
... | 40,385 |
def delete_system_outage(outage_id, **kwargs):
"""
Delete a system outage.
"""
import sfa_api.utils.storage_interface as storage
storage._call_procedure(
'delete_system_outage', str(outage_id),
with_current_user=False
)
click.echo(f"Successfully deleted outage {outage_id}") | 40,386 |
def curl_post(method, txParameters=None, RPCaddress=None, ifPrint=False):
"""
call Ethereum RPC functions
"""
payload = {"jsonrpc": "2.0",
"method": method,
"id": 1}
if txParameters:
payload["params"] = [txParameters]
headers = {'Content-type': 'application/... | 40,387 |
def intRoexpwt2(g1, g2, p, w, t):
""" Integral of the roexpwt filter Oxenham & Shera (2003) equation (3)
Parameters
----------
g1, g2 - Limits of the integral in normalized terms (eg.: g1=0.1,g2=0.35)
p - SLope parameter
t - Factor by which second slope is shallower than first
w - relative ... | 40,388 |
def create_connection(query):
"""
クエリを発行するためのデコレータ
:param query: クエリストリング
:return:
"""
def wrapper(*args, **kargs):
config = Config()
connection = pymysql.connect(host= config.nijo_db_host,
user= config.nijo_db_user,
password= config... | 40,389 |
def numentries(arrays):
"""
Counts the number of entries in a typical arrays from a ROOT file,
by looking at the length of the first key
"""
return arrays[list(arrays.keys())[0]].shape[0] | 40,390 |
def update_job_completed_time(sender, instance, raw, using, update_fields, **kwargs):
"""
Takes actions every time a Job is saved, so changes to certain fields
can have side effects (eg automatically setting completion time).
"""
try:
obj = sender.objects.get(pk=instance.pk)
except sende... | 40,391 |
def build_jax_solve_eval_fwd(fenics_templates: FenicsVariable) -> Callable:
"""Return `f(*args) = build_jax_solve_eval(*args)(ofunc(*args))`. This is forward mode AD.
Given the FEniCS-side function ofunc(*args), return the function
`f(*args) = build_jax_solve_eval(*args)(ofunc(*args))` with
the JVP of `... | 40,392 |
def gen_gcam_target(imgs, model, target_layer='layer4', target_index=None, classes=get_imagenet_classes(), device='cuda', prep=True):
"""
Visualize model responses given multiple images
"""
# Get model and forward pass
gcam, probs, ids, images = gen_model_forward(imgs, model, device=device, p... | 40,393 |
def get_insert_query(table_name):
"""Build a SQL query to insert a RDF triple into a PostgreSQL dataset"""
return f"INSERT INTO {table_name} (subject,predicate,object) VALUES (%s,%s,%s) ON CONFLICT (subject,predicate,object) DO NOTHING" | 40,394 |
def q_mult(q1, q2):
"""Quaternion multiplication."""
w = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3]
x = q1[1] * q2[0] + q1[0] * q2[1] + q1[2] * q2[3] - q1[3] * q2[2]
y = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1]
z = q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1]... | 40,395 |
def is_object_group(group):
"""True if the group's object name is not one of the static names"""
return not group.name.value in (IMAGE, EXPERIMENT, OBJECT_RELATIONSHIPS) | 40,396 |
def test_message_inside_sysex():
"""Non-realtime message inside sysex should reset the parser."""
assert tokenize([0xf0, 0x90, 1, 2, 0xf7]) == [[0x90, 1, 2]] | 40,397 |
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python dict, if it is ... | 40,398 |
def makeProblemList(ds, source):
"""
Analyze source code dataset and
write down list of problems to tokenized dataset
Parameters:
- ds -- directory of tokenized datset to be constructed
- source -- directory with source code files of problem solutions
"""
_problems = os.listdir(so... | 40,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.