content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def read_lc_int(buf):
"""
Takes a buffer and reads an length code string from the start.
Returns a tuple with buffer less the integer and the integer read.
"""
if len(buf) == 0:
raise ValueError("Empty buffer.")
sizes = {252:2, 253:3, 254:8}
fst = int(buf[0])
if fs... | 64,500 |
def get_geography_countries_list():
"""Get a list of countries ordered by population size."""
data = load('geography')
return [row['country'] for row in data] | 64,501 |
def visual():
"""It makes little sense to do unittests of this module, so this will suffice."""
pb = ezprogress.progressbar.ProgressBar(total=100, title='Progress', bar_length=50)
pb.start()
for i in range(0, 100):
pb.update(i)
time.sleep(0.01)
pb.finished() | 64,502 |
def export(df: gpd.GeoDataFrame, dst: Path, name: str) -> None:
"""
Exports a GeoDataFrame to a GeoPackage.
:param gpd.GeoDataFrame df: GeoDataFrame containing LineStrings.
:param Path dst: output GeoPackage path.
:param str name: output GeoPackage layer name.
"""
try:
# Open GeoP... | 64,503 |
def sysLogin():
"""Endpoint for getting JWT token by other services
---
requestBody:
required: true
content:
application/json:
schema:
properties:
app:
type: string
key... | 64,504 |
def TemplateResponse(
request: Request, name: str, context: Dict[str, Any], *args, **kwargs
):
""" Create a template response """
context = dict(context)
context["request"] = request
context["scopes"] = parse_scopes(request)
return templates.TemplateResponse(name, context, *args, **kwargs) | 64,505 |
def method_factory(endpoint, client_method_name):
# type: (APIEndpoint, str) -> ClientMethod
"""
Kwargs:
endpoint: the endpoint to generate a callable method for
Returns:
A classmethod to be attached to the APIClient, which will perform
the actual request for this particular end... | 64,506 |
def elgamal_keypair_from_secret(a: ElementModQ) -> Optional[ElGamalKeyPair]:
"""
Given an ElGamal secret key (typically, a random number in [2,Q)), returns
an ElGamal keypair, consisting of the given secret key a and public key g^a.
"""
secret_key_int = a.to_int()
if secret_key_int < 2:
... | 64,507 |
def is_valid_record2(parsed_record):
"""Check if parsed_record is properly formatted"""
if not (
"byr" in parsed_record
and parsed_record["byr"].isdigit()
and len(parsed_record["byr"]) == 4
and (1920 <= int(parsed_record["byr"]) <= 2002)
):
return False
if not (
... | 64,508 |
def append_to_parquet_table(dataframe, filepath=None, writer=None):
"""Method writes/append dataframes in parquet format.
This method is used to write pandas DataFrame as pyarrow Table in parquet format. If the methods is invoked
with writer, it appends dataframe to the already written pyarrow table.
... | 64,509 |
def flw2qs(ex,ey,ep,D,ed,eq=None):
"""
Compute flows or corresponding quantities in the
quadrilateral field element.
Parameters:
ex = [x1, x2, x3, x4]
ey = [y1, y2, y3, y4] element coordinates
ep = [t] element thickness
D = [[kxx... | 64,510 |
def cda(ctx, srcid, rc, purpose, subject, reqorgid, cdatype, id, oid, output):
"""
Get patient HL7 CDA document.
"""
params = {
'sourceIdentifier': srcid,
'idType': 'RC',
'idValue': rc,
'purposeOfUse': purpose.upper(),
'subjectNameId': str(base64.b64encode(subject... | 64,511 |
def top(request):
"""
Return movies from top 3 ranks based on comments amount in some time period
:param request:
:return:
"""
movies = Movie.objects.all()
serializer = TopMovieSerializer(movies, many=True, context={'request': request})
filtered_list = [movie for movie in serializer.data... | 64,512 |
def test_parallel_arg_errors(tmpdir):
"""Error on bad algorithm arguments."""
base_named_configs = ["debug_log_root"]
base_config_updates = collections.ChainMap(PARALLEL_CONFIG_LOW_RESOURCE)
with pytest.raises(TypeError, match=".*Sequence.*"):
parallel.parallel_ex.run(
named_configs... | 64,513 |
def play_vs_ai():
"""Plays a basic game vs the ai"""
a = HumanAgent()
b = MiniMaxAgent()
g = Connect4Game(a, b)
g.play() | 64,514 |
def LargestPrimeFactor(num):
"""Calculate greatest prime factor using length of list
It is best practice to use greatest prime factor for hash table's
capacity. This method calculates the greatest prime factor using the
int passed in and returns the prime integer.
Time complexity of O(logn)
:p... | 64,515 |
def test_actual_results(params, vocab_desired, arr_desired):
"""Test that the actual results are the expected ones."""
bop = BagOfPatterns(**params)
arr_actual = bop.fit_transform(X)
assert bop.vocabulary_ == vocab_desired
if isinstance(arr_actual, np.ndarray):
np.testing.assert_array_equal(... | 64,516 |
def generate_tool_metadata( tool_config, tool, repository_clone_url, metadata_dict ):
"""Update the received metadata_dict with changes that have been applied to the received tool."""
# Generate the guid.
guid = suc.generate_tool_guid( repository_clone_url, tool )
# Handle tool.requirements.
tool_re... | 64,517 |
def fit_gaussian(data, weight=None, func=elliptical_gaussian):
"""Fit a gaussian on a map.
Parameters
----------
data : array_like
the input 2D map
weight : array_like (optional)
the corresponding weights
func : function
the fitted function
Returns
-------
t... | 64,518 |
def lua_property(name):
""" Decorator for marking methods that make attributes available to Lua """
def decorator(meth):
def setter(method):
meth._setter_method = method.__name__
return method
meth._is_lua_property = True
meth._name = name
meth.lua_setter... | 64,519 |
def toalphanum(s):
"""
gets rid of the unwanted characters
"""
_s = ''
for c in s:
if c in '\\ /(.)-':
_s += '_'
else:
_s += c
return _s | 64,520 |
def endl_C_yosMultiplicity( C, yi ) :
"""Returns the list [ nn, np, nd, nt, nHe3, na, ng ] where nn is the multiplicity
for neutrons, np is the multiplicity for protons, etc. If C-value is not defined
then None is returned. If the reaction is fission then -1 is returned for neutron
multiplity (i.e., C =... | 64,521 |
def get_identity(dim, name, conv=True):
"""
:param dim: dimension of the identity matrix
:param name: name for the variable
:param conv: BOOLEAN, define variables as matrix or vector
:return: created parameters of identity for T-layer
"""
return (
tf.Variable(tf.eye(dim, batch_shape=... | 64,522 |
def ip2int(ip_str):
"""
Convert XXX.XXX.XXX.XXX to integer representation
Args:
ip_str (str): IP in a XXX.XXX.XXX.XXX string format
Returns:
ip_int (int): Integer IP representation
"""
ip_int = None
if isinstance(ip_str,str):
# clean IP
if ip_str.find(':') >... | 64,523 |
def gram_matrix(feature_set):
"""
Given a set of vectors, in the form of a tensor, from a layer,
compute the Gram matrix (https://en.wikipedia.org/wiki/Gramian_matrix).
Args:
feature_set: Tensor of vectors
([1, filter_height, filter_width, num_feature_maps])
Returns:
gra... | 64,524 |
def test_Protein_2_FunctionEnum_and_Score_sparse_vs_flatfile_ex_3():
"""
20 random UniProtID that have TM scores
Protein_2_FunctionEnum_and_Score_table_UPS_FIN vs SparseMatrix_ENSPencoding_2_FuncEnum_UPS_FIN
"""
for i in range(20):
UniProtID_2_test = random.choice(ENSP_2_tuple_funcEnum_score... | 64,525 |
def impl_method(
target: Type,
*,
override: bool = False,
as_classmethod: bool = False,
as_staticmethod: bool = False,
):
"""
Decorator.
Set function as a method of the given class (regular, classmethod or staticmethod)
Args:
target: Type
override: bool - should exist... | 64,526 |
def test_dz():
"""(4) Test with non-replacing decorator"""
pass | 64,527 |
def create_user_links(verbose=False):
"""
Store user links in the DB so that loading the graph can be fast.
On the ml-100k dataset loading all these users is not tremendously faster
than re-computing the whole graph.
On the ml-1m dataset this adds a lot of data in the DB; growing it from
~130M... | 64,528 |
def _find_chordless_cycles(bond_graph, max_cycle_size):
"""Find all chordless cycles (i.e. rings) in the bond graph
Traverses the bond graph to determine all cycles (i.e. rings) each
atom is contained within. Algorithm has been adapted from:
https://stackoverflow.com/questions/4022662/find-all-chordles... | 64,529 |
def _get_all_children(base, tag):
"""Get a list of all child elements with a given tag.
Args:
base: The base node element. (lxml node)
tag: Child elements group tag used to select the elements. (string)
Returns:
A list with all child node elements found or an empty list.
"""
... | 64,530 |
def evaluate(y, pred_y):
"""
Revise: test when a key is a review/account.
Evaluate the prediction of account and review by SpEagle
Args:
y: dictionary with key = user_id/review_id and value = ground truth (1 means spam, 0 means non-spam)
pred_y: dictionary with key = user_id/review_id an... | 64,531 |
def unpack_object(data: MessageData) -> Any:
"""unpack data
Parameters
----------
data : mprpc.message.MessageData
data to unpack
Returns
-------
Any
unpacked data
Raises
------
mprpc.MPRPCException
If msgpack package failed to unpack data.
"""
... | 64,532 |
def load_user_fea_dic(config, fea_type):
"""Load user feature.
Args:
config (dict): Dictionary of configuration
fea_type (str): A string describing the feature type. Options:
Returns:
dict: A dictionary with key being the item_id and value being the numpy array of feature vector
... | 64,533 |
def access_token_generator(token_generator, access_token_template):
"""A function that generates a signed access token"""
def func(**extra_claims):
claims = {**access_token_template, **extra_claims}
return token_generator(**claims)
return func | 64,534 |
def daemonize(log=None, root_log=None, close_fds=True):
"""Make current process into a daemon.
"""
# Do a double-fork so that the daemon process is completely
# detached from its parent (it becomes a child of init).
# For details the classic text is:
# W. Richard Stevens, "Advanced Programming i... | 64,535 |
def interpolate_aviso(ds, XC, XG, YC, YG,
debug=True, verbose=True):
"""Interpolate aviso dataset onto model coordinates (regular lat lon grid)
PARAMETERS
----------
ds : xarray Dataset from reading in Aviso data
(e.g. from aviso_products.merge_aviso)
XC : numpy.arra... | 64,536 |
def home(request):
"""
View for homepage.
:param request: WSGI request from user
:return: Render the wiki page and pass the value from context to the template (home.html)
"""
hero_image = 'img/home-cover-night.png'
hero_image_light = 'img/home-cover-light.jpeg'
latest_add_rulesets = []
... | 64,537 |
def create_ABC_estimate_config(path_run_ABC, param_num):
"""
Create ABCtoolbox config file for estimation.
:param path_run_ABC: full or relative path to directory to run ABC in.
:param param_num: number of parameters
:return:
"""
file_name = '{}/test_ABC_estimate.txt'.format(path_run_ABC)
... | 64,538 |
def _testOnCurvePoints():
"""
>>> from defcon.test.testTools import getTestFontPath
>>> from defcon.objects.font import Font
>>> font = Font(getTestFontPath())
>>> glyph = font['A']
>>> contour = glyph[0]
>>> len(contour.onCurvePoints)
4
>>> [(point.x, point.y) for point in contour.o... | 64,539 |
def calculate_mixing_param_constants(asm_obj):
"""Calculate the constants Cs and Cm required for the
determination of the Cheng-Todreas mixing parameters
Parameters
----------
asm_obj : DASSH Assembly object
Contains the geometry and flow parameters
Returns
-------
tuple
... | 64,540 |
def plot_learning_curve(estimator, title, X, y, axes=None, ylim=None, cv=None,
n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):
"""
https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html
"""
if axes is None:
_, axes = plt.subplots(1, 3, f... | 64,541 |
def test_actual_results_without_weights():
"""Test that the actual results are the expected ones."""
params = {'estimator': SAXVSM()}
arr_actual = MultivariateClassifier(**params).fit(X, y).predict(X)
predictions = []
for i in range(n_features):
predictions.append(
params['estima... | 64,542 |
def test_inc_zero():
""" method to test inc function with zero """
assert inc(0) == 1 | 64,543 |
def _get_split_by_type_input_and_validation(
input: Dict[str, Union[list, set]],
background_mat: Matrix,
type_label: str,
splited_selection_for_variance = True
) -> Tuple[Matrix, Matrix, Dict[str, Matrix]]:
"""Get LTOO split (One-out as diffuse input and Leave-One-Out as validati... | 64,544 |
def get_candidate_targets(graph):
"""Return all candidate target on a given BEL graph."""
return [
node
for node in graph.nodes()
if _is_target_node(node)
] | 64,545 |
def _worker_multiprocessing_wrapper(pipe, *args, **kwargs):
"""Wrapper for launching workers with multiprocessing.
Args:
pipe: The `multiprocessing.Pipe` for sending results.
"""
item = worker(*args, **kwargs)
pipe.send(item) | 64,546 |
def register_sync_strategy(session, strategy_cls,
sync_type='file_at_src_and_dest'):
"""Registers a single sync strategy
:param session: The session that the sync strategy is being registered to.
:param strategy_cls: The class of the sync strategy to be registered.
:param syn... | 64,547 |
def test_new_events(div_table):
"""Новые события не порождаются."""
new_events = div_table._new_events(object())
assert isinstance(new_events, list)
assert not new_events | 64,548 |
def convert_np_dtype_to_dtype_(np_dtype):
"""
Convert the data type in numpy to the data type in Paddle
Args:
np_dtype(np.dtype): the data type in numpy.
Returns:
core.VarDesc.VarType: the data type in Paddle.
"""
dtype = np.dtype(np_dtype)
if dtype == np.float32:
... | 64,549 |
def cast_str_to_bool(input_string: str) -> bool:
"""Convert string to boolean with special handling for case, "True", 1.
Special string parsing for booleans.
Args:
input_string (str): Evaluate this string as bool.
Returns:
case-insensitive 'True', '1' or '1.0' is True.
It will... | 64,550 |
def main():
"""Run the core."""
parser = ArgumentParser()
subs = parser.add_subparsers(dest='cmd')
setup_parser = subs.add_parser('enrich', description="Enrich addresses with data.")
setup_parser.add_argument('-q', '--query', dest='query', required=True,
help='Query to... | 64,551 |
def HPLake_Op(mdot_kgpers, t_sup_K, t_re_K, t_lake_K):
"""
For the operation of a Heat pump between a district heating network and a lake
:type mdot_kgpers : float
:param mdot_kgpers: supply mass flow rate to the DHN
:type t_sup_K : float
:param t_sup_K: supply temperature to the DHN (hot)
... | 64,552 |
def get_application_module(application):
"""
Return the python module of a wrapped application
Parameters
----------
application: str
The name of the application
Return
------
The python module containing the wrapper to the application
"""
project_root = get_project_roo... | 64,553 |
def quantize_annotate_layer(to_annotate, quantize_config=None):
"""Annotate a `tf.keras` layer to be quantized.
This function does not actually quantize the layer. It is merely used to
specify that the layer should be quantized. The layer then gets quantized
accordingly when `quantize_apply` is used.
This m... | 64,554 |
async def command_server(msg):
"""Prints information about the server being monitored"""
if (j := server.list_ping()) is not None:
content = '**Server:** ' + server.host + ':' + str(server.port) + '\n'
if 'description' in j and 'text' in j['description']:
content += '**Description:*... | 64,555 |
def phi31_v_from_i_skow(phi31_i):
"""
Calculates the V band phi31 for the given I band phi3 using the
relationship found in Skowron et al. (2016).
(Skowron et al., 2016) (6)
Parameters
----------
phi31_i : float64
The I band phi31 of the star.
Returns
-------
phi31_v :... | 64,556 |
def setNextAvailMachineTimer(intent, session):
"""Dynamo resource and table"""
userTable = DynamoTable('Users')
return buildNextAvailMachineResponse(intent, session, userTable) | 64,557 |
def read_response_head(lines: List[bytes]) -> response.Response:
"""
Parse an HTTP response head (response line + headers) from an iterable of lines
Args:
lines: The input lines
Returns:
The HTTP response object (without body)
Raises:
ValueError: The input is malformed.
... | 64,558 |
def prepare_hr_for_events(events_info) -> str:
"""
Prepare the Human readable info for events command.
:param events_info: The events data.
:return: Human readable.
"""
hr_list = []
for record in events_info:
hr_record = {
'Event ID': record.get('id', None),
... | 64,559 |
def create_vector(expression,verbose=False):
""" Create vector out of the passed expression """
from collections import Counter
from mcmc_convergence_utilities import generate_subtrees
from time import time
s=time()
sub_trees=generate_subtrees(expression).values()
v=Counter(sub_trees)
if... | 64,560 |
def CDLHIGHWAVE(df):
"""
函数名:CDLHIGHWAVE
名称:High - Wave Candle 风高浪大线
简介:三日K线模式,具有极长的上/下影线与短的实体,预示着趋势反转。
python API
integer=CDLHIGHWAVE(open, high, low, close)
:return:
"""
close = df['close']
return talib.CDLHIGHWAVE(open, high, low, close) | 64,561 |
def thisGroup():
"""thisGroup() -> Group
Returns the current context Group node.
@return: The group node."""
return Group() | 64,562 |
def loadWindowTest(j, xfrom, xto):
"""
load a new window, move image to/from
"""
displayMessage(j, 'j.LoadWindow({"id": "%s"}, "light")' % xto)
j.LoadWindow("",
{"id": xto, "clone": xfrom},
"light",
"",
"width=512px,height=598px,lef... | 64,563 |
def swap_simple_oxide(oxin, oxout):
"""
Generates a function to convert oxide components between
two elemental oxides, for use in redox recalculations.
"""
inatoms = {k: v for (k, v) in oxin.atoms.items() if not k.__str__()=='O'}
outatoms = {k: v for (k, v) in oxout.atoms.items() if not k.__str... | 64,564 |
def set_current_head(root: Path, commit: str):
"""
Write a commit hash to the stock file.
Parameters
----------
root : Path
The stock root path
commit : str
Commit hash that will be written to the stock file
"""
with open(root / "head.stock", "w+") as f:
f.write(... | 64,565 |
def sync_wait_for_dataset(rank_id, rank_size, current_epoch):
"""
Wait util the dataset files required by all devices are downloaded.
Note:
It should be used together with `mindspore.dataset.OBSMindDataset` and
be called before each epoch.
Args:
rank_id(int): Rank ID of the dev... | 64,566 |
def logout():
"""
Display the logout request to the user
"""
next_page = request.args.get('next', "")
if is_connected():
return redirect(next_page)
else:
return render_template("logout.html", next=next_page) | 64,567 |
def peaks_adaptive(data, mask, rank=5, r0=7.0, dr=2.0, nsigm=5,\
npix_min=1, npix_max=None, amax_thr=0, atot_thr=0, son_min=8) :
"""Wrapper for liast of 2-d arrays or >2-d arrays
data and mask are N-d numpy arrays or list of 2-d numpy arrays of the same shape
"""
if isinstance(dat... | 64,568 |
def add_layers_basic(sample, R10, T01, R12, R21, T12, T21):
"""
Add two layers together.
The basic equations for the adding-doubling sample (neglecting sources) are
T_02 = T_12 (E - R_10 R_12)⁻¹ T_01
R_20 = T_12 (E - R_10 R_12)⁻¹ R_10 T_21 +R_21
T_20 = T_10 (E - R_12 R_10)⁻¹ T_21
R_0... | 64,569 |
def act_and_step(
key: PRNGKey,
env: gym.Env,
act_fn: ACT_FN,
use_state: bool,
) -> Tuple[PRNGKey, Dict[str, Array]]:
"""Do one-step and return the results.
Args:
key (PRNGKey)
env (GymEnv)
act_fn (ACT_FN)
use_state (bool): Use a state if True. Use an obs otherwi... | 64,570 |
def structure_rebuild_test(pdb_structure, verbose=False):
"""Test rebuild PDB structure from internal coordinates.
:param pdb_structure: Biopython Structure
Structure to test
:param verbose: bool
print extra messages
:return: dict
comparison dict from compare_residues()
"""
... | 64,571 |
def new(input):
"""Create a new Queue"""
# TODO for some reason the input is getting converted into an object and if escaped characters are supplied from the command line
# They are not escaped correctly
# At this point we can't handle escaped characters.
# try for stdin
if not sys.stdin.isatty... | 64,572 |
def sklearn_to_pfa(estimator, types, featurizer=None):
"""
Convert scikit-learn estimator to PFA format.
:param estimator: Scikit-learn estimator, must be supported
:param types: List of tuples (name, type)
"""
types = _fix_types_compatibility(types)
featurizer = featurizer or _construct_fe... | 64,573 |
def rgb_to_hsv(r, g, b):
"""
Converts RGB to HSV
Hue will be normalized and will be on the scale of 0-1 than 0-360
Conversion formula is taken from
https://www.rapidtables.com/convert/color/rgb-to-hsv.html
:param r: Red (0 to 1)
:param g: Green (0 to 1)
:param b: Blue (0 to 1)
:ret... | 64,574 |
def push(scene):
"""
Place *scene* on the top of the stack, and move control to it. This does
return control, so remember to return immediately after calling it.
:param scene: The new scene.
:type scene: :class:`Scene <spyral.Scene>`
"""
if _stack:
spyral.event.handle('director.sc... | 64,575 |
def format_slug(text: str = None, max_len: int = 50) -> str:
"""
Format string to create slug with max length.
Parameters
----------
text: str
name to format into a NetBox slug
max_len: int
maximum possible length of slug
Returns
-------
str: input name formatted as ... | 64,576 |
def cal_merger_props(gals, nouts_all,
verbose=True,
j_smooth_w = 51,
smooth_poly_deg = 5,
rscale = 3.0,
j0_mean_window = 0.5, # take median of j over this time span
# Merger criterion by angular... | 64,577 |
def image_detect_and_compute(detector, img_name):
"""Detect and compute interest points and their descriptors."""
img = cv2.imread(os.path.join(dataset_path, img_name))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kp, des = detector.detectAndCompute(img, None)
return img, kp, des | 64,578 |
async def get_xsts_token(token: str):
"""Gets the XSTS token and the user hash given the XBL token.
Args:
token: The XBL token to authenticate with.
Raises:
IncorrectCredentials: If the XBL token is incorrect.
"""
payload = {
"Properties": {"SandboxId": "RETAIL", ... | 64,579 |
def tts(df, train_size=0.8):
"""
Create train and test dataframes with provided datagroup dataframe.
---
IN
df: datagroup df as created by pull_datagroup_from_db() function (df)
train_size: size of training set, test set will be 1-train_size (float)
OUT
train_df, test_df
"""
... | 64,580 |
def _LogRequest(page_name, req):
"""Logs a reqest object in a a relatively human-readable way.
Args:
page_name: A string identifying this page. Used in log entry for easy
greppability.
req: A WSGI request object.
"""
arg_dict = dict([(arg, req.get(arg)) for arg in req.argume... | 64,581 |
def get_object_type(objects: list, types: list) -> list:
"""Get the object specified.
Args:
objects: a list of objects.
types: a list of the types.
Returns:
A list of a certain type.
"""
return [item for item in objects if item.get('type') in types] | 64,582 |
def generate_random_basis(n_points=1000, n_dims=3, radius=1.0, random_seed=13):
"""Sample uniformly from d-dimensional unit ball
The code is inspired by this small note:
https://blogs.sas.com/content/iml/2016/04/06/generate-points-uniformly-in-ball.html
Parameters
----------
n_points : int
... | 64,583 |
async def save_model_to_disk(training_id: str = '', model: UploadFile = File(...)):
"""
Receives a .zip file containing a tensorflow2 SavedModel object sent by a dataset microservice.
Then, will store the .zip file in trained model docker volume, with the naming format of
<training_id>.zip
:param t... | 64,584 |
def load_face_detector_and_embedder(model_path, model_proto_path, embed_model):
"""Returns loaded face detector and embedder
Args:
model_path (str): Path to the detector model
model_proto_path (str): Path to the proto.txt file from detector model
embed_model (str): Path to the embedder... | 64,585 |
def generate_mitigation_md(mitigation, domain, side_menu_data, side_menu_mobile_data, notes):
"""Generates the markdown for the given mitigation"""
attack_id = util.buildhelpers.get_attack_id(mitigation)
if attack_id:
data = {}
data['attack_id'] = attack_id
data['domain'] = domai... | 64,586 |
def guess_avdm_ols(sed_mod, sed_obs, Alambda):
""" matrix form OLS solution for Av and DM """
sed_mod = np.array(sed_mod)
sed_obs = np.array(sed_obs)
assert sed_mod.ndim == 2
assert sed_obs.ndim == 2
n_band = sed_obs.size
# color
X = np.array([Alambda, np.ones_like(Alambda)]).T
y =... | 64,587 |
def get_stats_example() -> pd.DataFrame:
"""Return example data for statistical analysis.
Returns
-------
data : :class:`~pandas.DataFrame`
dataframe with example data that can be used for statistical analysis
"""
return load_long_format_csv(_get_data("stats_sample.csv")) | 64,588 |
def PyEntityFactory( className, context ):
"""
Build a new class type by calling the factory, and add it
to the given context.
"""
EntityClass = PyEntityFactoryClass( className )
context[ className ] = EntityClass
return EntityClass | 64,589 |
def add_source(config, source, kafka_topic, token):
""" Declare source of data: file upload or kafka stream.
:param source: designate the source of this data, be it kafka stream of a local file
:type source: string
:param kafka_topic: string of the kafka topic to listen to
:type kafka_topic: string
... | 64,590 |
def unix() -> int:
"""
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
Returns:
int
"""
return int(time.time()) | 64,591 |
def next_page(url):
"""Takes Bing search result URL, returns next search result page URL."""
m = re.search('first', url)
if m:
m2 = re.search('first=(\d+)&', url)
page_count = int(m2.group(1))
new_page_count = page_count + 10
to_be_replaced = 'first=' + str(page_count)
... | 64,592 |
def m_mask(elements: str):
"""Mg Ca A Fe B C --> M A B C"""
symbols = elements.split()
hasm = False
nonmetal = []
for s in symbols:
if s in MDefined:
hasm = True
else:
nonmetal.append(s)
if hasm:
masked = "M " + " ".join(sorted(nonmetal))
else:... | 64,593 |
def sanitize_input(data):
"""Sanitizes input for reddit markdown tables"""
# TODO: maybe the rest of markdown?
return data.replace('|', '|').replace('\n', '').replace('*', '\\*') | 64,594 |
def _date2dt(date):
"""转化 datetime.date 到 datetime.datetime 类型"""
return datetime.datetime.combine(date, datetime.time.min) | 64,595 |
def cca_cv(audio_feature='mod_filter', visual_feature='landmarks_3d', save_fig=True, dataset='lrs3', videos_2_load=None):
"""
Cross-validation to train the CCA.
:param audio_feature:
:param visual_feature:
:param save_fig:
:param dataset:
:return:
"""
dl = DataLoader(dataset=datase... | 64,596 |
def _get_relative_anchors(cluster_medoids, bounds):
"""Get medoid coords relative to fetched RGB."""
relative_medoids = cluster_medoids.copy()
relative_medoids.loc[:, "xmin"] -= bounds["XMIN"]
relative_medoids.loc[:, "ymin"] -= bounds["YMIN"]
relative_medoids.loc[:, "xmax"] -= bounds["XMIN"]
rel... | 64,597 |
def get_tv_info_for_season( tv_id, season, verify = True ):
"""
Finds TMDB_ database information for the TV show and a specific season.
:param int tv_id: the TMDB_ series ID for the TV show.
:param int season: the season on the TV show.
:param bool verify: optional argument, whether to verify S... | 64,598 |
def backend_rawfile_load(filename: str, upload_path: str) -> complex:
"""Load an audio sequence from a wav file using the native sampling rate.
Args:
filename (str): audio wav filename
upload_path (str, optional): Upload folder path on backend server.
Returns:
numpy array: audio s... | 64,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.