content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def print_insn_mnem(ea):
"""
Get instruction mnemonics
@param ea: linear address of instruction
@return: "" - no instruction at the specified location
@note: this function may not return exactly the same mnemonics
as you see on the screen.
"""
res = ida_ua.ua_mnem(ea)
if not res:... | 5,328,400 |
def setdim(P, dim=None):
"""
Adjust the dimensions of a polynomial.
Output the results into Poly object
Args:
P (Poly) : Input polynomial
dim (int) : The dimensions of the output polynomial. If omitted,
increase polynomial with one dimension. If the new dim is
... | 5,328,401 |
def extract_file_from_zip(zipfile, filename):
"""
Returns the compressed file `filename` from `zipfile`.
"""
raise NotImplementedError()
return None | 5,328,402 |
def reframe_box_masks_to_image_masks(box_masks, boxes, image_height,
image_width):
"""Transforms the box masks back to full image masks.
Embeds masks in bounding boxes of larger masks whose shapes correspond to
image shape.
Args:
box_masks: A tf.float32 tensor of size [n... | 5,328,403 |
def set_volume(entities: DottedDict, interface: InterfaceIO) -> None:
"""Set volume to a certain level."""
global _original_volume
new_volume = re.findall(r"\d+", entities.get("level", ""))
if not new_volume:
return
_spotify.set_volume(new_volume[0])
_original_volume = new_volume[0] | 5,328,404 |
def multi_classes_nms(cls_scores, box_preds, nms_config, score_thresh=None):
"""
Args:
cls_scores: (N, num_class)
box_preds: (N, 7 + C)
nms_config:
score_thresh:
Returns:
"""
pred_scores, pred_labels, pred_boxes = [], [], []
for k in range(cls_scores.shape[1]):
... | 5,328,405 |
def _register_resolver() -> None:
"""Registers the cirq module's public classes for JSON serialization."""
from cirq.protocols.json_serialization import _internal_register_resolver
from cirq.json_resolver_cache import _class_resolver_dictionary
_internal_register_resolver(_class_resolver_dictionary) | 5,328,406 |
def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self... | 5,328,407 |
def fit(causal_model: ProbabilisticCausalModel, data: pd.DataFrame):
"""Learns generative causal models of nodes in the causal graph from data.
:param causal_model: The causal model containing the mechanisms that will be fitted.
:param data: Observations of nodes in the causal model.
"""
progress_b... | 5,328,408 |
def test_create_and_delete_my_bucket(make_stubber, make_unique_name, region, keep):
"""Test that running the demo with various AWS Regions and arguments works as
expected."""
stubber = make_stubber(demo_bucket_basics, 'get_s3', region)
s3 = demo_bucket_basics.get_s3(region)
bucket_name = make_unique... | 5,328,409 |
def run(problem, **kwargs):
"""
A single run with a specific set of performance parameters.
"""
setup = model_type[problem]['setup']
options = {}
time_order = kwargs.pop('time_order')[0]
space_order = kwargs.pop('space_order')[0]
autotune = kwargs.pop('autotune')
block_shapes = as_t... | 5,328,410 |
async def test_snips_say(hass):
"""Test snips say with invalid config."""
calls = async_mock_service(hass, "snips", "say", snips.SERVICE_SCHEMA_SAY)
data = {"text": "Hello"}
await hass.services.async_call("snips", "say", data)
await hass.async_block_till_done()
assert len(calls) == 1
assert... | 5,328,411 |
async def create_or_update(
hub,
ctx,
name,
resource_group,
prefix_length,
sku="standard",
public_ip_address_version="IPv4",
zones=None,
**kwargs,
):
"""
.. versionadded:: 4.0.0
Creates or updates a static or dynamic public IP prefix.
:param name: The name of the pu... | 5,328,412 |
def _get_job_name(job_label: str = None) -> str:
"""Returns Beam runner job name.
Args:
job_label: A user defined string that helps define the job.
Returns:
A job name compatible with apache beam runners, including a time stamp to
insure uniqueness.
"""
job_name = 'tfrecorder-' + common.get_t... | 5,328,413 |
def process_provinces(data: Mapping[str, Union[str, int]]) -> List:
"""Returns list of all provinces from data file
Args:
data (Mapping): A dictionary of province data
"""
for province in data:
yield [province.get('code'), province.get('name')] | 5,328,414 |
def init_json():
""" Initialize two JSON files to store results """
with open("./reachable.json","w") as f:
json.dump({},f)
with open("unreachable.json","w") as f:
json.dump({},f) | 5,328,415 |
def all_not_none(*args):
"""Shorthand function for ``all(x is not None for x in args)``. Returns
True if all `*args` are not None, otherwise False."""
return all(x is not None for x in args) | 5,328,416 |
def weighted_photon_spec(eng):
""" Returns the weighted photon spectrum from positronium annihilation.
This assumes 3/4 ortho- and 1/4 para-, normalized to a single
annihilation.
Parameters
----------
eng : ndarray
The energy abscissa.
Returns
-------
Spectrum
T... | 5,328,417 |
def get_for_tag(app_name):
"""
Retorna a tag for customizada para listar registros no template list.html
:param app_name: Nome do app que está sendo criado
:type app_name: str
"""
return "{% for " + app_name + " in " + app_name + "s %}" | 5,328,418 |
def perform_log(tc, args={}):
"""Collects all counters and tracks them"""
opt_print = args.get('print', False)
properties = get_properties()
if print:
print(properties)
cpu = get_cpu_counters(args)
if len(cpu) > 0:
track_dict_as_metric(tc, cpu, properties=properties)
if... | 5,328,419 |
def print_names(pair):
""""Print pair names
Args:
pair: is a tuple containing the players that match user input
Return: None
prints each pair match to screen in the order
the small player on the left and the tall on the right
"""
player1, player2 = pair
p1 = play... | 5,328,420 |
def _reloadFn(*args):
"""Placeholder callback function for :func:`_handleSIGHUP`."""
return True | 5,328,421 |
def interpolation_lagrange_matrix(old_grid, new_grid):
"""
Evaluate lagrange matrix to interpolate state and control values from the solved grid onto the new grid.
Parameters
----------
old_grid : <GridData>
GridData object representing the grid on which the problem has been solved.
new... | 5,328,422 |
def bfs_paths(graph, start, end):
"""
return shortest path from start to end in graph
"""
# queue is list of tuples containing (vertex, path)
assert start in graph.keys()
assert end in graph.keys()
queue = [(start, [start])]
while queue:
vertex, path = queue.pop(0)
for n... | 5,328,423 |
def test_calculate_source_not_string(source):
"""
GIVEN source
WHEN calculate is called with the source
THEN InvalidInputError is raised.
"""
with pytest.raises(errors.InvalidInputError):
calculate(source) | 5,328,424 |
def optimize_shim(coils, unshimmed, mask, mask_origin=(0, 0, 0), bounds=None):
"""
Optimize unshimmed volume by varying current to each channel
Args:
coils (numpy.ndarray): X, Y, Z, N coil map
unshimmed (numpy.ndarray): 3D B0 map
mask (numpy.ndarray): 3D inte... | 5,328,425 |
def _log(x1):
"""closure of log for zero arguments, sign-protected"""
with np.errstate(divide="ignore", invalid="ignore"):
x1 = np.where(np.abs(x1) > 0.001, x1, 1)
return np.where(x1 < -1, np.log(np.abs(x1)) * np.sign(x1), np.log(np.abs(x1))) | 5,328,426 |
def whats_the_meaning_of_life(n_cores=23):
"""Answers the question about the meaning of life.
You don't even have to ask the question, it will figure it out for you.
Don't use more cores than available to mankind.
Parameters
----------
n_cores: int [default: 23]
The number of CPU cores... | 5,328,427 |
def get_good_start(system, numdistricts):
"""
Basically, instead of starting with a really bad initial solution for
simulated annealing sometimes we can rig it to start with a decent one...
"""
print('Acquiring a good initial solution')
solution = Solution(system, numdistricts)
solution.gene... | 5,328,428 |
def test_cav():
"""Test module cav.py by downloading
cav.csv and testing shape of
extracted data has 138 rows and 2 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = cav(test_path)
try:
assert x_train.shape == (138, 2)
except:
shutil.rmtree(test_path)
raise() | 5,328,429 |
def test_valid_version():
"""Check that the package defines a valid ``__version__``."""
v_curr = parse_version(pypkg_gh_releases_01.__version__)
v_orig = parse_version("0.1.0-dev")
assert v_curr >= v_orig | 5,328,430 |
def search_up(word_list, matrix):
"""Search words from word_list in matrix, up direction
:param word_list - list of strings
:param matrix - list of lists
:return list of lists"""
return straight_search(word_list, matrix, True, False) | 5,328,431 |
def int_validator(inp, ifallowed):
"""
Test whether only (positive) integers are being keyed into a widget.
Call signature: %S %P
"""
if len(ifallowed) > 10:
return False
try:
return int(inp) >= 0
except ValueError:
return False
return True | 5,328,432 |
def _check_config_aurora(configuration):
"""
Internal function to check configuration of an aurora
"""
if "serial port" not in configuration:
configuration.update({"serial port": -1})
if "number of ports to probe" not in configuration:
configuration.update({"ports to probe" : 20}) | 5,328,433 |
def clear():
"""
Clears the console platform-specific.
"""
p = platform.system()
if p == 'Windows':
subprocess.call('cls', shell=False)
elif p in ['Linux', 'Darwin']:
subprocess.call('clear', shell=False) | 5,328,434 |
def delete_site_files(site):
"""Deletes all site content and configuration files."""
files = ["/etc/nginx/director.d/{}.conf", "/etc/php/7.0/fpm/pool.d/{}.conf", "/etc/supervisor/director.d/{}.conf"]
files = [x.format(site.name) for x in files]
for f in files:
if os.path.isfile(f):
t... | 5,328,435 |
def scrape_page(url):
"""
scrape page by url and return its html
:param url: page url
:return: html of page
"""
logging.info('scraping %s...', url)
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
logging.error('get in... | 5,328,436 |
def getProductionUrl(code,d0):
"""Get the url for outage data from d0 to d1."""
url = getUrl('png',code,2018,opts=[[None]])
url = url.replace('__datehere__',eomf.m2s(d0),)
return url | 5,328,437 |
def has_gaps_in_region(read, region):
"""
Returns True if the given pysam read spans the given pybedtools.Interval,
``region``.
"""
# If the given read has gaps in its alignment to the reference inside the
# given interval (more than one block inside the SV event itself), there are
# gaps in... | 5,328,438 |
def zha_device_joined(opp, setup_zha):
"""Return a newly joined ZHA device."""
async def _zha_device(zigpy_dev):
await setup_zha()
zha_gateway = get_zha_gateway(opp)
await zha_gateway.async_device_initialized(zigpy_dev)
await opp.async_block_till_done()
return zha_gatewa... | 5,328,439 |
async def unlock_perm(message: Message):
""" unlock chat permissions from tg group """
unlock_type = message.input_str
chat_id = message.chat.id
if not unlock_type:
await message.err(r"I Can't Unlock Nothing! (-‸ლ)")
return
if unlock_type == "all":
try:
await mess... | 5,328,440 |
def test_logical_operators():
"""Logical operators
@see: https://www.w3schools.com/python/python_operators.asp
Logical operators are used to combine boolean values.
"""
# Let's work with these numbers to illustrate logic operators.
first_number = 5
second_number = 10
# and
# Retu... | 5,328,441 |
def get_all_list_data(request_context, function, *args, **kwargs):
"""
Make a function request with args and kwargs and iterate over the "next" responses until exhausted.
Return initial response json data or all json data as a single list. Responses that have a series of
next responses (as retrieved by... | 5,328,442 |
def bdd_common_after_all(context_or_world):
"""Common after all method in behave or lettuce
:param context_or_world: behave context or lettuce world
"""
# Close drivers
DriverWrappersPool.close_drivers(scope='session', test_name='multiple_tests',
test_passed=con... | 5,328,443 |
def test_primitive_error(source, location):
"""
GIVEN source and location
WHEN primitive is called with the source and location
THEN InvalidJsonError is raised.
"""
with pytest.raises(InvalidJsonError):
primitive(source=source, current_location=location) | 5,328,444 |
def is_outlier(x, check_finite=False, confidence=3):
"""Boolean mask with outliers
:param x: vector
:param check_finite:
:param confidence: confidence level: 1, 2, 3 or 4, which correspond to
90%, 95%, 99% and 99.9% two-tailed confidence respectively (normal
distribution). Default: 3 (9... | 5,328,445 |
def stateless_shuffle(value, seed):
"""Randomly shuffles a tensor, statelessly."""
flat_value = tf.reshape(value, [-1])
indices = tf.argsort(
tf.random.stateless_uniform(tf.shape(flat_value), seed=seed))
flat_shuffle = tf.gather(flat_value, indices)
return tf.reshape(flat_shuffle, tf.shape(v... | 5,328,446 |
def is_one_line_function_declaration_line(line: str) -> bool: # pylint:disable=invalid-name
"""
Check if line contains function declaration.
"""
return 'def ' in line and '(' in line and '):' in line or ') ->' in line | 5,328,447 |
def check_if_ended(id):
"""
Check if the course has already ended.
:param id: Id of the course that needs to be checked.
:type id: int
:return: If a course has ended
:rtype: bool
"""
course = moodle_api.get_course_by_id_field(id)
end_date = course['courses'][0]['enddate']
if(dt... | 5,328,448 |
def get_all_applications(user, timeslot):
"""
Get a users applications for this timeslot
:param user: user to get applications for
:param timeslot: timeslot to get the applications.
:return:
"""
return user.applications.filter(Proposal__TimeSlot=timeslot) | 5,328,449 |
def get_console_url(args):
""" Get a console login URL """
# Get credentials, maybe assume the role
session_creds = get_credentials(args)
# build the token request and fetch the sign-in token
url = request_signin_token(args, session_creds)
r = requests.get(url,timeout=200.0)
if r.sta... | 5,328,450 |
def get_uq_samples(config, campaign_dir, number_of_samples, skip=0):
"""
Copies UQ ensemble results from the local FabSim directory to the local
EasyVVUQ work directory. Does not fetch the results from the (remote)
host. For this, use the fetch_results() subroutine.
Parameters
----------
co... | 5,328,451 |
def test_factorise_numbers():
"""Only natural numbers > 1 are taken into process."""
assert factorise(2) == {2: 1}
assert factorise(3) == {3: 1}
assert factorise(4) == {2: 2}
assert factorise(10) == {2: 1, 5: 1}
assert factorise(24) == {2: 3, 3: 1}
assert factorise(30) == {2: 1, 3: 1, 5: 1}
... | 5,328,452 |
async def test_abort_if_already_setup(hass):
"""Test we abort if component is already setup."""
MockConfigEntry(
domain=DOMAIN,
data=CONFIG_DATA,
).add_to_hass(hass)
with patch(
"homeassistant.components.asuswrt.config_flow.socket.gethostbyname",
return_value=IP_ADDRESS,... | 5,328,453 |
def store_to_db(timezone, config, data, auth_code):
"""Stores the data in the backend database with a HTTP POST request."""
if data == {}:
logging.error('Received no data, stopping')
return
data['timestamp'] = get_timestamp(timezone)
data = OrderedDict(sorted(data.items()))
resp = r... | 5,328,454 |
def input_layer_from_space(space):
"""
create tensorlayer input layers from env.space input
:param space: env.space
:return: tensorlayer input layer
"""
if isinstance(space, Box):
return input_layer(space.shape)
elif isinstance(space, Discrete):
return tl.layers.Input(dtype=t... | 5,328,455 |
async def test_invalid_host(hass):
"""Test the failure when invalid host provided."""
client = ClientMock()
client.is_offline = True
with patch("twinkly_client.TwinklyClient", return_value=client):
result = await hass.config_entries.flow.async_init(
TWINKLY_DOMAIN, context={"source":... | 5,328,456 |
def searchable_paths(env_vars=PATH_VARS):
"""
Return a list of directories where to search "in the PATH" in the provided
``env_vars`` list of PATH-like environment variables.
"""
dirs = []
for env_var in env_vars:
value = os.environ.get(env_var, '') or ''
dirs.extend(value.split(... | 5,328,457 |
def _init_app():
""" Intializes the dash app."""
this_dir = os.path.dirname(os.path.abspath(__file__))
css_file = os.path.join(this_dir, "stylesheet.css")
app = dash.Dash(
__name__,
external_stylesheets=[css_file],
suppress_callback_exceptions=True,
)
return app | 5,328,458 |
def test_get_jobs_status(
globals, urls, client, mock_test_responses, context_fixture):
"""Context shows jobs status in dataframe with specific status."""
context = context_fixture('Healthy')
mock_test_responses(task='upload', status=CoreStatus.DONE)
responses.add(
responses.GET, urls('... | 5,328,459 |
def get_application_registry():
"""Return the application registry. If :func:`set_application_registry` was never
invoked, return a registry built using :file:`defaults_en.txt` embedded in the pint
package.
:param registry: a UnitRegistry instance.
"""
return _APP_REGISTRY | 5,328,460 |
def get_dataset(cfg, designation):
"""
Return a Dataset for the given designation ('train', 'valid', 'test').
"""
dataset = importlib.import_module('.' + cfg['dataset'], __package__)
return dataset.create(cfg, designation) | 5,328,461 |
def invite(email, inviter, user=None, sendfn=send_invite, resend=True,
**kwargs):
"""
Invite a given email address.
Returns a ``(User, sent)`` tuple similar to the Django
:meth:`django.db.models.Manager.get_or_create` method.
If a user is passed in, reinvite the user. For projects that... | 5,328,462 |
def RestrictDictValues( aDict, restrictSet ):
"""Return a dict which has the mappings from the original dict only for values in the given set"""
return dict( item for item in aDict.items() if item[1] in restrictSet ) | 5,328,463 |
def pump_impact(request):
"""
Ajax controller that prepares and submits the new pump impact jobs and workflow.
"""
session = None
try:
session_id = request.session.session_key
resource_id = request.POST.get('resource_id')
pumps = request.POST.get('data')
tool = reque... | 5,328,464 |
def classify_images(images_dir, petlabel_dic, model):
"""
Creates classifier labels with classifier function, compares labels, and
creates a dictionary containing both labels and comparison of them to be
returned.
PLEASE NOTE: This function uses the classifier() function defined in
classifie... | 5,328,465 |
def create_redis_fixture(scope="function"):
"""Produce a Redis fixture.
Any number of fixture functions can be created. Under the hood they will all share the same
database server.
Args:
scope (str): The scope of the fixture can be specified by the user, defaults to "function".
Raises:
... | 5,328,466 |
def get_heroes(**kwargs):
"""
Get a list of hero identifiers
"""
return make_request("GetHeroes",
base="http://api.steampowered.com/IEconDOTA2_570/", **kwargs) | 5,328,467 |
def print_table(file_scores, global_scores, output_filename,
n_digits=2, table_format='simple'):
"""Pretty print scores as table.
Parameters
----------
file_to_scores : dict
Mapping from file ids in ``uem`` to ``Scores`` instances.
global_scores : Scores
Global scor... | 5,328,468 |
def gt_strategy(
pandera_dtype: Union[numpy_engine.DataType, pandas_engine.DataType],
strategy: Optional[SearchStrategy] = None,
*,
min_value: Union[int, float],
) -> SearchStrategy:
"""Strategy to generate values greater than a minimum value.
:param pandera_dtype: :class:`pandera.dtypes.DataTy... | 5,328,469 |
def get_smoker_status(observation):
"""Does `observation` represent a suvery response indicating that the patient is or was a smoker."""
try:
for coding in observation['valueCodeableConcept']['coding']:
if ('system' in coding and 'code' in coding and
coding['system'] == utils.SNOMED_SYSTEM and
... | 5,328,470 |
def model_input_data_api():
"""Returns records of the data used for the model."""
# Parse inputs
# Hours query parameter must be between 1 and API_MAX_HOURS.
hours = request.args.get('hours', default=24, type=int)
hours = min(hours, current_app.config['API_MAX_HOURS'])
hours = max(hours, 1)
... | 5,328,471 |
def GetIAP(args, messages, existing_iap_settings=None):
"""Returns IAP settings from arguments."""
if 'enabled' in args.iap and 'disabled' in args.iap:
raise exceptions.InvalidArgumentException(
'--iap', 'Must specify only one of [enabled] or [disabled]')
iap_settings = messages.BackendServiceIAP()
... | 5,328,472 |
def test_get_metric_one(client: LNMetricsClient) -> None:
"""Get the metrics from one node"""
response = client.get_nodes(network="bitcoin")
node = response[0]
last_update = datetime.fromtimestamp(node["last_update"])
first = last_update.replace(minute=0, second=0, microsecond=0) - timedelta(hours=4... | 5,328,473 |
def get_default_instance():
"""Return the default VLC.Instance.
"""
global _default_instance
if _default_instance is None:
_default_instance = Instance()
return _default_instance | 5,328,474 |
def __check_legacy_point_coordinates(updater: DocumentUpdater):
"""
Check if all array values in field has legacy geo point
coordinates type. Raise InconsistencyError if other arrays was found
:param updater:
:return:
"""
def by_path(ctx: ByPathContext):
fltr = {"$and": [
... | 5,328,475 |
def test_tabulation():
"""
To validate the scanner considers "\t" as a single character, but double space.
"""
s = "let\t:\n"
scan = Scanner(s)
for i, e in enumerate(scan):
if i < 3:
assert e == s[i]
assert scan.lineno == 0
assert scan.offset == i
... | 5,328,476 |
def rules_yq_toolchains(version = YQ_DEFAULT_VERSION):
"""Register yq binary that specified version for all platforms as toolchains."""
if not YQ_BINDIST.get(version):
fail("Binary distribution of yq {} is not available.".format(version))
for os, checksum in YQ_BINDIST.get(version).items():
... | 5,328,477 |
async def test_set_invalid_speed(hass, calls):
"""Test set invalid speed when fan has valid speed."""
await _register_components(hass)
# Turn on fan
await common.async_turn_on(hass, _TEST_FAN)
# Set fan's speed to high
await common.async_set_speed(hass, _TEST_FAN, SPEED_HIGH)
# verify
... | 5,328,478 |
def flatList(items):
"""Yield items from any nested iterable; see Reference."""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatList(x):
yield sub_x
else:
yield x | 5,328,479 |
def dirty_multi_node_expand(node, precision, mem_map=None, fma=True):
""" Dirty expand node into Hi and Lo part, storing
already processed temporary values in mem_map """
mem_map = mem_map or {}
if node in mem_map:
return mem_map[node]
elif isinstance(node, Constant):
value = nod... | 5,328,480 |
def update_interface_device_hostname(apps, schema_editor):
"""Update all interfaces with hostname from associated device"""
Device = apps.get_model('nsot', 'Device')
for dev in Device.objects.iterator():
dev.interfaces.update(device_hostname=dev.hostname) | 5,328,481 |
def create_princess_df(spark_session) -> DataFrame:
"""Return a valid DF of disney princesses."""
princesses = [
{
"name": "Cinderella",
"age": 16,
"happy": False,
"items": {"weakness": "thorns", "created": "2020-10-14"},
},
{
"... | 5,328,482 |
def get_sheet_names(file_path):
"""
This function returns the first sheet name of the excel file
:param file_path:
:return:
"""
file_extension = Path(file_path).suffix
is_csv = True if file_extension.lower() == ".csv" else False
if is_csv:
return [Path(file_path).name]
xl = p... | 5,328,483 |
def build_config(ctx, params):
"""Load configuration, load modules and install dependencies.
This function loads the configuration and install all necessary
dependencies defined on a `requirements.txt` file inside the module.
If the flag `--verbose` is passed the logging level will be set as debug and
... | 5,328,484 |
def test_move_scss_010(temp_builds_dir):
"""
'Move' event on main sample
"""
basedir = temp_builds_dir.join('watcher_move_scss_010')
bdir, inspector, settings_object, watcher_opts = start_env(basedir)
build_scss_sample_structure(settings_object, basedir)
# Init handler
project_handler... | 5,328,485 |
async def test_advanced_option_flow(hass):
"""Test advanced config flow options."""
controller = await setup_unifi_integration(
hass, clients_response=CLIENTS, wlans_response=WLANS
)
result = await hass.config_entries.options.async_init(
controller.config_entry.entry_id, context={"show_... | 5,328,486 |
def count_votes(votation_id):
"""
Count number of different vote_key. Its pourpose is to compare with voters.
"""
n = db.session.query(Vote.vote_key).filter(Vote.votation_id == votation_id).distinct().count()
return n | 5,328,487 |
def test_ca1dmodel():
""" ConstantAcceleration Transition Model test """
state_vec = np.array([[3.0], [1.0], [0.1]])
noise_diff_coeffs = np.array([[0.01]])
base(state_vec, noise_diff_coeffs) | 5,328,488 |
def update_ammo(ammo_label):
""" Updates the label that keeps track of the ammunition """
ammo_label.set_text(f"{ammo[aim_mode]}/{full_ammo[aim_mode]}") | 5,328,489 |
def get_eng_cv_rate(low_prob):
"""Returns 'low' and 'high' probabilites for student to english I conversion
Simulated data for class enrollment.
Args:
low_prob(float): low end of probability
Returns: dict
"""
np.random.seed(123)
global eng_cv_rate_dict
eng_cv_rate_dict = {'low'... | 5,328,490 |
def dev_unify_nest(args: Type[MultiDev], kwargs: Type[MultiDev], dev, mode, axis=0, max_depth=1):
"""
Unify the input nested arguments, which consist of sub-arrays spread across arbitrary devices, to unified arrays
on the single target device.
:param args: The nested positional arguments to unify.
... | 5,328,491 |
def make_preprocessor(transforms=None, device_put=False):
"""
"""
# verify input
if transforms is not None:
if not isinstance(transforms, (list, tuple)):
transforms = (transforms)
for fn in transforms:
if not callable(fn):
raise ValueError("Each e... | 5,328,492 |
def validate_sintel(args, model, iters=50):
""" Evaluate trained model on Sintel(train) clean + final passes """
model.eval()
pad = 2
for dstype in ['clean', 'final']:
val_dataset = datasets.MpiSintel(args, do_augument=False, dstype=dstype)
epe_list = []
tv_list = []
... | 5,328,493 |
def timeRangeContainsRange(event1Start, event2Start, event1End, event2End):
"""
Returns true if one set of times starts and ends
within another set of times
@param event1Start: datetime
@param event2Start: datetime
@param event1End: datetime
@param event2End: datetime
@return: boolean
... | 5,328,494 |
def compute_confidence_intervals(x: np.array, z: float = 1.96) -> float:
"""
Function to compute the confidence interval of the mean of a sample.
Hazra, Avijit. "Using the confidence interval confidently." Journal of thoracic disease 9.10 (2017): 4125.
Formula:
CI = x̅ ± z × (std/√n)
wh... | 5,328,495 |
def _deinitialized( ):
"""
後始末
"""
camera = bpy.types.Camera
del camera.tilt_shift_vertical
del camera.tilt_shift_horizontal
del camera.temp_lens
del camera.temp_shift_x
del camera.temp_shift_y | 5,328,496 |
def SendCommands(cmds, key):
"""Send commands to the running instance of Editra
@param cmds: List of command strings
@param key: Server session authentication key
@return: bool
"""
if not len(cmds):
return
# Add the authentication key
cmds.insert(0, key)
# Append the messa... | 5,328,497 |
def setmanager(domain_name, user_name='manager'):
""" Make a user manager of a domain
"""
domain = models.Domain.query.get(domain_name)
manageruser = models.User.query.get(user_name + '@' + domain_name)
domain.managers.append(manageruser)
db.session.add(domain)
db.session.commit() | 5,328,498 |
def mock_legacy_venv(venv_name: str, metadata_version: Optional[str] = None) -> None:
"""Convert a venv installed with the most recent pipx to look like
one with a previous metadata version.
metadata_version=None refers to no metadata file (pipx pre-0.15.0.0)
"""
venv_dir = Path(constants.PIPX_LOCAL... | 5,328,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.