content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _key_chord_transition_distribution(
key_chord_distribution, key_change_prob, chord_change_prob):
"""Transition distribution between key-chord pairs."""
mat = np.zeros([len(_KEY_CHORDS), len(_KEY_CHORDS)])
for i, key_chord_1 in enumerate(_KEY_CHORDS):
key_1, chord_1 = key_chord_1
chord_index_1 = i... | 0e89b1e11494237c526170f25286c3ad098a1023 | 3,658,300 |
def level_set(
current_price, standard_deviation, cloud, stop_mod, take_profit_mod,
):
"""
Calculates risk and reward levels.
Should return a stop loss and take profit levels.
For opening a new position.
Returns a stop (in the format (StopType, offset)) and a take profit level.
"""
stop... | 541a15b22bc830db530658c10515a15def196516 | 3,658,301 |
def back(deque):
""" returns the last elemement in the que """
if length(deque) > 0:
return deque[-1]
else:
return None | 810d2135cf39af7959f6142be4b2b3abee8d6185 | 3,658,302 |
import json
import operator
def my_subs_helper(s):
"""Helper function to handle badly formed JSON stored in the database"""
try:
return {'time_created':s.time_created, 'json_obj':sorted(json.loads(s.json_data).iteritems(), key=operator.itemgetter(0)), 'plain_json_obj':json.dumps(json.loads(s.json_data... | 4b649d865c3a99f89111baa694df4902e65243e6 | 3,658,303 |
def dynamic_features(data_dir, year, data_source, voronoi, radar_buffers, **kwargs):
"""
Load all dynamic features, including bird densities and velocities, environmental data, and derived features
such as estimated accumulation of bird on the ground due to adverse weather.
Missing data is interpolated... | fd5675b127d6a20f930d8ee88366e7426c5a09b9 | 3,658,304 |
def __normalize_allele_strand(snp_dfm):
"""
Keep all the alleles on FWD strand.
If `strand` is "-", flip every base in `alleles`; otherwise do not change `alleles`.
"""
on_rev = (snp_dfm.loc[:, "strand"] == "-")
has_alleles = (snp_dfm.loc[:, "alleles"].str.len() > 0)
condition = (on_rev & h... | 1ebe00294eb55de96d68fc214bd5051d40a2dfa5 | 3,658,305 |
def add_to_codetree(tword,codetree,freq=1):
""" Adds one tuple-word to tree structure - one node per symbol
word end in the tree characterized by node[0]>0
"""
unique=0
for pos in range(len(tword)):
s = tword[pos]
if s not in codetree:
codetree[s] = [0,{}]
... | e92a48f112e7a774bed3b125509f7f64dce0a7ec | 3,658,306 |
def TA_ADXm(data, period=10, smooth=10, limit=18):
"""
Moving Average ADX
ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend
Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/
Parameter... | 40f41b013127b122bddf66e3dfe53f746c89b3c7 | 3,658,307 |
def remove_from_dict(obj, keys=list(), keep_keys=True):
""" Prune a class or dictionary of all but keys (keep_keys=True).
Prune a class or dictionary of specified keys.(keep_keys=False).
"""
if type(obj) == dict:
items = list(obj.items())
elif isinstance(obj, dict):
items = list(... | b1d9a2bd17269e079ce136cc464060fc47fe5906 | 3,658,308 |
def unify_qso_catalog_uvqs_old(qsos):
"""Unifies the name of columns that are relevant for the analysis"""
qsos.rename_column('RA','ra')
qsos.rename_column('DEC','dec')
qsos.rename_column('FUV','mag_fuv')
qsos.rename_column('Z','redshift')
qsos.add_column(Column(name='id',data=np.arange(len(qso... | 8fe561e7d6e99c93d08efe5ff16d6e37ed66ab4e | 3,658,309 |
def get_hash_key_name(value):
"""Returns a valid entity key_name that's a hash of the supplied value."""
return 'hash_' + sha1_hash(value) | b2bba3031efccb5dab1781695fc39c993f735e71 | 3,658,310 |
import yaml
def yaml_dumps(value, indent=2):
"""
YAML dumps that supports Unicode and the ``as_raw`` property of objects if available.
"""
return yaml.dump(value, indent=indent, allow_unicode=True, Dumper=YamlAsRawDumper) | ed368fb84967190e460c1bcf51bd573323ff4f46 | 3,658,311 |
def poi_remove(poi_id: int):
"""Removes POI record
Args:
poi_id: ID of the POI to be removed
"""
poi = POI.get_by_id(poi_id)
if not poi:
abort(404)
poi.delete()
db.session.commit()
return redirect_return() | 26c1cb2524c6a19d9382e9e0d27947a0d2b2a98c | 3,658,312 |
def stringToTupleOfFloats(s):
"""
Converts s to a tuple
@param s: string
@return: tuple represented by s
"""
ans = []
for i in s.strip("()").split(","):
if i.strip() != "":
if i == "null":
ans.append(None)
else:
ans.append(float... | 7eec23232f884035b12c6498f1e68616e4580878 | 3,658,313 |
import json
import requests
def create_training(training: TrainingSchema):
"""
Create an training with an TrainingSchema
:param training: training data as TrainingSchema
:return: http response
"""
endpoint_url = Config.get_api_url() + "training"
job_token = Config.get_job_token()
heade... | c0ce20fc68cbb3d46b00e451b85bf01991579bcc | 3,658,314 |
def respects_language(fun):
"""Decorator for tasks with respect to site's current language.
You can use this decorator on your tasks together with default @task
decorator (remember that the task decorator must be applied last).
See also the with-statement alternative :func:`respect_language`.
**Ex... | 547629321d649a102a0c082b1eddcac32334432c | 3,658,315 |
def zero_one_window(data, axis=(0, 1, 2), ceiling_percentile=99, floor_percentile=1, floor=0, ceiling=1,
channels_axis=None):
"""
:param data: Numpy ndarray.
:param axis:
:param ceiling_percentile: Percentile value of the foreground to set to the ceiling.
:param floor_percentile... | 4056433a9f3984bebc1c99f30be4f8e9ddc31026 | 3,658,316 |
import sys
def factorial(x):
"""factorial(x) -> Integral
"Find x!. Raise a ValueError if x is negative or non-integral."""
if isinstance(x, float):
fl = int(x)
if fl != x:
raise ValueError("float arguments must be integral")
x = fl
if x > sys.maxsize:
raise... | 664cc8e0e215f089bbc57fec68553d788305e4c0 | 3,658,317 |
def get_event_stderr(e):
"""Return the stderr field (if any) associated with the event."""
if _API_VERSION == google_v2_versions.V2ALPHA1:
return e.get('details', {}).get('stderr')
elif _API_VERSION == google_v2_versions.V2BETA:
for event_type in ['containerStopped']:
if event_type in e:
... | 89a32228d3ad0ecb92c6c0b45664903d6f4b507d | 3,658,318 |
def xA(alpha, gamma, lsa, lsd, y, xp, nv):
"""Calculate position where the beam hits the analyzer crystal.
:param alpha: the divergence angle of the neutron
:param gamma: the tilt angle of the deflector
:param lsa: the sample-analyzer distance
:param lsd: the sample deflector distance
:param y:... | 0dfb9bd7b761fa0669893c692f3adb2a5cb079c4 | 3,658,319 |
from typing import Optional
from datetime import datetime
def find_recent_login(user_id: UserID) -> Optional[datetime]:
"""Return the time of the user's most recent login, if found."""
recent_login = db.session \
.query(DbRecentLogin) \
.filter_by(user_id=user_id) \
.one_or_none()
... | 153dc509e2382e8f9eb18917d9be04d171ffdee9 | 3,658,320 |
async def async_remove_config_entry_device(
hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry
) -> bool:
"""Remove ufp config entry from a device."""
unifi_macs = {
_async_unifi_mac_from_hass(connection[1])
for connection in device_entry.connections
if conn... | f8ae37a454f5c5e3314676162ff48e1e05530396 | 3,658,321 |
def batch_unsrt_segment_sum(data, segment_ids, num_segments):
""" Performas the `tf.unsorted_segment_sum` operation batch-wise"""
# create distinct segments per batch
num_batches = tf.shape(segment_ids, out_type=tf.int64)[0]
batch_indices = tf.range(num_batches)
segment_ids_per_batch = segment_ids +... | 299a514e926c43564960288c706c1d535620144b | 3,658,322 |
import json
def read_json(file_name):
"""Read json from file."""
with open(file_name) as f:
return json.load(f) | 2eccab7dddb1c1038de737879c465f293a00e5de | 3,658,323 |
def get_role(request):
"""Look up the "role" query parameter in the URL."""
query = request.ws_resource.split('?', 1)
if len(query) == 1:
raise LookupError('No query string found in URL')
param = parse.parse_qs(query[1])
if 'role' not in param:
raise LookupError('No role parameter found in the query s... | 87cc8f15a3d0aeb45a8d7ea67fb34573e41b7df7 | 3,658,324 |
def login(username: str, password: str) -> Person:
"""通过用户名和密码登录智学网
Args:
username (str): 用户名, 可以为准考证号, 手机号
password (str): 密码
Raises:
ArgError: 参数错误
UserOrPassError: 用户名或密码错误
UserNotFoundError: 未找到用户
LoginError: 登录错误
RoleError: 账号角色未知
Returns:
... | a982cddb107cc8ccf8c9d1868e91299cd6ac07f3 | 3,658,325 |
def _decode_end(_fp):
"""Decode the end tag, which has no data in the file, returning 0.
:type _fp: A binary `file object`
:rtype: int
"""
return 0 | 5e8da3585dda0b9c3c7cd428b7e1606e585e15c6 | 3,658,326 |
def make_dqn_agent(q_agent_type,
arch,
n_actions,
lr=2.5e-4,
noisy_net_sigma=None,
buffer_length=10 ** 6,
final_epsilon=0.01,
final_exploration_frames=10 ** 6,
... | 0b5974e30a12ef760a424d8d229319ccfee3119a | 3,658,327 |
def build_consensus_from_haplotypes(haplotypes):
"""
# ========================================================================
BUILD CONSENSUS FROM HAPLOTYPES
PURPOSE
-------
Builds a consensus from a list of Haplotype objects.
INPUT
-----
[HAPLOTYPE LIST] [haplotypes]
... | 977e59e77e45cb4ccce95875f4802a43028af060 | 3,658,328 |
from typing import List
from typing import Dict
from typing import Tuple
def convert_data_for_rotation_averaging(
wTi_list: List[Pose3], i2Ti1_dict: Dict[Tuple[int, int], Pose3]
) -> Tuple[Dict[Tuple[int, int], Rot3], List[Rot3]]:
"""Converts the poses to inputs and expected outputs for a rotation averaging a... | 1f058ae1925f5392416ec4711b55e849e277a24c | 3,658,329 |
def all_arrays_to_gpu(f):
"""Decorator to copy all the numpy arrays to the gpu before function
invokation"""
def inner(*args, **kwargs):
args = list(args)
for i in range(len(args)):
if isinstance(args[i], np.ndarray):
args[i] = to_gpu(args[i])
return f(*a... | 25ea43a611ac8a63aa1246aaaf810cec71be4c3f | 3,658,330 |
def create_intersect_mask(num_v, max_v):
"""
Creates intersect mask as needed by polygon_intersection_new
in batch_poly_utils (for a single example)
"""
intersect_mask = np.zeros((max_v, max_v), dtype=np.float32)
for i in range(num_v - 2):
for j in range((i + 2) % num_v, num_v - int(i =... | 32d2758e704901aa57b70e0edca2b9292df2583a | 3,658,331 |
def gdi_abuse_tagwnd_technique_bitmap():
"""
Technique to be used on Win 10 v1703 or earlier. Locate the pvscan0 address with the help of tagWND structures
@return: pvscan0 address of the manager and worker bitmap and the handles
"""
window_address = alloc_free_windows(0)
manager_bitmap_handle = create_bitmap(0x1... | e77253d082b9aaaa083c84ffdbe8a74ae0b84b0b | 3,658,332 |
import os
import argparse
import sys
import array
def main():
"""CLI entrypoint"""
parser = Parser(
prog='unwad',
description='Default action is to convert files to png format and extract to xdir.',
epilog='example: unwad gfx.wad -d ./out => extract all files to ./out'
)
pars... | eee25c0b6d6481ff5e169f36a53daa5bdf3bbd52 | 3,658,333 |
def check_stop() -> list:
"""Checks for entries in the stopper table in base db.
Returns:
list:
Returns the flag, caller from the stopper table.
"""
with db.connection:
cursor = db.connection.cursor()
flag = cursor.execute("SELECT flag, caller FROM stopper").fetchone()
... | b2694938541704508d5304bae9abff25da2e0fc9 | 3,658,334 |
from TorCtl import SQLSupport
import socket
def open_controller(filename,ncircuits,use_sql):
""" starts stat gathering thread """
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((control_host,control_port))
c = PathSupport.Connection(s)
c.authenticate(control_pass) # also launches thread...... | 8686a60dc27d486aac3e6622cd82f94983eda74c | 3,658,335 |
def get_camelcase_name_chunks(name):
"""
Given a name, get its parts.
E.g: maxCount -> ["max", "count"]
"""
out = []
out_str = ""
for c in name:
if c.isupper():
if out_str:
out.append(out_str)
out_str = c.lower()
else:
out_s... | 134a8b1d98af35f185b37c999fbf499d18bf76c5 | 3,658,336 |
def _GetBuildBotUrl(builder_host, builder_port):
"""Gets build bot URL for fetching build info.
Bisect builder bots are hosted on tryserver.chromium.perf, though we cannot
access this tryserver using host and port number directly, so we use another
tryserver URL for the perf tryserver.
Args:
builder_hos... | 551ac7ee9079009cd8b52e41aeabb2b2e4e10c21 | 3,658,337 |
def case_two_args_positional_callable_first(replace_by_foo):
""" Tests the decorator with one positional argument @my_decorator(goo) """
return replace_by_foo(goo, 'hello'), goo | fa5ca0af3d5af7076aebbb8364f29fc64b4e3c28 | 3,658,338 |
def cal_sort_key( cal ):
"""
Sort key for the list of calendars: primary calendar first,
then other selected calendars, then unselected calendars.
(" " sorts before "X", and tuples are compared piecewise)
"""
if cal["selected"]:
selected_key = " "
else:
selected_key = "X"
... | fd1d8b32ee904d3684decba54268d926c5fd3d82 | 3,658,339 |
from datetime import datetime
def select_zip_info(sample: bytes) -> tuple:
"""Print a list of items contained within the ZIP file, along with
their last modified times, CRC32 checksums, and file sizes. Return
info on the item selected by the user as a tuple.
"""
t = []
w = 0
z = ZipFile(s... | aac5b04c40552c09d07bf2db0c2d4431fc168aa2 | 3,658,340 |
import traceback
import select
def create_ionosphere_layers(base_name, fp_id, requested_timestamp):
"""
Create a layers profile.
:param None: determined from :obj:`request.args`
:return: array
:rtype: array
"""
function_str = 'ionoshere_backend.py :: create_ionosphere_layers'
trace... | 3aa77c6d04fb24b2d8443467fbc0189e42b7dd9f | 3,658,341 |
def unitary_ifft2(y):
"""
A unitary version of the ifft2.
"""
return np.fft.ifft2(y)*np.sqrt(ni*nj) | 16dfe62cea08a72888cc3390f4d85f069aac5718 | 3,658,342 |
def orb_scf_input(sdmc):
""" find the scf inputs used to generate sdmc """
myinputs = None # this is the goal
sdep = 'dependencies' # string representation of the dependencies entry
# step 1: find the p2q simulation id
p2q_id = None
for key in sdmc[sdep].keys():
if sdmc[sdep][key].result_names[0] == 'o... | c319693e9673edf540615025baf5b5199c5e27a3 | 3,658,343 |
def is_success(code):
""" Returns the expected response codes for HTTP GET requests
:param code: HTTP response codes
:type code: int
"""
if (200 <= code < 300) or code in [404, 500]:
return True
return False | fa502b4989d80edc6e1c6c717b6fe1347f99990d | 3,658,344 |
from typing import Optional
from typing import Union
async def asyncio(
*,
client: AuthenticatedClient,
json_body: SearchEventIn,
) -> Optional[Union[ErrorResponse, SearchEventOut]]:
"""Search Event
Dado um Trecho, uma lista de Grupos que resultam da pesquisa
por esse Trecho e um price token... | 6bf2a312d41cf77776e0c333ed72080c030a7170 | 3,658,345 |
def get_symmtrafo(newstruct_sub):
"""???
Parameters
----------
newstruct_sub : pymatgen structure
pymatgen structure of the bulk material
Returns
-------
trafo : ???
???
"""
sg = SpacegroupAnalyzer(newstruct_sub)
trr = sg.get_symmetry_dataset()
trafo = []
... | 9a346b4d0761de467baae1ee5f4cb0c623929180 | 3,658,346 |
def convert_sentence_into_byte_sequence(words, tags, space_idx=32, other='O'):
""" Convert a list of words and their tags into a sequence of bytes, and
the corresponding tag of each byte.
"""
byte_list = []
tag_list = []
for word_index, (word, tag) in enumerate(zip(words, tags)):
tag_ty... | 2288d22e44d99ee147c9684befd3d31836a66a9d | 3,658,347 |
import os
def corr_cov(data, sample, xdata, xlabel='x', plabels=None, interpolation=None,
fname=None):
"""Correlation and covariance matrices.
Compute the covariance regarding YY and XY as well as the correlation
regarding YY.
:param array_like data: function evaluations (n_samples, n_f... | a999c5c53db3ca738665631ada721188efc333d5 | 3,658,348 |
def get_number_rows(ai_settings, ship_height, alien_height):
"""Determina o numero de linhas com alienigenas que cabem na tela."""
available_space_y = (ai_settings.screen_height -
(3 * alien_height) - ship_height)
number_rows = int(available_space_y / (2 * alien_height))
return ... | 473f73bc5fb4d6e86acb90f01d861d4d8561d494 | 3,658,349 |
def generate_trial_betas(bc, bh, bcrange, bhrange, step_multiplier, random_state_debug_value=None):
"""Generate trial beta values for an MC move. Move sizes are scaled by the 'step_multiplier' argument,
and individually by the 'bcrange' or 'bhrange' arguments for the beta_c and beta_h values respectively.
... | bacc11ac74076c827c609664d3d56e5e58f47df4 | 3,658,350 |
def map_ref_sites(routed: xr.Dataset, gauge_reference: xr.Dataset,
gauge_sites=None, route_var='IRFroutedRunoff',
fill_method='r2', min_kge=-0.41):
"""
Assigns segs within routed boolean 'is_gauge' "identifiers" and
what each seg's upstream and downstream reference se... | a2146e532a7aa95ba0753aaddc6d6da2cc4f1c67 | 3,658,351 |
def get_error(est_track, true_track):
"""
"""
if est_track.ndim > 1:
true_track = true_track.reshape((true_track.shape[0],1))
error = np.recarray(shape=est_track.shape,
dtype=[('position', float),
('orientation', float),
... | 5ccdb12b844de9b454f62375358d4a1e1b91e6f7 | 3,658,352 |
from typing import Any
def test_conflict():
"""
Tiles that have extras that conflict with indices should produce an error.
"""
def tile_extras_provider(hyb: int, ch: int, z: int) -> Any:
return {
Indices.HYB: hyb,
Indices.CH: ch,
Indices.Z: z,
}
... | 2d2e86f5d60762d509e7c27f5a74715c868abbc4 | 3,658,353 |
import json
def get_node_to_srn_mapping(match_config_filename):
"""
Returns the node-to-srn map from match_conf.json
"""
with open(match_config_filename) as config_file:
config_json = json.loads(config_file.read())
if "node_to_srn_mapping" in config_json:
return config_j... | 37bf2f266f4e5163cc4d6e9290a8eaf17e220cd3 | 3,658,354 |
from matplotlib.pyplot import get_cmap
def interpolate(values, color_map=None, dtype=np.uint8):
"""
Given a 1D list of values, return interpolated colors
for the range.
Parameters
---------------
values : (n, ) float
Values to be interpolated over
color_map : None, or str
Key ... | dfb9e58ef8d07c5e3455297270e36332ef9385df | 3,658,355 |
def nest_dictionary(flat_dict, separator):
""" Nests a given flat dictionary.
Nested keys are created by splitting given keys around the `separator`.
"""
nested_dict = {}
for key, val in flat_dict.items():
split_key = key.split(separator)
act_dict = nested_dict
final_key = ... | f5b8649d916055fa5911fd1f80a8532e5dbee274 | 3,658,356 |
def write(path_, *write_):
"""Overwrites file with passed data. Data can be a string, number or boolean type. Returns True, None if writing operation was successful, False and reason message otherwise."""
return _writeOrAppend(False, path_, *write_) | 3bd5db2d833c5ff97568489596d3dcea47c1a9f4 | 3,658,357 |
import json
def prepare_saab_data(sequence):
"""
Processing data after anarci parsing.
Preparing data for SAAB+
------------
Parameters
sequence - sequence object ( OAS database format )
------------
Return
sequence.Sequence - full (not-numbered) antibody sequence... | f88ba3f2badb951f456678e33f3371d80934754e | 3,658,358 |
def covariance_align(data):
"""Covariance align continuous or windowed data in-place.
Parameters
----------
data: np.ndarray (n_channels, n_times) or (n_windows, n_channels, n_times)
continuous or windowed signal
Returns
-------
aligned: np.ndarray (n_channels x n_times) or (n_wind... | 82b99b43202097670de8af52f96ef156218921fb | 3,658,359 |
import math
def _is_equidistant(array: np.ndarray) -> bool:
"""
Check if the given 1D array is equidistant. E.g. the
distance between all elements of the array should be equal.
:param array: The array that should be equidistant
"""
step = abs(array[1] - array[0])
for i in range(0, len(arr... | d12c12e48545697bdf337c8d20e45a27fb444beb | 3,658,360 |
def list_a_minus_b(list1, list2):
"""Given two lists, A and B, returns A-B."""
return filter(lambda x: x not in list2, list1) | 8fbac6452077ef7cf73e0625303822a35d0869c3 | 3,658,361 |
def is_equivalent(a, b):
"""Compares two strings and returns whether they are the same R code
This is unable to determine if a and b are different code, however. If this returns True you may assume that they
are the same, but if this returns False you must not assume that they are different.
i... | c37ea6e8684c1d2fcd5d549836c9115da98c7b2f | 3,658,362 |
def solve(lines, n):
"""Solve the problem."""
grid = Grid(lines)
for _ in range(n):
grid.step()
return grid.new_infections | 2db532a911e088dd58ee17bdc036ea017e979c8d | 3,658,363 |
import requests
def get_ingredient_id():
"""Need to get ingredient ID in order to access all attributes"""
query = request.args["text"]
resp = requests.get(f"{BASE_URL_SP}/food/ingredients/search?", params={"apiKey":APP_KEY,"query":query})
res = resp.json()
lst = {res['results'][i]["name"]:res['r... | 8c58232f48883a4b1e2d76ca1504b3dccabdb954 | 3,658,364 |
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
... | a6b044ffc9efdc279495c25735745006de9d7a8c | 3,658,365 |
def main() -> None:
"""
Program entry point.
:return: Nothing
"""
try:
connection = connect_to_db2()
kwargs = {'year_to_schedule': 2018}
start = timer()
result = run(connection, **kwargs)
output_results(result, connection)
end = timer()
print... | 53727547a16c8b203ca89d54f55ddbd8b2f2645b | 3,658,366 |
from pathlib import Path
from datetime import datetime
def _generate_cfg_dir(cfg_dir: Path = None) -> Path:
"""Make sure there is a working directory.
Args:
cfg_dir: If cfg dir is None or does not exist then create sub-directory
in CFG['output_dir']
"""
if cfg_dir is None:
... | 1c6653f43dc53b5cd8c2ac4f5cdcc084ef4c13ad | 3,658,367 |
def delete(home_id):
"""
Delete A About
---
"""
try:
return custom_response({"message":"deleted", "id":home_id}, 200)
except Exception as error:
return custom_response(str(error), 500) | 408fe8db0a728b33d7a9c065944d706d6502b8b5 | 3,658,368 |
def round_to_sigfigs(x, sigfigs=1):
"""
>>> round_to_sigfigs(12345.6789, 7) # doctest: +ELLIPSIS
12345.68
>>> round_to_sigfigs(12345.6789, 1) # doctest: +ELLIPSIS
10000.0
>>> round_to_sigfigs(12345.6789, 0) # doctest: +ELLIPSIS
100000.0
>>> round_to_sigfigs(12345.6789, -1) # doctest:... | a5191f3c60e85d50a47a43aee38d7d1f14d3fdc6 | 3,658,369 |
import urllib
import json
def load_api_data (API_URL):
"""
Download data from API_URL
return: json
"""
#actual download
with urllib.request.urlopen(API_URL) as url:
api_data = json.loads(url.read().decode())
#testing data
##with open('nrw.json', 'r') as testing_set:
## ... | 61832a798ac616f3d1612ce69411d4f43ed85699 | 3,658,370 |
def test_parsing(monkeypatch, capfd, configuration, expected_record_keys):
"""Verifies the feed is parsed as expected"""
def mock_get(*args, **kwargs):
return MockResponse()
test_tap: Tap = TapFeed(config=configuration)
monkeypatch.setattr(test_tap.streams["feed"]._requests_session, "send", mo... | 25a79966eba641e4b857c80e12fb123e8fc3477f | 3,658,371 |
def hsl(h, s, l):
"""Converts an Hsl(h, s, l) triplet into a color."""
return Color.from_hsl(h, s, l) | 081fb4b7e7fc730525d0d18182c951ad92fab895 | 3,658,372 |
import sys
def factor(afunc):
"""decompose the string m.f or m.f(parms) and return function and parameter dictionaries
afunc has the form xxx or xxx(p1=value, p2=value,...)
create a dictionary from the parameters consisting of at least _first:True.
parameter must have the form name=value, name=value,... | 10447db5728df2ff45846997dfb7fc52cf471080 | 3,658,373 |
def spline(xyz, s=3, k=2, nest=-1):
""" Generate B-splines as documented in
http://www.scipy.org/Cookbook/Interpolation
The scipy.interpolate packages wraps the netlib FITPACK routines
(Dierckx) for calculating smoothing splines for various kinds of
data and geometries. Although the data is evenly ... | 97500c7a63bc076abd770c43fd3f6d23c30baa03 | 3,658,374 |
import time
def load_supercomputers(log_file, train_ratio=0.5, windows_size=20, step_size=0, e_type='bert', mode="balance",
no_word_piece=0):
""" Load BGL, Thunderbird, and Spirit unstructured log into train and test data
Parameters
----------
log_file: str, the file path of ra... | 2282b8cbd975160e57ff62106a7e0bad3f337e5a | 3,658,375 |
def is_running(service: Service) -> bool:
"""Is the given pyodine daemon currently running?
:raises ValueError: Unknown `service`.
"""
try:
return bool(TASKS[service]) and not TASKS[service].done()
except KeyError:
raise ValueError("Unknown service type.") | 160c7c8da0635c9c11ebdaf711b794fc0a09adff | 3,658,376 |
def PropertyWrapper(prop):
"""Wrapper for db.Property to make it look like a Django model Property"""
if isinstance(prop, db.Reference):
prop.rel = Relation(prop.reference_class)
else:
prop.rel = None
prop.serialize = True
return prop | 9f93a37dffd433fd87ffa4bfdb65680a9ad1d02d | 3,658,377 |
def drowLine(cord,orient,size):
"""
The function provides the coordinates of the line.
Arguments:
starting x or y coordinate of the line, orientation
(string. "vert" or "hor") and length of the line
Return:
list of two points (start and end of the line)
"""
glo... | bc688cfe33dcf42ddac6770bbdf91ccc19c1b427 | 3,658,378 |
def bluetoothRead():
""" Returns the bluetooth address of the robot (if it has been previously stored)
arguments:
none
returns:
string - the bluetooth address of the robot, if it has been previously stored; None otherwise
"""
global EEPROM_BLUETOOTH_ADDRESS
... | c4e08d438b91b3651f27b374c0b38069ddd1eaaf | 3,658,379 |
def is_step_done(client, step_name):
"""Query the trail status using the client and return True if step_name has completed.
Arguments:
client -- A TrailClient or similar object.
step_name -- The 'name' tag of the step to check for completion.
Returns:
True -- if the step has succeeded.... | a5373d7e00f0c8526f573356b5d71a2ac08aa516 | 3,658,380 |
def on_chat_send(message):
"""Broadcast chat message to a watch room"""
# Check if params are correct
if 'roomId' not in message:
return {'status_code': 400}, request.sid
room_token = message['roomId']
# Check if room exist
if not db.hexists('rooms', room_token):
{'status_code'... | 01c7f15602653848c9310e90c0a353648fafbb52 | 3,658,381 |
from typing import Union
def arima(size: int = 100,
phi: Union[float, ndarray] = 0,
theta: Union[float, ndarray] = 0,
d: int = 0,
var: float = 0.01,
random_state: float = None) -> ndarray:
# inherit from arima_with_seasonality
"""Simulate a realization from a... | 24c3ac8af295d25facf0e65a4fc0925b22db9444 | 3,658,382 |
def gt_dosage(gt):
"""Convert unphased genotype to dosage"""
x = gt.split(b'/')
return int(x[0])+int(x[1]) | 819fc9beb834f57e44bcb0ac3e1d3c664c7efd42 | 3,658,383 |
from typing import Optional
from typing import Dict
from typing import Any
def create_key_pair_in_ssm(
ec2: EC2Client,
ssm: SSMClient,
keypair_name: str,
parameter_name: str,
kms_key_id: Optional[str] = None,
) -> Optional[KeyPairInfo]:
"""Create keypair in SSM."""
keypair = create_key_pai... | 40cca5fd938aa6709a4d844c912b294c6aaba552 | 3,658,384 |
def sumofsq(im, axis=0):
"""Compute square root of sum of squares.
Args:
im: Raw image.
axis: Channel axis.
Returns:
Square root of sum of squares of input image.
"""
out = np.sqrt(np.sum(im.real * im.real + im.imag * im.imag, axis=axis))
return out | 6aa791d3c6a2e8e6fff0dbe0a364350d48fb4794 | 3,658,385 |
import os
def get_airflow_home():
"""Get path to Airflow Home"""
return expand_env_var(os.environ.get('AIRFLOW_HOME', '~/airflow')) | 19af0ce78204b0c640e4e13fd56605bbcd395422 | 3,658,386 |
import csv
import re
import sys
def read_mapping_file(map_file):
"""
Mappings are simply a CSV file with three columns.
The first is a string to be matched against an entry description.
The second is the payee against which such entries should be posted.
The third is the account against which such... | e72ceb08daac0a12a426062f95cfa06776cfdedd | 3,658,387 |
def biquad_bp2nd(fm, q, fs, q_warp_method="cos"):
"""Calc coeff for bandpass 2nd order.
input:
fm...mid frequency in Hz
q...bandpass quality
fs...sampling frequency in Hz
q_warp_method..."sin", "cos", "tan"
output:
B...numerator coefficients Laplace transfer function
A...denominator... | c7330f9bd4a1941359a54ea6e6d7e8fe7801f55e | 3,658,388 |
def pullAllData():
""" Pulls all available data from the database
Sends all analyzed data back in a json with fileNames and list of list
of all "spots" intensities and backgrounds.
Args:
db.d4Images (Mongo db collection): Mongo DB collection with processed
... | 97674c981af48f37e90667c00947673f1df34c66 | 3,658,389 |
def f2():
"""
>>> # +--------------+-----------+-----------+------------+-----------+--------------+
>>> # | Chromosome | Start | End | Name | Score | Strand |
>>> # | (category) | (int32) | (int32) | (object) | (int64) | (category) |
>>> # |--------------+--... | 159c5167bacbeed38578a8b574b31fa2f57f9467 | 3,658,390 |
def latin(n, d):
"""
Build latin hypercube.
Parameters
----------
n : int
Number of points.
d : int
Size of space.
Returns
-------
lh : ndarray
Array of points uniformly placed in d-dimensional unit cube.
"""
# spread function
def spread(points):... | 416d8c8086eeeaf6e8ea0bf14c300750025455be | 3,658,391 |
def _get_valid_dtype(series_type, logical_type):
"""Return the dtype that is considered valid for a series
with the given logical_type"""
backup_dtype = logical_type.backup_dtype
if ks and series_type == ks.Series and backup_dtype:
valid_dtype = backup_dtype
else:
valid_dtype = logic... | 7b4bcd724d2d7a4029a794456882a8f59fc29006 | 3,658,392 |
def geometric_mean_longitude(t='now'):
"""
Returns the geometric mean longitude (in degrees).
Parameters
----------
t : {parse_time_types}
A time (usually the start time) specified as a parse_time-compatible
time string, number, or a datetime object.
"""
T = julian_centuries... | c47f106392f507d7750f86cba6a7c16ba3270b11 | 3,658,393 |
import os
def create_feature_data_batch(im_dir,video_ids):
"""
create_feature_data_batch
Similar function to create_feature_data however utilizing the batch version of functions used in the original function
suited towards larger set of images
Input : directory of thumbnails, list of video ids
... | 7fa672a25f55fdf004b07f0ba707987bcff26948 | 3,658,394 |
import os
def GetEnvironFallback(var_list, default):
"""Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value."""
for var in var_list:
if var in os.environ:
return os.environ[var]
return default | 1b9cad3c46264c089f250ccb19119cff8cacd0d1 | 3,658,395 |
def get_or_create(model, **kwargs):
"""Get or a create a database model."""
instance = model.query.filter_by(**kwargs)
if instance:
return instance
else:
instance = model(**kwargs)
db.session.add(instance)
return instance | 6af359ebda80b81a0d02762d576ff407f0c186c4 | 3,658,396 |
def test_class_id_cube_strategy_elliptic_paraboloid(experiment_enviroment,
renormalize,
thread_flag):
""" """
tm, dataset, experiment, dictionary = experiment_enviroment
class_id_params = {
"class... | fc5a17e5bf6b158ce242b4289938dec4d2d2e32b | 3,658,397 |
from typing import Dict
from typing import List
def apply_filters(filters: Dict, colnames: List, row: List) -> List:
"""
Process data based on filter chains
:param filters:
:param colnames:
:param row:
:return:
"""
if filters:
new_row = []
for col, data in zip(colnames,... | e52e8b2773dc4e794076b8a480e5eaaab50de06e | 3,658,398 |
def kaiming(shape, dtype, partition_info=None):
"""Kaiming initialization as described in https://arxiv.org/pdf/1502.01852.pdf"""
return tf.random.truncated_normal(shape) * tf.sqrt(2 / float(shape[0])) | 153213279909bf01e9782e0e56d270632c502b27 | 3,658,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.