content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def test(context):
"""
Manage tests (L1 metadata).
Check available tests, inspect their metadata.
Convert old metadata into the new fmf format.
"""
# Show overview of available tests
if context.invoked_subcommand is None:
tmt.base.Test.overview()
return 'test' | 5cdc10f09c97b0036e585cee33bc0932686bb053 | 60,900 |
def valid_pos(newpos, sprites):
""" checks if given position respects given distance between sprites """
mindist = DISTANCE_BETWEEN_SPRITES
valid = True
for s in sprites:
if (newpos - s.pos).length() < mindist:
valid = False
break
return valid | 1f43e7f6ad6ba2040aade1375a52fd6c99d8bc8c | 60,901 |
def register_guest():
"""
Handle requests to the /register_guest route
registers a guest account after an order has been made
"""
if session['guest']:
user = User.query.filter_by(id=session['guest']).first()
if user:
user.is_registered=True
form = Registratio... | 995d8ecfa4810528c66ae9c521962edc805c27b7 | 60,902 |
def beaufort(wind):
"""
https://en.wikipedia.org/wiki/Beaufort_scale
"""
if wind >= 32.7:
return "12 hurricane"
elif wind > 28.5:
return "11 violent storm"
elif wind > 24.5:
return "10 violent storm"
elif wind > 28.5:
return "9 violent storm"
elif wind > 17.2:
return "8 gale"
elif ... | 4fdbe110ea6b94bdeccbc5c1a4ad39950d35c479 | 60,903 |
from typing import Optional
def identity(length: int, k: int, axis: Optional[int] = None) -> ndarray:
"""
Get a vector of given length L with one 1 at position K.
Parameters
----------
length : int
order of the row vector
k : int
position of 1
axis : int or None, optional
... | a7f23cdfc92f3a7c04fcfc87310773c8f8a9e23d | 60,904 |
import posix
def IsAppBundle():
# type: () -> bool
"""Are we running inside Oil's patched version of CPython?
As opposed to a "stock" Python interpreter.
"""
# Ovm_Main in main.c sets this.
return posix.environ.get('_OVM_IS_BUNDLE') == '1' | 9e98681858e493231255f28ee3fbb41f1e104268 | 60,905 |
def pad_id(identifier, fmt):
"""Pad an identifier with leading zeros."""
if not isinstance(identifier, int):
identifier = clean_id(identifier)
if identifier == '':
identifier = 0
else:
identifier = int(identifier)
return fmt % identifier | fc2d3ae886c0bd1bbe0dea2dce1b22af3f67ab22 | 60,906 |
import math
def halstead_visitor_report(visitor):
"""Return a HalsteadReport from a HalsteadVisitor instance."""
h1, h2 = visitor.distinct_operators, visitor.distinct_operands
N1, N2 = visitor.operators, visitor.operands
h = h1 + h2
N = N1 + N2
if h1 and h2:
length = h1 * math.log(h1, ... | 441ecd5bcc963b579697654f2e745ca5a92a6b6a | 60,907 |
import pandas
def stackDF(df, column_names = ["column1","column2","values"], symmetric = True ):
"""Stacks similarity dataframe by return column1, column2, values df
Args:
df: pandas data frame
column_names: names of return df (default ["column1","column2","values"] )
symmetric (... | d328a77f9bcf411a5ed1dbdd7f7328dcc675c23c | 60,908 |
def install_system_packages(distro):
"""
Install system packages based on the Linux distribution of the remote node
"""
if distro in ["Debian", "Ubuntu"]:
require.deb.uptodate_index(max_age={'day': 7})
return require.deb.packages(fsettings.DEBIAN_PKGS)
elif distro in ["CentOS", "RHEL... | 41628959b9dfa3d39890096ab34f82fc42ba2fc2 | 60,909 |
def cmp_structure(llst, rlst, lslices, rslices):
"""Compare the structure of llst[lslices] and rlst[rslices]."""
lshape = slice_shape(llst, lslices)
rshape = slice_shape(rlst, rslices)
if (len(lshape) != len(rshape)):
return -1
for i in range(len(lshape)):
if lshape[i] != rshape[i]:
... | 29e8abde9de56244d408fa247fa8e72e011b8539 | 60,910 |
def adjust_frame_length(x, pad=True, divisible_by=1, **kwargs):
"""Adjust frame length given a feature vector or matrix.
This adjust the number of frames of a given feature vector or matrix to be
divisible by ``divisible_by`` by padding to the end or removing the last
few frames. Default uses zero-padd... | ef3b1aeea748703222351b3fc656b70ac52dfc22 | 60,911 |
def auth_routes():
"""
获得角色方法
:return:
"""
return jsonify({"/form/advanced-form":{"authority":["admin","user"]}}) | 75bc42327e2a2d943ce663bc5e10c0fb2e5f4b52 | 60,912 |
def tan(x):
"""
Returns the tangent of any given fractional value.
:param x: fractional input (sfix, sfloat)
:return: tan of :py:obj:`x` (sfix, sfloat)
"""
# reduces the angle to the [0,\pi/2) interval.
w, b1, b2 = sTrigSub(x)
# calculates the sin and the cos.
local_sin = ssin(w, b... | 2c182335133ab0abfa63f74e4f6d23cfe65123b2 | 60,913 |
def matrix_undirected_unweighted(user):
"""
Returns an undirected, unweighted matrix where an edge exists if the
relationship is reciprocated.
"""
matrix = matrix_undirected_weighted(user, interaction=None)
for a, b in combinations(range(len(matrix)), 2):
if matrix[a][b] is None or matri... | f196ee5d22159a2ec54a05fb7f32f018a73c8023 | 60,914 |
def make_sessions(data, session_th=120 * 60, is_ordered=False, user_key='user_id', item_key='item_id', time_key='ts'):
"""Assigns session ids to the events in data without grouping keys"""
if not is_ordered:
# sort data by user and time
data.sort_values(by=[user_key, time_key], ascending=True, i... | 64cee8b4f3c26a6f6f819f3af57bd4cd20aedfe4 | 60,915 |
def balance_data(pairs, classes, n_proportion):
"""Balance negative and positives samples
:param pairs: Positive/negative pairs previously generated
:param classes: Classes corresponding to the pairs
:param n_proportion: Proportion number, e.g. 2
"""
classes = np.array(classes)
pairs = np.a... | 0bac6ba0a0db8a39566d118efb087c6fbff2de59 | 60,916 |
def UC_psi(Z_mask,I,V,q_dict,geo_dict,Z=10):
"""Generates uniformity correction image given input parameters. Returns
dictionary that contains vectors: {q, S, sigS, N_pixels, N_outliers} and
images: {outliers, Sfit, Ic, and UCpsi}. """
q = q_dict['q']
q_flat = q_dict['q_flat']
polfactor = geo_di... | f748eccd4bb3f4c6f23dd8de7dce506e9d122f70 | 60,917 |
def _g2D_func(f, xs_edges, ys_edges, xs_centres, ys_centres, x_indices, y_indices):
"""Calculate the position probability numerically."""
pos = np.empty((2,))
x_mod = np.empty((xs_centres.shape[0],))
y_mod = np.empty((ys_centres.shape[0],))
g_values = np.zeros((xs_centres.shape[0], ys_centres.shape[... | d5cb8854e0d197e797426af3f63441dda7cf1cd2 | 60,918 |
from presqt.targets.gitlab.functions.fetch import gitlab_fetch_resource
import requests
def gitlab_upload_keywords(token, resource_id, keywords):
"""
Upload the keywords to a given resource id.
Parameters
----------
token: str
User's GitLab token
resource_id: str
ID of the res... | f46df53a364345e252212ad8f05c0e455b4d0acb | 60,919 |
import subprocess
def rsync_file(infile, outdir):
"""Rsyncs a file from the correlator machines to dsastorage.
Parameters
----------
infile : str
The sourcefile string, e.g. 'corr01.sas.pvt:/home/user/data/fl_out.1.5618974'
outfile : str
The destination string, e.g. '/home/user/da... | 6d631685b34077c15ba1aa4ace1c1ed277cbbdbc | 60,920 |
def reset_network():
"""
Method to return initial state of the network
"""
return jsonify_params(
CELLULAR_NETWORK.reset_network()
) | 81174766ae29ac0ba61ca2e6f4d0ffc8a220ba08 | 60,921 |
def filter_table_artefacts(
artefacts: tp.Iterable[Artefact]
) -> tp.Iterable[TableArtefact]:
"""
Filter all table artefacts from a list of artefacts.
Args:
artefacts: the artefacts to filter
Returns:
all table artefacts
"""
return [
tp.cast(TableArtefact, artefact)... | 2056ca6f04404bfcb3466cb2024e521d0f67207f | 60,922 |
from typing import Any
import json
def dumps(obj: Any) -> str:
"""Generate JSON from a Python object."""
return json.dumps(obj, cls=EventJSONEncoder) | 019f913286e182dcc8370532f83cde2ac00482ef | 60,923 |
def format_cpus(n):
"""Formats n as a number of CPUs"""
return '{:.1f}'.format(n) | f28f8d24826341aab70347679920dc68f0b394b0 | 60,924 |
def camera():
""" check camera
"""
_cameras = cmds.ls(type = "camera")
_left_cameras = list(set(_cameras) - set(["frontShape","topShape","perspShape","sideShape"]))
if _left_cameras:
info = "场景存在多余摄像机\n"
for _camera in _left_cameras:
info += "{}\n".format(_camera)
... | 6adf64742a171b20ddf0c5d8c59fda845061aff9 | 60,925 |
def switch_block(CLIENT) -> str:
"""Returns hash of most recent switch block.
"""
return CLIENT.queries.get_block_at_era_switch() | 70a1e712c521c24666de05ef11832f2d87217477 | 60,926 |
def format_exception_only(etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.last_type and sys.last_value. The return value is a list of
strings, each ending in a newline.
Normally, the list contains a single string; howe... | 8d8b1bd58cc84e0e00b59e41393f5b52b2e3d93c | 60,927 |
def polyval2d(x, y, c):
"""
Evaluate a 2-D polynomial at points (x, y).
This function returns the value
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
... | 7dddbf4c914cd74b7391aa97aee9610b746e7375 | 60,928 |
def _python(obj):
"""Highlight python syntax on Match object with one group."""
tmp = obj.group()
if tmp[0] in ('"', '\'', '#'):
return "<i>%s</i>" % tmp
if tmp[0] in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):
return "<u>%s</u>" % tmp
if tmp[:4] == "def ":
return "<b... | 1b8a4c00ba15f31b15d62fb8719de901e65e5fe1 | 60,929 |
def from_str_to_bool(string):
"""
# Notes
converts string to boolean value.
# Arguments
- string: string, either one of these values: "true", "false"
"""
res = string.lower()
if res == 'true':
return True
else:
return False | fea84bdebf9363d754d61755c7a8589a0b2b4950 | 60,930 |
def solve2(lines):
"""Solve the problem."""
path1 = trace_path(parse_path(lines[0]))
path2 = trace_path(parse_path(lines[1]))
dist = min([path1[(x, y)] + path2[(x, y)] for x, y in set(path1.keys()) & set(path2.keys())])
return dist | 46a0e3f59b9a102677409379a176892a44ff170d | 60,931 |
def multislice_assign(llst, rlst, lslices, rslices):
"""Return llst after assigning: llst[lslices] = rlst[rslices]"""
if cmp_structure(llst, rlst, lslices, rslices) < 0:
raise ValueError("lvalue and rvalue have different structures")
return m_assign(llst, rlst, lslices, rslices) | f7c9dcc4e300104f51425d2ee20480b87d5f2f72 | 60,932 |
def callback(f, *a):
"""
Vraci funkci f s nastavenym parametrem a.
Tato funkce umi osetrit i vice nez jeden parametr.
Pouziti:
callback(funkce, arg1, arg2, ..., argn )
"""
return lambda: f(*a) | a08188ce01bf887fe7c8c58c300c0ca63ea6fc82 | 60,933 |
def _intersect_items(baselist, comparelist):
"""Return matching items in both lists."""
return list(set(baselist) & set(comparelist)) | 393e31d13dc63656167505068bcb6fee199d4c06 | 60,934 |
from datetime import datetime
def _get_doy(fnames, freq, start):
"""Get the day of year from a filename.
Args:
freq (int): the frequency of the year, e.g. 365.
fnames (list of str): the list of file names.
start (string or None): the start date.
Returns:
numpy.ndarray: an... | bac82928bb7877a7012979f9e81c55023efedb25 | 60,935 |
from datetime import datetime
async def process_request(
dailies_by_station_id: dict,
yesterday_dailies_by_station_id: dict,
hourly_observations_by_station_id: dict,
wfwx_station: WFWXWeatherStation,
requested_station: StationRequest,
time_of_interest: datetime
) -> Sta... | 728b119a13c889ac1939afcb664a15d84bcab545 | 60,936 |
def get_engine(uri: str, connect_args: dict) -> sa.engine.Engine:
"""
Returns a sqlalchemy engine with pool_pre_ping enabled.
This function may be updated over time to reflect recommended engine configuration for use with FastAPI.
"""
return sa.create_engine(uri, pool_pre_ping=True, connect_args=co... | f038d983afefa614beea3dfa55f2dcf266480d0b | 60,937 |
def remove_extra_spaces(string_item):
"""
Remove all extra spaces from a string leaving single spaces
:type string_item: String
:param string_item: String that you want to remove spaces from
:rtype: String
:return: Corrected string without any extra spaces
"""
string_item = ' '.join(s... | cb7ce9197b5b59175f0712f1d2a4ba6727321c59 | 60,938 |
def parse_scale_conversion_command(sh: Worksheet, area: AreaTupleType, name: str = None) -> IssuesLabelContentTripleType:
"""
Analyze the input area
Obtain the numerical part
Read a row above and a column to the left, looking for source (left col) and target (row above) factor types
FactorTypes do ... | 5df3bb285d10790aecb1c6a6146f5decdb8e4737 | 60,939 |
def UnrefineSplineSet( fact = 2, compound = None, add = True, infa = False ):
"""
Description:
Unrefines a spline set.
Arguments:
# fact
Description: The unrefinement factor. For example, if equals 2, one spline over two is kept.
Type: Integer
GUI selection: -
Selection by n... | 4fcd1e977951592fa663ebba9f02b3c7d308c0b2 | 60,940 |
import typing
from typing import OrderedDict
import yaml
import math
import itertools
def get_native_env_from_simulation(
simulation_name: str, observation_file: str = None
) -> nativerl.Environment:
"""Returns a pynativerl.Environment given a Pathmind Python `Simulation` name.
:param simulation_name: na... | 5afdaa6d825b7443798dfb0d1b0482a3b07f5e94 | 60,941 |
def cardbot_help() -> discord.Embed:
"""
Get usage on the bot commands.
:returns: Instructions for using the bot
"""
embed = discord.Embed(title="Cardbot Help")
embed.add_field(
name="!search [card-name]",
value="""
Gives a list of all cards matching the search, as well as the s... | cb61ac9a146fc7edd94a514756bccc43f4ec36dd | 60,942 |
def joint_correctness_contingency_table(df1, df2, uid_key, prediction_key,
true_label_key):
"""Makes a contingency table comparing correctness of model 1 and model 2.
Args:
df1: a DataFrame for the predictions of model 1.
df2: a DataFrame for the predictions of model... | ad1c822015809e519fcb060a2346690b26add2ec | 60,943 |
def tunein_to_station(base: Tunein, station_id: int, session=None) -> str:
"""
:param base: value is taken from the tunein node and based on the playlist format required
(as PLS, M3U and XSPF formats are supported)
:param station_id: station id
:param session: request_cache session if available
... | e32424dd9908f6056855e21db38b5945b491fb9b | 60,944 |
import logging
def convert_v_v_2_molec_cm3(arr=None, wd=None, vol=None, a_m=None,
mols=None, res='4x5', trop_limit=True,
explicitly_calc=True, debug=False):
"""
Converts mixing ratio (v/v) into number density (molec/cm3).
Parameters
----------
... | a69d17fb4c0c40b09716a6050b647212f366ac1f | 60,945 |
import os
def _get_scene_calibration_table(calibration_files):
"""Return a calibration object from filepaths"""
calibration_table = {}
for f in calibration_files:
calibration = open_pbobject(f, SampleCalibration)
calibration_key, _ = os.path.splitext(os.path.basename(f))
for (name,... | 014c2d34f46dde8a70b7024a1e1131e8e9b0afd1 | 60,946 |
def OneHot(obs: np.ndarray):
"""
Args:
obs:(N,obs_dim)
Returns:
obs:(N,obs_dim+N)
"""
N, _ = obs.shape
encode = np.eye(N) # one hot encoding
return np.concatenate([obs, encode], axis=1) | c1692af8b0001d2383f8db703fada342808cded2 | 60,947 |
def shortest_path(start, end):
"""
Using 2-way BFS, finds the shortest path from start_position to
end_position. Returns a list of moves.
You can use the rubik.quarter_twists move set.
Each move can be applied using rubik.perm_apply
"""
visited_front={}
parent_front={}
q_front=dequ... | 1296b29055ffbb6461375946c74a24103601f712 | 60,948 |
from datetime import datetime
def reformat_date(date, new_fmt='%Y-%m-%d'):
""" Return reformated date. Example: 01/28/2014 & %d/%m/%Y -> 28/01/2014
Accepted date format: %m/%d/%Y
"""
try:
if type(date) is datetime:
return date.strftime(new_fmt)
else:
fmt = '%m/%... | 4e22350ad5a3b6f4087b5aadb1693263f31b5ee6 | 60,949 |
def all_episodes1():
"""
contains playable podcasts listed as just-in
"""
soup = thisislove.get_soup(URL)
playable_podcast1 = thisislove.get_playable_podcast1(soup)
items = thisislove.compile_playable_podcast1(playable_podcast1)
return items | 594fe8c4fbed54f4f5a064125b193a05f720e794 | 60,950 |
def append_species(filename, lines, names):
""" (dictionary, str) -> NoneType
Appends all of the species and genes from one file to a dictionary.
Returns a list that holds all the occurences of a species.
"""
for line in lines:
if line[0] == ">":
name = line[1:].strip()
if name not in names:
names... | d0ca1ccd4b0bc28676e68c3b4574ff1973969f86 | 60,951 |
import re
def search_type(name, source):
""" search for a specific type definitions
return type body (as raw text)
"""
m = re.search(TYPE_RE_TEMPLATE.format(name=name), source, re.DOTALL)
if m is None:
raise ValueError("Type "+name+" was not found")
return m.groupdict()["defs"] | 7c3fa7696376f2a42d0203060087c92149dc80b2 | 60,952 |
def to_note_off_event(note, channel):
"""
:param note: model Note
:return: Midi Event
"""
return midi.NoteOnEvent(channel=channel, tick=0, pitch=note.pitch,
velocity=0) | 5c0e506e2b461d759bbbbc5b2661dbbc1e957cb4 | 60,953 |
def force_ld_control_snps(ld_df, controls_snps):
"""
* does NOT ensure that all control snps are present in the ld _df
"""
# keep all control snps in "SNP_A"
temp_a = ld_df.loc[ld_df["SNP_A"].isin(controls_snps)].copy()
# keep all control snps in "SNP_B"
temp_b = ld_df.loc[ld_df["SNP_B"].is... | 95bf05d4cbf0834abc6113f39d9db501abc201fa | 60,954 |
def headloss_minor_elbow(FlowRate, Diam, KMinor):
"""Return the minor head loss (due to changes in geometry) in an elbow.
:param FlowRate: flow rate through pipe
:type FlowRate: u.m**3/u.s
:param Diam: diameter of pipe
:type Diam: u.m
:param KMinor: minor loss coefficient
:type KMinor: u.di... | f30d203c6ba46365474b3775cd28c45d8e147de4 | 60,955 |
def is_void(typ):
""" Check if the given type is void """
return isinstance(typ, BasicType) and typ.type_id == BasicType.VOID | d723cb4be0f35a1073ef94d150c20809a78b7edd | 60,956 |
def ensure_link_pathway_genome(kegg_genome_id: str, error_on_missing: bool = False) -> str:
"""Get the protein-pathway links for the given organism.
:raises: FileNotFoundError
"""
return ensure_path(
KEGG_PATHWAY_PREFIX,
'link_pathway',
url=f'{BASE}/link/pathway/{kegg_genome_id}... | 6e569cc8725c1aad3108613a02ec622097f52843 | 60,957 |
import codecs
def load_data_multilabel_new(vocabulary_word2index, vocabulary_word2index_label, valid_portion=0.05,
max_training_data=1000000,
traning_data_path='../train-zhihu4-only-title-all.txt', multi_label_flag=True,
use_seq2se... | 5a7e364961c3122fbbb85bbebc46549f01a2b217 | 60,958 |
import os
def download_esc50_dataset(**kwargs):
"""Downloads ESC50 dataset, and returns directory path."""
tf.compat.v1.logging.info('Downloading ESC50 dataset.')
# ${HOME}/.keras/datasets/mini_speech_commands.zip
filepath = tf.keras.utils.get_file(
'esc-50.zip',
'https://github.com/karoldvl/ESC-5... | 874788a97ac939b58ecf5bf60f311b7e057d4d69 | 60,959 |
import string
from StringIO import StringIO
from io import StringIO
def typeset_lists(filestr, format, debug_info=[]):
"""
Go through filestr and parse all lists and typeset them correctly.
This function must be called after all (verbatim) code and tex blocks
have been removed from the file.
This ... | bf894fae1ad769ccb98c8f279792fb4420dff4c6 | 60,960 |
def entropy(y0, y1, w0, w1):
"""
depracated
Impurity - entropy
:param y0: probabilistic output for samples in a set 0
:param y1: probabilistic output for samples in a set 1
:param w0: weight of the set 0 impurity
:param w1: weight of the set 1 impurity
:return: weighted impurity - entrop... | 0da9ae86309a5a6fffd71cd8553466877b58727c | 60,961 |
from typing import List
from typing import Tuple
def modified_mask_encodings(
encoding: List[int], tok,
markers: List[str]) -> Tuple[List[int], List[List[int]]]:
"""Modifies the text corresponding to encoding, to add spaces before discourse markers and finds the apt encodings
to use for the ma... | 695ad9b6bbd90e1cc3bb92ac50efb7c5cda74b29 | 60,962 |
def make_cube_bbox(bbox):
"""
:param bbox: (2,3) mi,mx
mx
(YZ) (XYZ)
6.........7
/. /|
/ . / |
/ . / |
3.........5 |
| . | |
| 2.....|...4
... | b6e34764439fcfc77198837c27f9fd7b607f5a67 | 60,963 |
def _calc_net_active_face_flux_at_node(grid, unit_flux_at_faces, out=None):
"""Calculate net face fluxes at nodes, ignore inactive faces.
Given a flux per unit width across each face in the grid, calculate the net
outflux (or influx, if negative) at each node (nodes without cells are
zero, or unchanged... | 31849c0fd6eb26bb6fb617b6aabd1ba8259c4c54 | 60,964 |
def convert_id_to_label(pred_ids_result, idx2label, batch_size):
"""
将id形式的结果转化为真实序列结果
:param pred_ids_result:
:param idx2label:
:return:
"""
result = []
for row in range(batch_size):
curr_seq = []
for ids in pred_ids_result[row][0]:
if ids == 0:
... | 4ee2373f411977290d3f1dca55f3a3e9253d1af4 | 60,965 |
import token
def hour_expr(k):
"""hour_expr <- num_hour OPTSPC HOUR"""
success, k1, h = num_hour(k)
if not success:
return False, k, None
success, k2, _ = optspc(k1)
success, k3, t = token('HOUR', k2)
if not success:
return False, k, None
return True, k3, h | 4e0e437c759e0b93dff7c87b06a5c175ce2ae322 | 60,966 |
def Cities():
""" Inserting the cities """
c = db.cursor()
with open('cities', 'r') as f:
cities = f.read()
# print('The cities are: {0}'.format(cities))
citylist = cities.split('\n')
if citylist[len(citylist)-1] == '':
del citylist[len(citylist)-1]
# print(citylist)
... | 96a18d6841f7d14ae9bb6cf05f753684369d0293 | 60,967 |
def list_networks():
""" zerotier-cli listnetworks command
Returns:
list: A list of networks (dict) that the device is connected to.
Raises:
CalledProcessError: If the cli call failed.
ValueError: If the json string could not be successfully parsed into a dict.
"""
return c... | 0fd12b30ba660da3cf95fa835d968cc5f0679400 | 60,968 |
def gnss_earth_rotation_drift(dset: "Dataset") -> np.ndarray:
"""Determine earth rotation drift based on precise or broadcast satellite clock information
The correction is caluclated after the description in Section 6.2.9 in :cite:`zhang2007`.
Args:
dset (Dataset): Model data.
Returns:
... | 3491ffbadb08d2bf1b51f81dbb5cb6a1ef5635b4 | 60,969 |
def build_raw_spike_net():
"""Network that only collects raw spikes"""
NNEURONS = 64
Dout = 1
tap_matrix = np.zeros((NNEURONS, Dout))
net = graph.Network("net")
net.pool = net.create_pool("p1", tap_matrix)
HAL.map(net)
set_analog_config()
return net | eb1628c37d8d16556dab5abe9cf77817a4a673a8 | 60,970 |
def bin_to_int(bin_list, inverse=True):
""" Given arbitrary length list of binary values, calculate integer value.
Parameters
----------
bin_list : list of int
List of binary values for calculating integer value.
inverse : bool, optional
If true (default) caluclate integer from bin_... | 0ab74bafe4d045081732f10733704d7bbeb4a9ea | 60,971 |
def preprocessing_document_list(sentences):
"""Sentence preprocessing pipeline for 'gensim'. Tokenized text is returned."""
tokenized_data = []
for sentence in sentences:
tokenized_data.append(text_preprocessing(sentence))
return tokenized_data | 05dbdcfc1e3efd1e18049d6791fc296041beca35 | 60,972 |
import copy
import torch
def predict_one_sample(model, tokenizer, device, args, content):
"""
对单个样本进行预测
Args:
model: 模型
tokenizer: 分词器
device: 设备信息
args: 配置项信息
content: 新闻正文
Returns:
"""
# 对新闻正文进行预处理,并判断如果超长则进行截断
content_tokens = tokenizer.tokenize... | 2d62d2f85d9afd6e5bed63edd19987e62af7823b | 60,973 |
def get_complementary_infos_disc(browser, dict_disc, url_disc):
"""Returns a dict containing complementary informations for a disc."""
try:
# complementary infos
browser.get_url(url_disc)
soup = browser.get_soup()
dict_complementary = {}
table = soup.find("table", {"class... | a83baf7331c1f0fd8474c8674082f6c06846e5ea | 60,974 |
import os
def _extract_model_name(model_path):
"""
Extract model name from model path.
Args:
model_path (str): Path of Converted model.
Returns:
str, name of Converted model.
"""
base_path = os.path.basename(model_path)
model_name = '.'.join(base_path.split('.')[:-1])
... | 3d848800324c8fc3cbbb98f3ce4978f673aa8660 | 60,975 |
def generateMetaGraph (mazeMap, playerLocation, coins):
"""
Generate a metaGraph from mazeMap, containing all coins and the player.
This function is built on the shortestPaths lib.
"""
nodes = [playerLocation] + coins
metaGraph = {}
bestPaths = {}
i = len(nodes)-1
while i >= 0:
... | d0caefe7e174d8620c40e312c7e4ca5f205c1b4a | 60,976 |
def RegisteredStart(builder):
"""This method is deprecated. Please switch to Start."""
return Start(builder) | f53036c086455a410c13265a4bc942b9066725a0 | 60,977 |
def callattr(value, attr, args = None, kwargs = None):
"""
gets the attribute(s) from a value and calls its
:Example:
---------
>>> from pyg import *
>>> value = Dict(function = lambda a, b: a + b)
>>> assert callattr(value, 'function', kwargs = dict(a = 1, b = 2)) == 3
>>> assert calla... | d4c20f8872255b5a85dffcedaede331d259fbe61 | 60,978 |
def _partial_multi_dot(player_payoff_tensor, strategies, index_avoided):
"""Computes a generalized dot product avoiding one dimension.
This is used to directly get the expected return of a given action, given
other players' strategies, for the player indexed by index_avoided.
Note that the numpy.dot function i... | 87aa4bf817fef359594e5e763792e0f37eef1e95 | 60,979 |
def safe_path_exists(o):
"""Check if `o` is a path to an existing file.
``pathlib2.Path(o).is_file()`` and ``os.path.exists()`` raise various types of
exceptions if unable to convert `o` to a value suitable for use as a path. This
method aims to allow checking any object without raising exceptions.
... | 774926eeac2c397d8543f6a6c1318f566301f2ff | 60,980 |
import types
import typing
def column_factory(
*,
spec: types.Schema,
schemas: types.Schemas,
required: typing.Optional[bool] = None,
logical_name: str,
model_schema: types.Schema,
) -> typing.Tuple[typing.List[typing.Tuple[str, sqlalchemy.Column]], types.Schema]:
"""
Generate column b... | dc3b5a570143c677d0ee674b6dd46822e9d3a561 | 60,981 |
def encode(e, properties=True, lnk=True, indent=False):
"""
Serialize the EDS object *e* to an EDS-PENMAN string.
Args:
e: a EDS object
properties (bool): if `False`, suppress variable properties
lnk: if `False`, suppress surface alignments and strings
indent (bool, int): if... | 97bbc7c7700abdbaca8c49213f27b488718fb259 | 60,982 |
import torch
def tensor_cross_prod(u, M):
"""
:param u: N x 3
:param M: N x P x 3
:return:
"""
s0 = u[:, 1][:, np.newaxis] * M[..., 2] - u[:, 2][:, np.newaxis] * M[..., 1]
s1 = -u[:, 0][:, np.newaxis] * M[..., 2] + u[:, 2][:, np.newaxis] * M[..., 0]
s2 = u[:, 0][:, np.newaxis] * M[...... | f312ff3c2954a514b1486d20bfbc0a3cd5d8db48 | 60,983 |
import sys
def confirm(question, assume_yes=True):
"""
Ask user a yes/no question and return their response as a boolean.
``question`` should be a simple, grammatically complete question such as
"Do you wish to continue?", and will have a string similar to ``" [Y/n] "``
appended automatically. Th... | 7dd1342329fe96cf5743476657a576e43ff7a87f | 60,984 |
import math
def get_visual_pool_size(
vis_arch,
num_frames,
crop_size,
):
"""
Compute the pooling size used in VisualClassifyHead.
args:
vis_arch (string): the architecture of the visual conv net.
num_frames (int): number of frames per clip.
crop_size (int): spatial siz... | cc924b3e2ce0a4dbb7d4ea241aeadd6863606172 | 60,985 |
def get_db_cluster_data(cluster_properties, source_region, result):
"""
Get data from cluster for result outputs.
"""
cluster_response = {}
logger.info("Source Region {}, Region {}".format(source_region, region))
if source_region == region:
cluster_response = aws.describe_db_clusters(DBC... | 6a570b190cfe488d0798769acd6d7f03da12adc3 | 60,986 |
def sample_config():
"""
sample config dict to test workflow utils
"""
sample_config = {
"QC": {
"picard_rmdup": "False",
"adapter": "AATGATACGGCGACCACCGAGATCTACACTCTTTCCCTACACGACGCTCTTCCGATCT",
"min_seq_length": "25",
"quality_trim": "True",
... | 42c959aa9478a8b1b188cc9cebda51cd99544e4b | 60,987 |
def compute_num_freqs(frequencies):
"""Computes the number of frequencies for each time point.
Parameters
----------
frequencies : list of np.ndarray
Frequency values
Returns
-------
num_freqs : np.ndarray
Number of frequencies at each time point.
"""
return np.arra... | 62a4460a6fda7cf23960b183e0c413f421dfaa7a | 60,988 |
def separate_substructures(tokenized_commands):
"""Returns a list of SVG substructures."""
# every moveTo command starts a new substructure
# an SVG substructure is a subpath that closes on itself
# such as the outter and the inner edge of the character `o`
substructures = []
curr = []
for c... | 0b2e57a7014525a9ab9b2d57b35afd05842fb2db | 60,989 |
def roty(t):
"""
Computes rotation matrix around the y-axis.
Parameters:
- - - - -
t : input angle in radians
"""
ct = np.cos(t)
st = np.sin(t)
R = np.asarray(
[[ct, 0, st],
[0, 1, -st],
[-st, 0, ct]])
... | 95bf899cb038c73e0e951ace8fbc323331808030 | 60,990 |
from datetime import datetime
def validateDate(date):
"""
Verifica se a data tem um dos seguintes formatos:\n
- %Y-%m-%d %H:%M:%S \n
- %Y/%m/%d %H:%M:%S \n
- %Y-%m-%d %H:%M \n
- %Y/%m/%d %H:%M \n
:param date: data
:return: boolean
"""
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y/%m/%... | 9c8949497c0b207458a61994b5cf76578cd486bf | 60,991 |
def get_power_spectral_density_matrix(
complex_tensor: ComplexTensor
) -> ComplexTensor:
"""
Cross-channel power spectral density (PSD) matrix
Args:
complex_tensor: speech or noise [..., F, C, T]
Returns
psd: [..., F, C, C]
"""
# outer product: [..., C_1, T] x [..., C_2... | e0c93e201f7e950e1950ab9300b0ca49ba5cfb61 | 60,992 |
def attach(client, volume_id, host, mode=None):
"""A convenience wrapper around _AttachmentState.attach()"""
with __manager__.get_state() as attach_state:
attachment = attach_state.attach(client, volume_id, host, mode=mode)
return attachment | 8a6a09fe28c5d953a2a46fbe160bbef40077e295 | 60,993 |
import os
def generate_key_create_folder():
"""Function to create folders for newly generated access key"""
key = gen_key()
folder = storage + key
os.makedirs(folder)
return key | 2e1473c69d0f6f6f47174966bc358e1aa950f39b | 60,994 |
def remove_peca(tabuleiro, pos):
"""
remove_peca: tabuleiro X posicao -> tabuleiro
Modifica destrutivamente o tabuleiro, removendo a peca da posicao dada.
Devolve o proprio tabuleiro.
"""
del tabuleiro[posicao_para_str(pos)]
return tabuleiro | eb1a908ae8bb8e11ff724b5a5968f6b81584f947 | 60,995 |
def _from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
return "#%02x%02x%02x" % rgb | 464cab5007935824b8b7af28e97cc882ec0653ee | 60,996 |
import ctypes
import os
def get_monotonic_timestamp_in_ms():
"""
Returns the timestamp in milliseconds
"""
t = timespec()
if 0 != clock_gettime(CLOCK_MONOTONIC_RAW, ctypes.pointer(t)):
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
timestamp_ms = (t.tv_s... | 6fb3ee879abdd2cb264f524431bed2dc0320e6b0 | 60,997 |
import time
def daskrej(
flist,
shape=None,
dtype=None,
num_chunks=8,
sigma_thresh=(10,),
combine_func=np.median,
save_intermediate=False
):
"""
Parameters
----------
flist
shape
dtype
num_chunks
Returns
-------
"""
... | 122fc905eab34bff3e18351a8ab84c256604e583 | 60,998 |
import time
import random
def P_m2(event_params, single_centre, binary_centre, sn_base, n_epochs):
"""Calculate the marginalised binary model probability of a specific light curve.
Args:
event_params: [list] Single lens model parameters.
sn_base: [float] Signal to noise baseline of data.
... | 8b75c83ea140eed2b34d30bdab7426f5d48665dd | 60,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.