content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def train_on(text):
""" Return a dictionary whose keys are alle the tuple of len PREFIX
of consecutive words inside text, and whose value is the list of
every single word which follows that tuple inside the text. For ex:
{('Happy', 'birthday'): ['to', 'dear'] ...} """
words = text.split()
assert... | 40230bbb346cb4c98d6694fb0d18652e7d6bd4e7 | 3,652,550 |
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""learning_rate_decay: updates the learning rate using
inverse time decay in numpy
Args:
alpha : is the original learning rate
decay_rate : is the weight used to determine the
r... | a98f893acc7f14dafcf2dea551df4eb44da07bc4 | 3,652,551 |
def update_studio(request):
"""updates the studio
"""
studio_id = request.params.get('studio_id')
studio = Studio.query.filter_by(id=studio_id).first()
name = request.params.get('name', None)
dwh = request.params.get('dwh', None)
wh_mon_start = get_time(request, 'mon_start')
wh_mon_end... | 2fbdcbd04bb0ec7d0b2f5790e59e9211c831066f | 3,652,552 |
def flip_coin(num_of_experiments = 1000, num_of_flips = 30):
"""
Flip the coin `num_of_flips` times and repeat this experiment `num_of_experiments` times. And
return the number of heads grouped together in all the experiments.
"""
all_heads = []
for i in range(num_of_experiments):
heads ... | 24ccd52693233f93f5c0bb7bb4f09220e86f320c | 3,652,553 |
from pathlib import Path
def get_questions(
path: str,
uid2idx: dict = None,
path_data: Path = None,
) -> po.DataFrame:
"""
Identify correct answer text and filter out wrong distractors from question string
Get tokens and lemmas
Get explanation sentence ids and roles
"""
# Dropping questions without expla... | 877c75f20b7b766655ecda5dc4bc63ada7ee593c | 3,652,554 |
def simple_command(device, cmd_id, data=None, receive=True):
"""
Raises:
HIDException -> if reading/writing to the USB device failed:
KBProtocolException -> if the packet is too large
"""
cmd_packet = bytearray(EP_VENDOR_SIZE)
cmd_packet[0] = cmd_id
# Optional data component
if data... | 57a5e237f2296fec1563c125cb934ce1914d8bac | 3,652,555 |
def dbopen(dbname, perm = 'r'):
"""Open a Datascope database"""
return Dbptr(dbname, perm) | 08a083def4f792927232eff5d625ae4e6f3355fb | 3,652,556 |
def to_nx(dsk):
"""
Code mainly identical to dask.dot.to_graphviz and kept compatible.
"""
collapse_outputs = False
verbose = False
data_attributes = {}
function_attributes = {}
g = nx.DiGraph()
seen = set()
connected = set()
for k, v in dsk.items():
k_name = nam... | 140b6a74ce7e75ddbc906bc4b4c7330e7585e0d8 | 3,652,557 |
def predict(model, img_base64):
"""
Returns the prediction for a given image.
Params:
model: the neural network (classifier).
"""
return model.predict_disease(img_base64) | 545a98dd682b81a1662878f91091615871562226 | 3,652,558 |
import hashlib
def get_hash(x: str):
"""Generate a hash from a string."""
h = hashlib.md5(x.encode())
return h.hexdigest() | 538c936c29867bb934776333fb2dcc73c06e23d0 | 3,652,559 |
def pair_force(r1, r2, par1, par2, sigma_c, box, r_cut, lj=True, coulomb=True):
"""Compute the sum of the Lennard Jones force and the short ranged part
of the Coulomb force between two particles.
Arguments:
r1 (ndarray): A one dimensional numpy-array with d elements (position of... | 10c6eee7547f94c06e650a0a738aace3380de454 | 3,652,560 |
def delete_network_acl_entry(client, network_acl_id, num=100, egress=False, dry=True):
"""
Delete a network acl entry
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.delete_network_acl_entry
"""
try:
response = client.delete_network_acl_entry( E... | e27e476f2fe37e7e0150a97ebd4b5e3cb93e86b1 | 3,652,561 |
import time
def mp_run(data, process_num, func, *args):
""" run func with multi process
"""
level_start = time.time()
partn = max(len(data) / process_num, 1)
start = 0
p_idx = 0
ps = []
while start < len(data):
local_data = data[start:start + partn]
start += partn
... | 13576bb107eae5a49063bcba3d698eeb957dbb1e | 3,652,562 |
def spell(corpus):
"""
Train a Spelling Normalizer
Parameters
----------
corpus : list of strings. Prefer to feed with malaya.load_malay_dictionary().
Returns
-------
SPELL_NORMALIZE: Trained malaya.normalizer._SPELL_NORMALIZE class
"""
if not isinstance(corpus, list):
... | 1aee5a941e1553f50540a5327ee0e3c4d1ce0bd3 | 3,652,563 |
def client_id_to_org_type_id(client_id):
"""
Client ID should be a string: "g:" + self._options['org'] + ":" +
self._options['type'] + ":" + self._options['id'],
"""
split = client_id.split(':')
if len(split) != 4:
raise InvalidClientId()
org = split[1]
... | 475058962f81760dc65b19ddbdc1d74e0ec2f55e | 3,652,565 |
def get_total_implements():
"""Obtiene los implementos totales solicitados en prestamos."""
total_implements = 0
for i in Loans.objects.all():
total_implements += i.ammount_implements
return total_implements | 5b8e2b21f8c31e33c60518fd4fba20eded614f05 | 3,652,566 |
from typing import Optional
from typing import Union
def _parse_maybe_array(
type_name: str, innermost_type: Optional[Union[ast_nodes.ValueType,
ast_nodes.PointerType]]
) -> Union[ast_nodes.ValueType, ast_nodes.PointerType, ast_nodes.ArrayType]:
"""Internal-onl... | 8a284083e604688c2a1eff8767b6cb31b493cb07 | 3,652,567 |
def ema_decay_schedule(
base_rate: jnp.ndarray,
step: jnp.ndarray,
total_steps: jnp.ndarray,
use_schedule: bool,
) -> jnp.ndarray:
"""Anneals decay rate to 1 with cosine schedule."""
if not use_schedule:
return base_rate
multiplier = _cosine_decay(step, total_steps, 1.)
return 1. - (1. - bas... | a6269162e1a93544031b241ff43e043971bec488 | 3,652,568 |
from typing import Callable
def _kill_filter(mm: MergedMiningCoordinator, filter_fn: Callable[[MergedMiningStratumProtocol], bool]) -> int:
""" Kill all workers that the filter `fltr` returns true for.
"""
count = 0
for protocol in filter(filter_fn, mm.miner_protocols.values()):
count += 1
... | 8a73427e46a418bf1d3ba974f73992dce0f1ad8c | 3,652,569 |
def get_node_layer_sort_preference(device_role):
"""Layer priority selection function
Layer sort preference is designed as numeric value.
This function identifies it by LAYERS_SORT_ORDER
object position by default. With numeric values,
the logic may be improved without changes on NeXt app side.
... | 08fbdbcb272664498d3709ffc9f49dbb2042fef2 | 3,652,570 |
def is_anagram(s,t):
"""True if strings s and t are anagrams.
"""
# We can use sorted() on a string, which will give a list of characters
# == will then compare two lists of characters, now sorted.
return sorted(s)==sorted(t) | 2b615f8180bcaa598e24c0772893c9a528bc5153 | 3,652,571 |
def f1_score(labels, predict, name=None):
"""
Streaming f1 score.
"""
predictions = tf.floor(predict + 0.5)
with tf.variable_scope(name, 'f1', (labels, predictions)):
epsilon = 1e-7
_, tp = tf.metrics.true_positives(labels, predictions)
_, fn = tf.metrics.false_negatives(labe... | 243612cad4ca1a876ccfbccfe55fdeeed893d644 | 3,652,572 |
import requests
def test_notify_matrix_plugin_fetch(mock_post, mock_get):
"""
API: NotifyMatrix() Server Fetch/API Tests
"""
# Disable Throttling to speed testing
plugins.NotifyBase.request_rate_per_sec = 0
response_obj = {
'room_id': '!abc123:localhost',
'room_alias': '#abc1... | 27dde8766cdfd136104e647a5a97416a69982cb5 | 3,652,573 |
import copy
def site_summary_data(query, notime=True, extra="(1=1)"):
"""
Summary of jobs in different states for errors page to indicate if the errors caused by massive site failures or not
"""
summary = []
summaryResources = []
# remove jobstatus from the query
if 'jobstatus__in' in quer... | 010ca33e4de15c74199fbf54c565119f493698cc | 3,652,574 |
def Epsilon(u):
"""Vector symmetric gradient."""
return Sym(Grad(u.transpose())) | ed1d163ca031ada0d1645029690fa53c3d2acfa0 | 3,652,575 |
def at(seq, msg, cmd=None, *args, **kwargs):
"""Output the comwdg"""
return translator(seq)(*COMWDG_CMD)() | dd98234261731c3048444ab7d99ec6ed34eb62f1 | 3,652,576 |
def get_directory(f):
"""Get a directory in the form of a list of entries."""
entries = []
while 1:
line = f.readline()
if not line:
print '(Unexpected EOF from server)'
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] in CRLF:
... | fdd83e040f23f5ab84e0eb7cef457dfd66159f78 | 3,652,577 |
def get_worker_status(worker):
"""Retrieve worker status by worker ID from redis."""
set_redis_worker_status_pool()
global WORKER_STATUS_POOL
# retrieve worker status
r = StrictRedis(connection_pool=WORKER_STATUS_POOL)
res = r.get(WORKER_STATUS_KEY_TMPL % worker)
return res.decode() if has... | 886817f7995bc8259891b10699ec4d26587e0653 | 3,652,579 |
def lif_r_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):
"""Creates a nest glif_lif_r_psc object"""
coeffs = config['coeffs']
threshold_params = config['threshold_dynamics_method']['params']
reset_params = config['voltage_reset_method']['params']
params = {'V_th': coeffs['th_inf'] * confi... | 091e45f44f9c777dac6c2b35fd51459a7947e301 | 3,652,580 |
def get_bigwig_values(bigwig_path, chrom_name, chrom_end, chrom_start=0):
"""
Get the values for a genomic region of interest from a bigwig file.
:param bigwig_path: Path to the bigwig file
:param chrom_name: Chromosome name
:param chrom_end: chromosome end
:param chrom_start: chromosome start
... | 37fe5a40a5fde1ccaee7cac32d8b9beb68a65c51 | 3,652,581 |
def get_successors(state, maxwords):
"""Traverses state graph to find valid anagrams."""
terminal = len(state['chars']) == 0
# Check whether the state is invalid and should be pruned
if not is_valid(state['anagram'], terminal, maxwords):
return []
# If valid terminal state, stop search an... | 9c842edc378a781195ef41ed58c7952f216b642e | 3,652,583 |
def read_and_parse_cdl_file(file_name):
"""
Reads relevant information from a "cdl" file
"""
if file_name is None:
return None
wl_map = {}
bl_map = {}
colclk_wl_map = {}
# Parse line-by-line
with open(file_name, "r") as fp:
for line in fp:
line = line.... | e1bfbb75f473932861bb2e804dd0609c62544cf3 | 3,652,584 |
def detect_outlier_at_index(
srs: pd.Series,
idx: int,
n_samples: int,
z_score_threshold: float,
) -> bool:
"""
Check if a value at index `idx` in a series is an outlier.
The passed series is supposed to be ordered by increasing timestamps.
This function
- detects z-score window in... | 65a4d7e661f6cf4641d9cd82d1bb31c5e2d21616 | 3,652,585 |
def _organize_parameter(parameter):
"""
Convert operation parameter message to its dict format.
Args:
parameter (OperationParameter): Operation parameter message.
Returns:
dict, operation parameter.
"""
parameter_result = dict()
parameter_keys = [
'mapStr',
... | 8cbd7c863bb244e71266a573ba756647d0ba13ea | 3,652,586 |
def colorpicker(request):
"""
Controller for the app home page.
"""
my_param = MyParamColor()
context = get_context(request, my_param)
return render(request, 'tethys_django_form_tutorial/colorpicker.html', context) | 071f587683a24c101a7963a3934c989570c0fa66 | 3,652,587 |
def translate_date(default=defaults.get('language')):
"""Parse/translate a date."""
d = request.args.get('date')
if not d:
raise RuntimeError(_('Date is mandatory.'))
dest_lang = request.args.get('dest') if request.args.get('dest') else default
variation = request.args.get('variation') if r... | ada6f4416e227414dfc6f32fc3387c8b38830e70 | 3,652,588 |
from typing import Any
from typing import Union
from typing import Optional
def check_call(
*command: Any,
working_directory: Union[PathLike, str] = ".",
verbose: bool = False,
quoted: bool = False,
**kwargs: Any,
) -> Optional[str]:
"""Proxy for subprocess.check_call"""
return check_run(
... | 384cd78599355e694445a7c682613672bba374a1 | 3,652,589 |
from typing import Tuple
def fit_client(client: Client, weights: Weights) -> Tuple[Weights, int]:
"""Refine weights on a single client."""
return client.fit(weights) | db8e6003f452a5147274ac6e83df7d216ca46c91 | 3,652,590 |
def _find_rpms_in_packages(koji_api, name_list, major_minor):
"""
Given a list of package names, look up the RPMs that are built in them.
Of course, this is an inexact science to do generically; contents can
vary from build to build, and multiple packages could build the same RPM name.
We will first... | edfb55f0b6997d8f930c8d93c2ee1be1c111bcfc | 3,652,591 |
def calculate_algorithm_tags(analyses):
"""
Calculate the algorithm tags (eg. "ip", True) that should be applied to a sample document based on a list of its
associated analyses.
:param analyses: the analyses to calculate tags for
:type analyses: list
:return: algorithm tags to apply to the sam... | b2b13e3a0ccd21f446c5406baa966b2c0c4c6be9 | 3,652,592 |
import json
def open_json(filepath):
"""
Returns open .json file in python as a list.
:param: .json file path
:returns: list
:rvalue: str
"""
with open(filepath) as f:
notes = json.load(f)
return notes | a7cae15880ee1caaaf7bfa8c1aec98f5f83debe7 | 3,652,593 |
import json
def remove_user_list():
"""
Endpoint to remove a specific list or a complete user
---
tags:
- User Methods
parameters:
- name: user
type: string
in: query
required: true
description: user you want to qu... | b53660edd56fcf5bbe061331d5f2b8756f621dd8 | 3,652,594 |
import requests
def upload(f, content_type, token, api_key):
"""Upload a file with the given content type to Climate
This example supports files up to 5 MiB (5,242,880 bytes).
Returns The upload id if the upload is successful, False otherwise.
"""
uri = '{}/v4/uploads'.format(api_uri)
header... | d6ead1f029811ec5894848b71841fd008068cee0 | 3,652,595 |
def get_node_name_centres(nodeset: Nodeset, coordinates_field: Field, name_field: Field):
"""
Find mean locations of node coordinate with the same names.
:param nodeset: Zinc Nodeset or NodesetGroup to search.
:param coordinates_field: The coordinate field to evaluate.
:param name_field: The name fi... | 2dc1e670999d9491e52efce02e5d7ecd22b75226 | 3,652,596 |
from enum import Enum
def pred(a):
"""
pred :: a -> a
the predecessor of a value. For numeric types, pred subtracts 1.
"""
return Enum[a].pred(a) | 070bf20e7b7ecd694806e78bd705e872b2fd8464 | 3,652,597 |
def pascal_to_snake(pascal_string):
"""Return a snake_string for a given PascalString."""
camel_string = _pascal_to_camel(pascal_string)
snake_string = _camel_to_snake(camel_string)
return "".join(snake_string) | 69c54fd8600878af2a8d168659a781b8389419ce | 3,652,599 |
def collect_targets_from_attrs(rule_attrs, attrs):
"""Returns a list of targets from the given attributes."""
result = []
for attr_name in attrs:
_collect_target_from_attr(rule_attrs, attr_name, result)
return [target for target in result if is_valid_aspect_target(target)] | 6be1731049f6970004763f5e9ec7d0a3bde76189 | 3,652,600 |
from typing import Tuple
def extract_codes(text: str) -> Tuple[str, ...]:
"""Extract names of warnings from full warning text."""
match = CODES_PAT.search(text)
if not match:
raise ValueError("No warning code found")
return tuple(match.group(1).split(",")) | 6727049c195197ed2407f30093c362a2c6f35cd4 | 3,652,601 |
def task_list(request, pk):
"""
View to get task list based on user list for forms
"""
user_model = User.objects.filter(is_staff=False)
task_model = Task.objects.filter(user=pk)
user_detail = User.objects.get(pk=pk)
query = request.GET.get('q')
if query:
task_model = task_m... | dbb6545ca66a367b2b3e89a494ac8a9bbdbbb341 | 3,652,602 |
import json
def load_credentials():
"""
load_credentials
:return: dict
"""
with open("credentials.json", "r", encoding="UTF-8") as stream:
content = json.loads(stream.read())
return content | 2f08fc4e897a7c7eb91de804158ee67cd91635d0 | 3,652,603 |
def get_utm_string_from_sr(spatialreference):
"""
return utm zone string from spatial reference instance
"""
zone_number = spatialreference.GetUTMZone()
if zone_number > 0:
return str(zone_number) + 'N'
elif zone_number < 0:
return str(abs(zone_number)) + 'S'
else:
re... | 50f01758f7ee29f1b994d36cda34b6b36157fd9e | 3,652,604 |
def messages_count(name):
"""
Get message count for queue
curl -X GET -H 'Accept: application/json' http://localhost:8080/queues/C13470112/msgs/count
curl -X GET -H 'Accept: application/json' 83.212.127.232:8080/queues/C13470112/msgs/count
"""
conn = get_conn()
queue = conn.get_queue(name)
count = queue.count... | 86abcbc6a9bb81f0ce8a6a19941761c042f5a7e9 | 3,652,605 |
def return_intersect(cameraList):
"""
Calculates the intersection of the Camera objects in the *cameraList*.
Function returns an empty Camera if there exists no intersection.
Parameters:
cameraList : *list* of *camera.Camera* objects
A list of cameras from the camera.Camera class, e... | a47613b8d79c4a4535cd5e7e07aa3b26dea019a5 | 3,652,606 |
def import_measurements(task, subject, gsrn, session):
"""
Imports measurements for a single MeteringPoint, and starts a
start_submit_measurement_pipeline() pipeline for each of the newly
imported measurements.
:param celery.Task task:
:param str subject:
:param str gsrn:
:param sqlalch... | 6f0fc4aec546c5cf7b23bf2471ac625639e9dbbb | 3,652,609 |
import pandas
from typing import List
def add_agg_series_to_df(
df: pandas.DataFrame, grouped_levels: List[str], bottom_levels: List[str]
) -> pandas.DataFrame:
"""
Add aggregate series columns to wide dataframe.
Parameters
----------
df : pandas.DataFrame
Wide dataframe containing bo... | 7c3b7b526c394c8a24bf754365dbc809476b7336 | 3,652,610 |
def conv_relu_pool_forward(x, w, b, conv_param, pool_param):
"""
Convenience layer that performs a convolution, a ReLU, and a pool.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
- pool_param: Parameters for the pooling layer... | d9a32950d1b56b4843938b339c7233e7fc87c5cc | 3,652,611 |
def avg_pixelwise_var(images_seen: np.int16):
"""
Computes the variance for every pixel p across all images, resulting in a matrix holding
the variance for eack pixel p, then calculates the average of that variance across all
pixels. This allows us to compensate for different fov sizes.
Note: images... | 4b6196ddd25c0cd3ad0cd7cb1928b99772aa563f | 3,652,612 |
def get_r2_matrix(ts):
"""
Returns the matrix for the specified tree sequence. This is computed
via a straightforward Python algorithm.
"""
n = ts.get_sample_size()
m = ts.get_num_mutations()
A = np.zeros((m, m), dtype=float)
for t1 in ts.trees():
for sA in t1.sites():
... | e6a3eca421c40c9b9bbe218e7f6179eda0e07a00 | 3,652,613 |
def omdb_title(
api_key: str,
id_imdb: str = None,
media: str = None,
title: str = None,
season: int = None,
episode: int = None,
year: int = None,
plot: str = None,
cache: bool = True,
) -> dict:
"""
Looks up media by id using the Open Movie Database.
Online docs: http:... | 54efaba216b7de203fe6960f58a8ebb93b980c4c | 3,652,615 |
def get_status(addr):
"""Get the current status of a minecraft server.
addr -- server address
Returns an mcstatus object.
"""
server = MinecraftServer.lookup(addr)
try:
return server.status()
except Exception:
return None | 9e5a346d3cec803005ef0c65d24f929b56dfa68f | 3,652,616 |
def calculate_losses(estimator, input_fn, labels):
"""Get predictions and losses for samples.
The assumptions are 1) the loss is cross-entropy loss, and 2) user have
specified prediction mode to return predictions, e.g.,
when mode == tf.estimator.ModeKeys.PREDICT, the model function returns
tf.estimator.Esti... | 1a25519d661a6de185c39bb9c65a23a3eea71971 | 3,652,617 |
def text_cleaning(value, stopwords=None):
"""Applies the four cleaning funtions to a value.
Turns value into string, makes lowercase, strips trailing and leading spaces, and removes digits, punctuation, and stopwords
Args:
value (str): string to be cleaned
Returns:
str_out (s... | 291f4150601b7537cbb4d10cb53598dcb9a83829 | 3,652,618 |
def calc_pts_lag(npts=20):
"""
Returns Gauss-Laguerre quadrature points rescaled for line scan integration
Parameters
----------
npts : {15, 20, 25}, optional
The number of points to
Notes
-----
The scale is set internally as the best rescaling for a line scan
... | dc491bc8dd46f81809a0dc06da8c123357736622 | 3,652,619 |
def APPEND(*ext, **kw):
"""Decorator to call XDWAPI with trailing arguments *ext.
N.B. Decorated function must be of the same name as XDWAPI's one.
"""
def deco(api):
@wraps(api)
def func(*args, **kw):
args = list(args)
if "codepage" in kw:
args.a... | c73dc1b192835a0eefa53f660b1af4626a3ab75c | 3,652,620 |
def stations_within_radius(stations, centre, r):
"""Returns a list of all stations (type MonitoringStation) within radius r of a geographic coordinate x."""
stations_inside_radius = []
for station, distance in stations_by_distance(stations, centre):
# Check if distance is inside the requried radius... | 8182bdfc0d46ee64e98358c06b3d4787a0f1fa52 | 3,652,621 |
def manage_topseller(request, template_name="manage/marketing/topseller.html"):
"""
"""
inline = manage_topseller_inline(request, as_string=True)
# amount options
amount_options = []
for value in (10, 25, 50, 100):
amount_options.append({
"value": value,
"selecte... | e9af634b66a7f7631a0bb7633cc445f05efb615a | 3,652,622 |
from typing import Optional
def embedded_services(request: FixtureRequest) -> Optional[str]:
"""
Enable parametrization for the same cli option
"""
return getattr(request, 'param', None) or request.config.getoption('embedded_services', None) | 908a48d9fa8696e6970fe5884632f1b373063667 | 3,652,624 |
def vigenere(plaintext,cypher):
"""Implementation of vigenere cypher"""
i = 0
cyphertext = ""
for character in plaintext:
n = ord(cypher[i%len(cypher)].lower())-97
new_char = rot_char(character, n)
cyphertext += new_char
if new_char != ' ':
i += 1
ret... | 2b5cdd839bcfc0e55cdac65f9752cf88bd34c2e2 | 3,652,625 |
def get_local_unit_slip_vector_SS(strike, dip, rake):
"""
Compute the STRIKE SLIP components of a unit slip vector.
Args:
strike (float): Clockwise angle (deg) from north of the line at the
intersection of the rupture plane and the horizontal plane.
dip (float): Angle (degrees) ... | dddedaeaabe91137c38bbaa2ec2bb1d42a6629c7 | 3,652,626 |
def get_country_code(country_name):
"""Gets the code of the country given its name"""
for code, name in COUNTRIES.items():
if name == country_name:
return code | bb4a3eebae0b14fc8207ef4301812d3d305a8dfd | 3,652,627 |
def build_model(cfg, train_cfg=None, test_cfg=None):
"""Build model."""
if train_cfg is None and test_cfg is None:
return build(cfg, MODELS)
else:
return build(cfg, MODELS, dict(train_cfg=train_cfg, test_cfg=test_cfg)) | f47aa433bf2cbd637e9ea2e8e842bab9feb12ab1 | 3,652,628 |
def find_instruction_type(opcode: str) -> InstructionType:
"""Finds instruction type for object instruction
Parameters
----------
opcode : str
opcode of instruction in hex
Returns
-------
InstructionType
type of instruction using InstructionType enum
"""
# R type in... | a8f5002834f9e9e847ef4f848a13f6e8037948f6 | 3,652,629 |
import string
def gen_tier_id(inst, id_base, tier_type=None, alignment=None, no_hyphenate=False):
"""
Unified method to generate a tier ID string. (See: https://github.com/goodmami/xigt/wiki/Conventions)
"""
# In order to number this item correctly, we need to decide how many tiers of the same type
... | f21b94677efe25e545d7efd99c68ed1722018c35 | 3,652,630 |
def create_temporary_file(filename, contents=""):
""" Decorator for constructing a file which is available
during a single test and is deleted afterwards.
Example usage::
@grader.test
@create_temporary_file('hello.txt', 'Hello world!')
def hook_test(m):
... | b4ce96e0d239acc379d78b7c13042cea5c0a4fe0 | 3,652,631 |
def find_post_translational_modifications(filter=None, page=0, pageSize=100): # noqa: E501
"""Find values for an specific property, for example possible taxonomy values for Organism property
# noqa: E501
:param filter: Keyword to filter the list of possible values
:type filter: str
:param page: Nu... | 9c9d196a7d0d3e8c3b2725247504cecf822ac541 | 3,652,632 |
def random_vector(A, b):
"""
Generates a random vector satisfying Ax <= b through rejection
sampling.
"""
dimension = A.shape[1]
not_feasible = True
while not_feasible == True:
config.reject_counter = config.reject_counter + 1
if config.reject_counter == config.milestone:
... | e710ef0a3e49fc7834850465f11232df546b944d | 3,652,633 |
from .transform import mapi
from typing import Callable
def mapi(mapper: Callable[[TSource, int], TResult]) -> Projection[TSource, TResult]:
"""Returns an observable sequence whose elements are the result of
invoking the mapper function and incorporating the element's index
on each element of the source."... | e640a1a4b68b9115ca2358502b675e4d6710ea83 | 3,652,634 |
def game_to_screen(position):
"""
Converts coordinates from game view into screen coordinates for mouse interaction
"""
return (GAME_LEFT + position[0], GAME_TOP + position[1]) | 2176d74a98db1e226dc960b14db35af303bfe9ec | 3,652,635 |
def get_graph_params(filename, nsize=1):
"""Load and process graph adjacency matrix and upsampling/downsampling matrices."""
data = np.load(filename, encoding='latin1')
A = data['A']
U = data['U']
D = data['D']
U, D = scipy_to_pytorch(A, U, D)
A = [adjmat_sparse(a, nsize=nsize) for a in A]
... | 5c0671dbe7cd2f56aace9319f78289b1e34defa4 | 3,652,636 |
from . import computers
def _(dbmodel, backend):
"""
get_backend_entity for DummyModel DbComputer.
DummyModel instances are created when QueryBuilder queries the Django backend.
"""
djcomputer_instance = djmodels.DbComputer(
id=dbmodel.id,
uuid=dbmodel.uuid,
name=dbmodel.na... | dd9dc5eeb0dcd54816675bd2dc19e5a0fc10a59a | 3,652,637 |
import six
def retrieve(filename, conf, return_format='dict', save_to_local=False, delete_remote=False, timeout=60):
"""Retrieving Processed Session File from server via sFTP
1. Get xml file string from server and return object
2. If save_to_local, save to local file system
Args:
filename: f... | 1ebf550b8a9be3019ed851a5e4571ed9a72f3e44 | 3,652,638 |
def get_simulate_func_options(
params,
options,
method="n_step_ahead_with_sampling",
df=None,
n_simulation_periods=None,
):
"""Rewrite respy's get_simulation_function such that options can be passed
and therefore the seed be changed before any run. Documentation is adapted
from :func:`re... | 9d77730facb29d460c958033873bb2ce02f5a9ed | 3,652,639 |
def get_host_user_and_ssh_key_path(instance_name, project, zone):
"""Return a tuple of (hostname, username and ssh_key_path)."""
output = api.local(
'gcloud compute ssh --project "%s" --zone "%s" %s --dry-run' %
(project, zone, instance_name),
capture=True)
print output
m = re.match('/usr/bin... | eabc88808fe0b73e9df507ea0397c3b9eb38a8de | 3,652,641 |
def TDataStd_TreeNode_Find(*args):
"""
* class methods working on the node =================================== Returns true if the tree node T is found on the label L. Otherwise, false is returned.
:param L:
:type L: TDF_Label &
:param T:
:type T: Handle_TDataStd_TreeNode &
:rtype: bool
... | 6c37e5f05627287eab4c4c13a21d92aa6e4e6a1a | 3,652,642 |
def make_group_corr_mat(df):
"""
This function reads in each subject's aal roi time series files and creates roi-roi correlation matrices
for each subject and then sums them all together. The final output is a 3d matrix of all subjects
roi-roi correlations, a mean roi-roi correlation matrix and a roi-r... | 4d30136e8ce46e984c0039ddaca26efd04f231b9 | 3,652,643 |
def get_tradedate(begin, end):
"""
get tradedate between begin date and end date
Params:
begin:
str,eg: '1999-01-01'
end:
str,eg: '2017-12-31'
Return:
pd.DataFrame
"""
try:
conn = pymysql.connect(**config)
cursor = conn.cursor()
... | 9464caee65f12b9704e63068e159494baad25e6a | 3,652,644 |
def collect_tweet(update: Update, context: CallbackContext) -> int:
"""Tweet caption collection for tweet without attachments"""
logger.info("'{update.message.text}' tweet type selected")
update.message.reply_text("Enter the tweet")
return TWEET | 6fc25efa4dc10f2316b70ff18f9a5c77b83c1e4a | 3,652,645 |
from typing import Dict
def get_unhandled_crictical_errors(req:HttpRequest, n:int):
"""
Preprocess errors before injection
and gets `n` unhandled errors
Typical Return Value if `n` errors were found...
{"es":[
{
"id": "192.168.1.51",
"title":"hey there... | ae2afdeda89f9a9d946fa60a8ba5e15277388e50 | 3,652,646 |
def ADO_mappings(N, K, level_cutoff):
"""
ADO (auxilary density operators) are indexed by a N by (K + 1) matrix
consisting of non-negative integers.
ADO_mappings calculates all possible matrices "ado_index" of size
N by (K+1) where np.sum(m) < level_cutoff
Parameters
----------
N : int... | a76da5569863ea8d17ec248eb09b2b6e5a300ad2 | 3,652,647 |
def f_beta(precision, recall, beta):
"""
Returns the F score for precision, recall and a beta parameter
:param precision: a double with the precision value
:param recall: a double with the recall value
:param beta: a double with the beta parameter of the F measure, which gives more or less weight to... | be6c2b011c51d58d4b5f943671cd53b45632b48f | 3,652,648 |
import ntpath, os, yaml
def get_cfg(existing_cfg, _log):
"""
generates
"""
_sanity_check(existing_cfg, _log)
with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
'r') as stream:
try:
ret = yaml.load(stream)
... | 3d69096ebc1b78ad52dcc5b35b225ccfea5ff189 | 3,652,650 |
import struct
def readShort(f):
"""Read 2 bytes as BE integer in file f"""
read_bytes = f.read(2)
return struct.unpack(">h", read_bytes)[0] | 1b31c2285d055df3c128e8158dcc67eb6c0a2b18 | 3,652,653 |
def get_color(thing):
"""Get color for thing.
:param thing: Thing to get color for.
:return: Color tuple if rule exists otherwise None.
"""
for rule in _COLOR_RULES:
color = rule(thing)
if color is not None:
return color
return None | 79620c0ec8d5e9a153038b9b6a65f36158dce255 | 3,652,654 |
def build_table(infos):
""" Builds markdown table. """
table_str = '| '
for key in infos[0].keys():
table_str += key + ' | '
table_str += '\n'
table_str += '| '
for key in infos[0].keys():
table_str += '--- | '
table_str += '\n'
for info in infos:
table_str += ... | 8d31e6abc9edd0014acbac3570e4a2bc711baa4a | 3,652,655 |
import six
import threading
def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs):
"""
Sends a telegram notification and returns *True* on success. The communication with the telegram
API might have some delays and is therefore handled by a thread.
"""
# test impo... | a736025f5c6a6acff634f325ecbad0e591f30174 | 3,652,656 |
def convert_to_dapr_duration(td: timedelta) -> str:
"""Converts date.timedelta to Dapr duration format.
Args:
td (datetime.timedelta): python datetime object.
Returns:
str: dapr duration format string.
"""
total_minutes, secs = divmod(td.total_seconds(), 60.0)
hours, mins = di... | 729cde6d2dccea1c8fa36eec506ee8ee6ea34b6e | 3,652,657 |
def get_slot(handler_input, slot_name):
# type: (HandlerInput, AnyStr) -> Optional[Slot]
"""Return the slot information from intent request.
The method retrieves the slot information
:py:class:`ask_sdk_model.slot.Slot` from the input intent request
for the given ``slot_name``. More information on t... | c564f3b82fb21c12b81d1fda0214c330e7355080 | 3,652,658 |
from typing import Callable
def password_to_key(
hash_implementation: Callable[[bytes], TDigestable], padding_length: int
) -> Callable[[bytes, bytes], bytes]:
"""
Create a helper function to convert passwords to SNMP compliant keys
according to :rfc:`3414`.
>>> hasher = password_to_key(hashlib.s... | 3f638afaa5c950f70edf39ca699701ec1709729e | 3,652,659 |
import re
def categorize_tag_key_characters(OSM_FILE = "data\\round_rock.xml", category = 'Summary'):
"""Categorizes attributes into those with:
all lower character, all lower after colon(:),
containing special/problem characters and
all all others that were not listed in above
wh... | 4e2f6c6a24a14114ce8f5c8d2855847859ad4d8f | 3,652,660 |
def rotate_left(value, count, nbits, offset):
"""
Rotate a value to the left (or right)
@param value: value to rotate
@param count: number of times to rotate. negative counter means
rotate to the right
@param nbits: number of bits to rotate
@param offset: offset of the first b... | ed24a0a958bed1ab1a01c4a858bfba0fd163e2fd | 3,652,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.