content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def isready() -> bool:
"""Is the embedded R ready for use."""
INITIALIZED = RPY_R_Status.INITIALIZED
return bool(
rpy2_embeddedR_isinitialized == INITIALIZED.value
) | ce9bc69c897004f135297331c33101e30e71dca7 | 3,649,600 |
def yolo2_loss(args, anchors, num_classes, label_smoothing=0, use_crossentropy_loss=False, use_crossentropy_obj_loss=False, rescore_confidence=False):
"""YOLOv2 loss function.
Parameters
----------
yolo_output : tensor
Final convolutional layer features.
true_boxes : tensor
Ground ... | bd0c123872e564beee45c0a9084bb043eb03b778 | 3,649,601 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Tuple
import types
def create_compressed_model(model: tf.keras.Model,
config: NNCFConfig,
compression_state: Optional[Dict[str, Any]] = None) \
-> Tuple[Compres... | 42ffc9c9426ce8b95db05e042fa2d51098fc544f | 3,649,602 |
def load_misc_config():
"""Load misc configuration.
Returns: Misc object for misc config.
"""
return Misc(config.load_config('misc.yaml')) | b1eb2e8cc3e836b846d292c03bd28c4449d80805 | 3,649,603 |
def filter_activations_remove_neurons(X, neurons_to_remove):
"""
Filter activations so that they do not contain specific neurons.
.. note::
The returned value is a view, so modifying it will modify the original
matrix.
Parameters
----------
X : numpy.ndarray
Numpy Matri... | 711a858f8d28e5d0909991d85538a24bf063c523 | 3,649,604 |
def adaptive_threshold(im, block_size, constant, mode=cv2.THRESH_BINARY):
"""
Performs an adaptive threshold on an image
Uses cv2.ADAPTIVE_THRESH_GAUSSIAN_C:
threshold value is the weighted sum of neighbourhood values where
weights are a gaussian window.
Uses cv2.THRESH_BINARY:
... | c237a0bb05dc8a43495f60ef9d8157c4b9c4bf1f | 3,649,605 |
def get_loss(stochastic, variance_regularizer):
"""Get appropriate loss function for training.
Parameters
----------
stochastic : bool
determines if policy to be learned is deterministic or stochastic
variance_regularizer : float
regularization hyperparameter to penalize high varianc... | e78d47c31a7762bcb091ea1a314348c27f2174b7 | 3,649,606 |
import copy
def simul_growth_ho_amir(nbstart, run_time, params, name):
"""Simulate the Ho and Amir model (Front. in Microbiol. 2015) with inter-initiation per origin adder and
timer from initiation to division
Parameters
----------
nbstart : int
number of cells to simulate
run_ti... | fa4d35cfd26dbcb08217b3ffee6cf4e3e7431a08 | 3,649,607 |
def variable_id(variable):
"""Return variable identification for .dot file"""
if isinstance(variable, FileAccess):
return "a_{}".format(variable.id)
act_id = variable.activation_id
act_id = "global" if act_id == -1 else act_id
return "v_{}_{}".format(act_id, variable.id) | b68fd9d6b08a537768dc82b7925f0cb6f383428e | 3,649,608 |
def node_set_power_state(request, node_id, state, soft=False):
"""Set power state for a given node.
:param request: HTTP request.
:param node_id: The UUID or name of the node.
:param state: the power state to set ['on', 'off', 'reboot'].
:param soft: flag for graceful power 'off' or reboot
:ret... | e94a13f4a797d31bd0eae24803a782b049ea44dc | 3,649,609 |
import sympy
def __sympyToC_Grad(exprs: list, doOpts: bool = False) -> str:
""" creates C code from a list of sympy functions (somewhat optimized).
source: https://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy
and modified """
tmpsyms = sympy.numbered_symbols("tmp")
if do... | 33a95d99b19458ac7b8dd8d8e4272485b0f5f206 | 3,649,610 |
import os
import logging
import sys
def startServer(mock=True, mockS3=False):
"""
Test cases that communicate with the server should call this
function in their setUpModule() function.
"""
# If the server starts, a database will exist and we can remove it later
dbName = cherrypy.config['databa... | 02bd95f96adda8a9af194952bcbe82c71235d07e | 3,649,611 |
def index():
"""User friendly index page at the root of the server
guides the user to the reportss
"""
return render_template('index.html') | 0e810716e0bbfae98736bc13f458636eb33dc87d | 3,649,612 |
def read_lookup(infile):
"""
-----------------------------------------------------------------------------
Read data from a lookup database.
Inputs:
infile [string] Input file containing the lookup data base.
Outputs:
[tuple] each element of the tuple is a numpy array. The elements in ... | a86a2e8da2580e66656f8328488941c402383c60 | 3,649,613 |
import traceback
import sys
def sum_function(context, nodeset, string):
"""
The dyn:sum function calculates the sum for the nodes passed as the first
argument, where the value of each node is calculated dynamically using an
XPath expression passed as a string as the second argument.
http://www.ex... | dac1abae26522db33826f0a0e635e9afb4b3efc1 | 3,649,614 |
import json
def event_detail(request, id):
""" Return a JSON dict mapping for event given id
"""
event = get_object_or_404(Event, pk=id)
event_dict = {
"success": 1,
"result": [{
"id": event.id,
"title": event.title,
"description": event.description,... | 4b4083a81d5de90e9156f05d9f7b0375981a42d0 | 3,649,615 |
import logging
def prepare_state(qubits: list[cirq.Qid], x: int) -> list[cirq.Gate]:
"""Prepare qubits into an initial state.
Args:
qubits: The qubits to prepare.
x: The initial state of the qubits. Must be non-negative.
Returns:
A list of gates to prepare the qubits.
Raises... | f11a4ddd83a6e2d1d7348c8ef3b5693a26e3e26d | 3,649,616 |
def manage(id):
"""Manage room request."""
room_request = RoomRequest.query.get(id)
if room_request is None:
return abort(404)
return render_template('room_request/manage.html', room_request=room_request) | 5a565342adbe53a647cb622e4688d1c26d88078d | 3,649,617 |
def ger(self, y):
"""Computer an outer product between two vectors"""
assert self.dim() == 1 and y.dim() == 1, "Outer product must be on 1D tensors"
return self.view((-1, 1)).matmul(y.view((1, -1))) | 003dda3dd678fdcf35f63f80c064586320c97d23 | 3,649,618 |
def load_data(database_filepath):
"""
Input:
1. database_filepath: the path of cleaned datasets
Output:
1. X: all messages
2. y: category columns generated by cleaning process
3. category_names: category columns' names
Process:
1. Read-in the datafrmae
2. ... | 15ec78cfac2dfde9294061432514001b21967b93 | 3,649,619 |
def lh_fus(temp):
"""latent heat of fusion
Args:
temp (float or array): temperature [K]
Returns:
float or array: latent heat of fusion
"""
return 3.336e5 + 1.6667e2 * (FREEZE - temp) | 8127970612b031d2aaf7598379f41b549a3268e1 | 3,649,620 |
def to_eaf(file_path, eaf_obj, pretty=True):
"""
modified function from https://github.com/dopefishh/pympi/blob/master/pympi/Elan.py
Write an Eaf object to file.
:param str file_path: Filepath to write to, - for stdout.
:param pympi.Elan.Eaf eaf_obj: Object to write.
:param bool pretty: Flag to ... | 605e7f711f34661daae6869419d6f8bebb05a2c4 | 3,649,621 |
def delete_station(station_id):
"""Delete station from stations
:param station_id:
:return: string
"""
logger.debug(f"Call delete_stations: {station_id}")
# Load old data into structure
stations = load_stations()
# Find index in list of stations
target_index = find_index_in_list_of_d... | d377f2b029cb206ec78acf220a83bf88df8fd758 | 3,649,622 |
def query_for_build_status(service, branch, target, starting_build_id):
"""Query Android Build Service for the status of the 4 builds in the target
branch whose build IDs are >= to the provided build ID"""
try:
print ('Querying Android Build APIs for builds of {} on {} starting at'
' buildID {}'... | 4e1e04dae1ce13217374207a1b57d7380552dfc5 | 3,649,623 |
def create_pool(
dsn=None,
*,
min_size=10,
max_size=10,
max_queries=50000,
max_inactive_connection_lifetime=300.0,
setup=None,
init=None,
loop=None,
authenticator=None,
**connect_kwargs,
):
"""Create an Asyncpg connection pool through Approzium authentication.
Takes s... | 0b50a4cba07fb4797e04cc384dd46d1e21deed12 | 3,649,624 |
import logging
def _get_all_schedule_profile_entries_v1(profile_name, **kwargs):
"""
Perform a GET call to get all entries of a QoS schedule profile
:param profile_name: Alphanumeric name of the schedule profile
:param kwargs:
keyword s: requests.session object with loaded cookie jar
... | 32d6278ce6704feb5831012c2d0050b226fc7dfa | 3,649,625 |
def loadSource(path):
"""Loads a list of transportReactions. Format:
R("Macgamb_Transp")
R("Madnb_Transp")
R("MalaDb_Transp")..."""
file = open(path, 'r')
sources = [line.strip() for line in file]
file.close()
return sources | 244e9e5619a5039822ef14dfbb3d99b55cb6cc74 | 3,649,626 |
from typing import Optional
import struct
def frombin(
__data: Bitcode,
__dtype: SupportedDataType | bytes,
num: int = 1,
*,
encoding: Optional[str] = None,
signed: bool = True,
) -> ValidDataset:
"""converts a string of 0 and 1 back into the original data
Args:
data (BinaryCo... | 6fa7219ea8622071c7bb3277c8b59717543e9286 | 3,649,627 |
def check_size():
"""Assumes the problem size has been set by set_size before some operation.
This checks if the size was changed
Size is defined as (PIs, POs, ANDS, FF, max_bmc)
Returns TRUE is size is the same"""
global npi, npo, nands, nff, nmd
#print n_pis(),n_pos(),n_ands(),n_latches()
... | 361edb3b4f20a3ae4920c784ad2d1c56fe35e2d6 | 3,649,628 |
def vrms2dbm(vp):
"""
Converts a scalar or a numpy array from volts RMS to dbm assuming there is an impedence of 50 Ohm
Arguments:
- vp: scalar or numpy array containig values in volt RMS to be converted in dmb
Returns:
- scalar or numpy array containing the result
"""
return ... | 7d0f76ab74cf82d2d56f97840153f1b9bc3cb8a8 | 3,649,629 |
def aa_i2c_read (aardvark, slave_addr, flags, data_in):
"""usage: (int return, u08[] data_in) = aa_i2c_read(Aardvark aardvark, u16 slave_addr, AardvarkI2cFlags flags, u08[] data_in)
All arrays can be passed into the API as an ArrayType object or as
a tuple (array, length), where array is an ArrayType objec... | 59cca99e3ae811e957f9dd053205f3639c1451a4 | 3,649,630 |
import os
def get_log_dir(env=None):
"""
Get directory to use for writing log files. There are multiple
possible locations for this. The ROS_LOG_DIR environment variable
has priority. If that is not set, then ROS_HOME/log is used. If
ROS_HOME is not set, $HOME/.ros/log is used.
@param env: ov... | 9ede24a3afdf9869171c49f7f238b5b0a608830b | 3,649,631 |
def urbandictionary_search(search):
"""
Searches urbandictionary's API for a given search term.
:param search: The search term str to search for.
:return: definition str or None on no match or error.
"""
if str(search).strip():
urban_api_url = 'http://api.urbandictionary.com/v0/define?te... | 3cd63486adc11f3ca20d4cd6216006d3f2d2239f | 3,649,632 |
def Performance(ALGORITHM_CONFIG, CELLULAR_MODEL_CONFIG, alog_name):
"""
Performance testing
"""
# Server profile: num_ues=200, APs=16, Scale=200.0, explore_radius=1
loadbalanceRL = interface.Rainman2(SETTINGS)
loadbalanceRL.algorithm_config = ALGORITHM_CONFIG
loadbalanceRL.environment_confi... | 87e5d6b0c400af0262b6a2c746e855b9b71a5c35 | 3,649,633 |
def launch(sid):
"""
Launch a scan
Launch the scan specified by the sid.
"""
data = connect('POST', '/scans/{0}/launch'.format(sid))
return data['scan_uuid'] | fa99e7a50e9e2ddb30ba131ebd61c998c2cdabaa | 3,649,634 |
import ast
def transpose_dict(data, data_key):
"""Function: transpose_dict
Description: Transpose specified keys in a list of dictionaries
to specified data types or None.
Arguments:
(input) data -> Initial list of dictionaries.
(input) data_key -> Dictionary of keys and data ... | 7675ea2f80e9e85993dc99a2a31df04abfeba2c8 | 3,649,635 |
def aligner_to_symbol(calls):
"""
Assign symbols to different aligners in the input file
Set the attribute of the class instances
return a list of indices for which each aligner is found uniquely and all aligners
sorted by aligners
"""
symbols = ['o', '+', 'x', 'v', '*', 'D', 's', 'p', '8',... | b9cef3ae33b6ce84daf78a8bc8ce528f97d7a8a6 | 3,649,636 |
import sys
def timestamped_filename(line):
"""Given a line like '.... filename <timestamp>', return filename."""
m = re_timestamped_line.search(line)
if m:
return m.group("filename")
else:
print >> sys.stderr, "Error: could not find filename in:", line
return None | 5c63f976b1b56f347ab5926bd4247dad342b44e6 | 3,649,637 |
def nfvi_create_subnet(network_uuid, subnet_name, ip_version, subnet_ip,
subnet_prefix, gateway_ip, dhcp_enabled, callback):
"""
Create a subnet
"""
cmd_id = _network_plugin.invoke_plugin('create_subnet', network_uuid,
subnet_name, ip_ver... | 383a0ffeb6e364f761c8d4038bf8e53f367021c1 | 3,649,638 |
def convertCRS(powerplants, substations, towers, crs, grid):
"""
:param powerplants:
:param substations:
:param towers:
:param crs:
:return:
"""
substations.to_crs(crs)
# powerplants = powerplants.set_crs(crs)
# powerplants = powerplants.to_crs(crs)
# print(powerplants.crs)
... | 9fcb8c51323c00935ba2c882502a273f2bf532ff | 3,649,639 |
def get_pathway(page_name, end_pg, max_len, trail, paths):
"""
Finds a list of all paths from a starting wikipedia page to an end page
Assumes page_name is a valid wikipedia article title and end_pg is a valid
Wikipedia Page Object
Args:
page_name: (Str) The name of the current article... | 3b8effcb1f5295a854d32cc6438093f5ba7c1fa4 | 3,649,640 |
def clip_to_ndc(point_clip_space, name="clip_to_ndc"):
"""Transforms points from clip to normalized device coordinates (ndc).
Note:
In the following, A1 to An are optional batch dimensions.
Args:
point_clip_space: A tensor of shape `[A1, ..., An, 4]`, where the last
dimension represents points in ... | ee49d891da941b6da48797035c5b976f5d10762d | 3,649,641 |
def korrektur(wordfile, datei):
"""Patch aus korrigierten Einträgen"""
if not datei:
datei = 'korrektur.todo'
teste_datei(datei)
korrekturen = {}
for line in open(datei, 'r'):
if line.startswith('#'):
continue
# Dekodieren, Zeilenende entfernen
line = li... | 31b37d0787738d3424d8daacc4af945e883aeb9d | 3,649,642 |
def read_number(dtype, prompt='', floor=None, ceil=None, repeat=False):
""" Reads a number within specified bounds. """
while True:
try:
result = dtype(input(prompt))
if floor is not None and result < floor:
raise ValueError(f'Number must be no less than... | a528b1f5912ba4bab0b87c87004311778eaa8187 | 3,649,643 |
from typing import Optional
def dem_adjust(
da_elevtn: xr.DataArray,
da_flwdir: xr.DataArray,
da_rivmsk: Optional[xr.DataArray] = None,
flwdir: Optional[pyflwdir.FlwdirRaster] = None,
connectivity: int = 4,
river_d8: bool = False,
logger=logger,
) -> xr.DataArray:
"""Returns hydrologic... | d59f5bae1df44cc84c4eb98d8dd14ca923dc4809 | 3,649,644 |
from copy import copy
from numpy import zeros, unique
from itertools import product
def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'):
""" Train a message classification model """
pred = zeros(len(obs))
fullpred = zeros((len(obs),len(unique(obs))))
model = copy(bestMode... | fdf60d23894bfd997cdf7fa82cb59257ad7b2954 | 3,649,645 |
def vm_deploy(vm, force_stop=False):
"""
Internal API call used for finishing VM deploy;
Actually cleaning the json and starting the VM.
"""
if force_stop: # VM is running without OS -> stop
cmd = 'vmadm stop %s -F >/dev/null 2>/dev/null; vmadm get %s 2>/dev/null' % (vm.uuid, vm.uuid)
e... | 324dffa2a181d4b796a8f263eeb57d1452826c78 | 3,649,646 |
import sys
def get_cpuinfo():
"""Returns the flags of the processor."""
if sys.platform == 'darwin':
return platforms.osx.get_cpuinfo()
if sys.platform == 'win32':
return platforms.win.get_cpuinfo()
if sys.platform == 'linux2':
return platforms.linux.get_cpuinfo()
return {} | 2ac223337d54426d36c9fda8d88f3545c6d4c30a | 3,649,647 |
from datetime import datetime
def previous_analytics(request, package, id):
"""
Return a list of previous analytics for the given package.
Only shows analytics which the user can access.
Also limits to the last 100 of them!
"""
context = []
profile = request.user.get_profile()
... | 9722cd424de89cfe8e189b425fe2db64cb1e129b | 3,649,648 |
def get_monitor_value(image, monitor_key):
"""Return the monitor value from an image using an header key.
:param fabio.fabioimage.FabioImage image: Image containing the header
:param str monitor_key: Key containing the monitor
:return: returns the monitor else returns 1.0
:rtype: float
"""
... | cf74ab608837b6f5732a70d997afa1fe424b2ee1 | 3,649,649 |
import os
def resources(request):
"""
Page for accessing RMG resources, including papers and presentations
"""
folder = os.path.join(settings.STATIC_ROOT, 'presentations')
files = []
if os.path.isdir(folder):
files = os.listdir(folder)
toRemove = []
for f in files:
... | 857d4a89571da2270ca072965c64840f0a022268 | 3,649,650 |
def default_thread_index (value, threads):
"""
find index in threads array value
:param value:
:param threads:
:return:
"""
value_index = threads.index(value)
return value_index | 7be2efb6579f2880f53dac11705ba6a068c2d92d | 3,649,651 |
import requests
def new_things(url):
"""Attempts to register new things on the directory
Takes 1 argument:
url - URL containing thing descriptions to register
"""
response = requests.post('{}/things/register_url'.format(settings.THING_DIRECTORY_HOST), headers={
'Authorization': settin... | 0336d094e9581f3382dd33ac8a9bf8fd43754d82 | 3,649,652 |
def isID(value):
"""Checks if value looks like a Ulysses ID; i.e. is 22 char long.
Not an exact science; but good enougth to prevent most mistakes.
"""
return len(value) == 22 | 527db9446adc2b88c2117bd35c74474c3e7bad24 | 3,649,653 |
def tool_on_path(tool: str) -> str:
"""
Helper function to determine if a given tool is on the user's PATH variable. Wraps around
runspv.tool_on_path().
:param tool: the tool's filename to look for.
:return: the path of the tool, else ToolNotOnPathError if the tool isn't on the PATH.
"""
ret... | 52963a818bcea59eaaec1d20000d3a4a1296ee26 | 3,649,654 |
def DefineDecode(i, n, invert=False):
"""
Decode the n-bit number i.
@return: 1 if the n-bit input equals i
"""
class _Decode(Circuit):
name = 'Decode_{}_{}'.format(i, n)
IO = ['I', In(Bits[ n ]), 'O', Out(Bit)]
@classmethod
def definition(io):
if n <= ... | 9be19b191a1048dffd8a6fe82caabdcb1dd33f42 | 3,649,655 |
def absent(name, database, **client_args):
"""
Ensure that given continuous query is absent.
name
Name of the continuous query to remove.
database
Name of the database that the continuous query was defined on.
"""
ret = {
"name": name,
"changes": {},
"re... | f280dad71275cd576edbefac9376463a2ab91fc7 | 3,649,656 |
def get_ads(client, customer_id, new_ad_resource_names):
"""Retrieves a google.ads.google_ads.v4.types.AdGroupAd instance.
Args:
client: A google.ads.google_ads.client.GoogleAdsClient instanc e.
customer_id: (str) Customer ID associated with the account.
new_ad_resource_names: (str) Re... | 3e1bc99901490c53c66418a63238cf76de282896 | 3,649,657 |
def corrfact_vapor_rosolem(h, h_ref=None, const=0.0054):
"""Correction factor for vapor correction from absolute humidity (g/m3).
The equation was suggested by Rosolem et al. (2013).
If no reference value for absolute humidity ``h_ref`` is provided,
the average value will be used.
Parameters
... | 6add20bf118e85e77f245776101169efb9ba4eac | 3,649,658 |
def sine_ease_out(p):
"""Modeled after quarter-cycle of sine wave (different phase)"""
return sin(p * tau) | 58a78ad44e04df42f0533b6a94e51d04398407a9 | 3,649,659 |
def _extract_codes_from_element_text(dataset, parent_el_xpath, condition=None): # pylint: disable=invalid-name
"""Extract codes for checking from a Dataset. The codes are being extracted from element text.
Args:
dataset (iati.data.Dataset): The Dataset to check Codelist values within.
parent_e... | 45e4ec2a61dc38066ad9a71d41e63a48c6ccde23 | 3,649,660 |
def rotate_im(img, angle, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None):
"""Rotate the image.
Rotate the image such that the rotated image is enclosed inside the tightest
rectangle. The area not occupied by the pixels of the original image is colored
black.
Parame... | 40ab5d9761bdb2044fe99af4d5a51187edd34327 | 3,649,661 |
def list_modules(curdir=CURDIR, pattern=MOD_FILENAME_RE):
"""List names from {ok,ng}*.py.
"""
return sorted(
m.name.replace('.py', '')
for m in curdir.glob('*.py') if pattern.match(m.name)
) | 249b276ec5f42534a4ad162c02110bcf1f9cadf0 | 3,649,662 |
def encode_set_validator_config_and_reconfigure_script(
validator_account: AccountAddress,
consensus_pubkey: bytes,
validator_network_addresses: bytes,
fullnode_network_addresses: bytes,
) -> Script:
"""# Summary
Updates a validator's configuration, and triggers a reconfiguration of the system t... | 8b5e5d259750eecf3cea78e9abba82300baa2626 | 3,649,663 |
def _do_ecf_reference_data_import(
import_method,
widget,
logwidget=None,
specification_items=None,
ecfdate=None,
datecontrol=None,
):
"""Import a new ECF club file.
widget - the manager object for the ecf data import tab
"""
ecffile = widget.datagrid.get_data_source().dbhome
... | 593b1ac77688c92c9fcd3ea8fafb3f5089849293 | 3,649,664 |
import ast
import inspect
def ast_operators(node):
"""Return a set of all operators and calls in the given AST, or return an error if any are invalid."""
if isinstance(node, (ast.Name, ast.Constant)):
return set()
elif isinstance(node, ast.BinOp):
return {type(node.op)} | ast_operators(nod... | ce5c69e228fbab682cd41330a058b6f16b8d5d1a | 3,649,665 |
def calibrate_clock(out, tolerance=0.002, dcor=False):
"""\
currently for F2xx only:
recalculate the clock calibration values and write them to the flash.
"""
device = get_msp430_type() >> 8
variables = {}
if device == 0xf2:
# first read the segment form the device, so that only the ... | 6ad9940a0b43aff54317ff0b054a5a8e84fa5f73 | 3,649,666 |
def get_rejection_listings(username):
"""
Get Rejection Listings for a user
Args:
username (str): username for user
"""
activities = models.ListingActivity.objects.for_user(username).filter(
action=models.ListingActivity.REJECTED)
return activities | 47f7078f193de651f282d1823900cd876bf9fd93 | 3,649,667 |
def quadratic_weighted_kappa(y_true, y_pred):
"""
QWK (Quadratic Weighted Kappa) Score
Args:
y_true:
target array.
y_pred:
predict array. must be a discrete format.
Returns:
QWK score
"""
return cohen_kappa_score(y_true, y_pred, weights='quadrati... | fe3208d58cfbed7fdc51ee6069bb4d72584ea6d7 | 3,649,668 |
def statistika():
"""Posodobi podatke in preusmeri na statistika.html"""
check_user_id()
data_manager.load_data_from_file()
data_manager.data_for_stats()
return bottle.template("statistika.html", data_manager=data_manager) | afc72610e4ca245089b131d06dfb5ed8a172615c | 3,649,669 |
def decrement(x):
"""Given a number x, returns x - 1 unless that would be less than
zero, in which case returns 0."""
x -= 1
if x < 0:
return 0
else:
return x | 56b95324c147a163d3bdd0e9f65782095b0a4def | 3,649,670 |
def get_dagmaf(maf: msa.Maf) -> DAGMaf.DAGMaf:
"""Converts MAF to DagMaf.
Args:
maf: MAF to be converted.
Returns:
DagMaf built from the MAF.
"""
sorted_blocks = sort_mafblocks(maf.filecontent)
dagmafnodes = [
DAGMaf.DAGMafNode(block_id=b.id,
... | 40fd06a9429874f1ca7188f2ff185c4dd8b64e01 | 3,649,671 |
def optdat10(area,lpdva,ndvab,nglb):
"""Fornece dados para a otimizacao"""
# Tipo de funcao objetivo: tpobj==1 ---Peso
# tpobj==2 ---Energia
# tpobj==3 ---Máxima tensão
# tpobj==... | 064813cb2e66adfed6cb5e694614b88343a7613c | 3,649,672 |
def rotvec2quat(vec):
"""
A rotation vector is a 3 dimensional vector which is
co-directional to the axis of rotation and whose
norm gives the angle of rotation (in radians).
Args:
vec (list or np.ndarray): a rotational vector. Its norm
represents the angle of rotation.
Ret... | a19b7b67e9cd5877cc5045887d071e069892e0a6 | 3,649,673 |
def generate_pop(pop_size, length):
"""
初始化种群
:param pop_size: 种群容量
:param length: 编码长度
:return bin_population: 二进制编码种群
"""
decim_population = np.random.randint(0, 2**length-1, pop_size)
print(decim_population)
bin_population = [('{:0%sb}'%length).format(x) for x in decim_population]... | d1248fe59161d2a75eaf08ffe2b180537c2d1af5 | 3,649,674 |
import argparse
import sys
def prepare_argument_parser():
"""
Set up the argument parser for the different commands.
Return:
Configured ArgumentParser object.
"""
argument_parser = argparse.ArgumentParser(
description='Build source code libraries from modules.')
argument_parser.ad... | e57c3609ff54139dbb42ce95795f43acba9b3d25 | 3,649,675 |
def CountClusterSizes(clusterLabels):
""" This function takes the labels produced by spectral clustering (or
other clustering algorithm) and counts the members in each cluster.
This is primarily to see the distribution of cluster sizes over all
windows, particularly to see if there singlet... | 25bf78a83e55b72c7a33546450655efe7ee84874 | 3,649,676 |
def solver_problem1(digits_list):
"""input digits and return numbers that 1, 4, 7, 8 occurs"""
cnt = 0
for digits in digits_list:
for d in digits:
if len(d) in [2, 3, 4, 7]:
cnt += 1
return cnt | d1946d00d368ad498c9bb0a8562ec0ea76d26449 | 3,649,677 |
def spam_dotprods(rhoVecs, povms):
"""SPAM dot products (concatenates POVMS)"""
nEVecs = sum(len(povm) for povm in povms)
ret = _np.empty((len(rhoVecs), nEVecs), 'd')
for i, rhoVec in enumerate(rhoVecs):
j = 0
for povm in povms:
for EVec in povm.values():
ret[... | 95adc6ea8e1d33899a7dc96ba99589ef9bffb7fe | 3,649,678 |
import sys
def is_just_monitoring_error(unique_message):
"""
Return True if the unique_message is an intentional error just for
monitoring (meaning that it contains the one of the
JUST_MONITORING_ERROR_MARKERS somewhere in the exc_text)
"""
if sys.version_info == 2:
exc_text = unicode(... | d566174d8f7f46aad588594aded7e78ef3a91957 | 3,649,679 |
def get_chi_atom_indices():
"""Returns atom indices needed to compute chi angles for all residue types.
Returns:
A tensor of shape [residue_types=21, chis=4, atoms=4]. The residue types are
in the order specified in rc.restypes + unknown residue type
at the end. For chi angles which are not d... | 5ac6f2208e2819b8e0d04329cbfb94cb5dcd26ba | 3,649,680 |
def get_all_device_stats():
"""Obtain and return statistics for all attached devices."""
devices = get_devices()
stats = {}
for serial in devices:
model, device_stats = get_device_stats(serial)
if not stats.get(model):
stats[model] = {}
stats[model][serial] = device_stats
return stats | 9f2a50c4f6008120bc9527260f501f7e261dd19f | 3,649,681 |
def plot_coefs(coefficients, nclasses):
"""
Plot the coefficients for each label
coefficients: output from clf.coef_
nclasses: total number of possible classes
"""
scale = np.max(np.abs(coefficients))
p = plt.figure(figsize=(25, 5))
for i in range(nclasses):
p = plt.subplo... | 356c6c4bb96b08a370b8c492275e638b059594e2 | 3,649,682 |
import json
def infect():
"""Return a function that calls the infect endpoint on app."""
def inner(users, qs):
app.debug = True
with app.test_client() as client:
headers = {'Content-Type': 'application/json'}
data = json.dumps(users)
rv = client.post('/infec... | 3c6798b39b8545425d671c6ece8d0220c2630b5c | 3,649,683 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['description'] = """This plot shows the number of days with a high
temperature at or above a given threshold. You can optionally generate
this ... | 479d98e9ab19dcc03332c1a95ccc0624cdcfe24d | 3,649,684 |
def calc_cost_of_buying(count, price):
"""株を買うのに必要なコストと手数料を計算
"""
subtotal = int(count * price)
fee = calc_fee(subtotal)
return subtotal + fee, fee | 391909bbff35c6eb7d68c965e3f36317e4164b1a | 3,649,685 |
def add_units_to_query(df, udict=None):
"""
"""
for k, u in udict.items():
if k not in df.colnames:
continue
try:
df[k].unit
except Exception as e:
print(e)
setattr(df[k], 'unit', u)
else:
df[k] *= u / df[k].unit # ... | 984113ed8306d7734ac5351de347f331982c4251 | 3,649,686 |
import signal
def update_lr(it_lr, alg, test_losses, lr_info=None):
"""Update learning rate according to an algorithm."""
if lr_info is None:
lr_info = {}
if alg == 'seung':
threshold = 10
if 'change' not in lr_info.keys():
lr_info['change'] = 0
if lr_info['chan... | de6ef7d700a9c4b549b6d500f6737c84dc032c95 | 3,649,687 |
def ocr_page_image(
doc_path,
page_num,
lang,
**kwargs
):
"""
image = jpg, jpeg, png
On success returns ``mglib.path.PagePath`` instance.
"""
logger.debug("OCR image (jpeg, jpg, png) document")
page_path = PagePath(
document_path=doc_path,
page_num=page_num,
... | d1b87d4bdad967e40971eeb9e4b1e881781b87ad | 3,649,688 |
from functools import reduce
def factors(n):
"""
return set of divisors of a number
"""
step = 2 if n%2 else 1
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(sqrt(n))+1, step) if n % i == 0))) | 687608f5397181892aa338c96ee299f91d7b5431 | 3,649,689 |
import decimal
def round_decimal(x, digits=0):
"""This function returns the round up float.
Parameters
----------
x : a float
digits : decimal point
Returns
----------
Rounded up float
"""
x = decimal.Decimal(str(x))
if digits == 0:
return int(... | 8670fa1e9063376e012ebbc71df0a19c6205ea9c | 3,649,690 |
def basic_gn_stem(model, data, **kwargs):
"""Add a basic ResNet stem (using GN)"""
dim = 64
p = model.ConvGN(
data, 'conv1', 3, dim, 7, group_gn=get_group_gn(dim), pad=3, stride=2
)
p = model.Relu(p, p)
p = model.MaxPool(p, 'pool1', kernel=3, pad=1, stride=2)
return p, dim | 7cd1c1e0ff58431fc89acdec0f6c1d5f6fa9daa8 | 3,649,691 |
def log_scale(start,end,num):
"""Simple wrapper to generate list of numbers equally spaced in logspace
Parameters
----------
start: floar
Inital number
end: Float
Final number
num: Float
Number of number in the list
Returns
-------
list: 1d array
Lis... | 32d3976cb9cbcceb4cef9af15da373ea84e4d0c7 | 3,649,692 |
def measure_xtran_params(neutral_point, transformation):
"""
Description: Assume that the transformation from robot coord to camera coord is: RotX -> RotY -> RotZ -> Tranl
In this case: RotX = 180, RotY = 0; RotZ = -90; Tranl: unknown
But we know coords of a determined neutral ... | c2758158d545dbc6c2591f7f64f1df159a0c82db | 3,649,693 |
def getPrefix(routetbl, peer_logical):
""" FUNCTION TO GET THE PREFIX """
for route in routetbl:
if route.via == peer_logical:
return route.name
else:
pass | 2ca32a1fd63d6fcefbcc9ac23e8636c73e88455b | 3,649,694 |
def Logger_log(level, msg):
"""
Logger.log(level, msg)
logs a message to the log.
:param int level: the level to log at.
:param str msg: the message to log.
"""
return _roadrunner.Logger_log(level, msg) | af552b17aaeebef9713efffedcabd75946c961f1 | 3,649,695 |
import typing
def obj_test(**field_tests: typing.Callable[[typing.Any], bool]) -> typing.Callable[[typing.Any], bool]:
"""Return a lambda that tests for dict with string keys and a particular type for each key"""
def test(dat: typing.Any) -> bool:
type_test(dict)(dat)
dom_test = type_test(str... | 0439821b634807e178539b0444b69305c15e2e4e | 3,649,696 |
def hist2D(x, y, xbins, ybins, **kwargs):
""" Create a 2 dimensional pdf vias numpy histogram2d"""
H, xedg, yedg = np.histogram2d(x=x, y=y, bins=[xbins,ybins], density=True, **kwargs)
xcen = (xedg[:-1] + xedg[1:]) / 2
ycen = (yedg[:-1] + yedg[1:]) / 2
return xcen, ycen, H | 7f192f4db38e954aad96abc66fa4dc9c190acd82 | 3,649,697 |
def generate_ngram_dict(filename, tuple_length):
"""Generate a dict with ngrams as key following words as value
:param filename: Filename to read from.
:param tuple_length: The length of the ngram keys
:return: Dict of the form {ngram: [next_words], ... }
"""
def file_words(file_pointer):
... | 45f7eccae852e61f20044448955cade00174998c | 3,649,698 |
def get_end_point(centerline, offset=0):
"""
Get last point(s) of the centerline(s)
Args:
centerline (vtkPolyData): Centerline(s)
offset (int): Number of points from the end point to be selected
Returns:
centerline_end_point (vtkPoint): Point corresponding to end of centerline.... | f476e93b55bb046cfb6afb61a2e3ae37a172def3 | 3,649,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.