content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def glycan_to_graph(glycan, libr = None):
"""the monumental function for converting glycans into graphs\n
| Arguments:
| :-
| glycan (string): IUPAC-condensed glycan sequence (string)
| libr (list): sorted list of unique glycoletters observed in the glycans of our dataset\n
| Returns:
| :-
|... | b709cd064cc97159e7bf19b90c3dab2016fbc786 | 4,886 |
def run(ex: "interactivity.Execution") -> "interactivity.Execution":
"""Exit the shell."""
ex.shell.shutdown = True
return ex.finalize(
status="EXIT",
message="Shutting down the shell.",
echo=True,
) | 7ab7bbe8b1c276c1b84963c3a8eb9a1bdb79888c | 4,887 |
def get_features(df, row = False):
""" Transform the df into a df with basic features and dropna"""
df_feat = df
df_feat['spread'] = df_feat['high'] - df_feat['low']
df_feat['upper_shadow'] = upper_shadow(df_feat)
df_feat['lower_shadow'] = lower_shadow(df_feat)
df_feat['close-open'] = df_feat['c... | 42e9c54a3357634cc74878909f2f8a33cfc6ee0c | 4,888 |
import torch
def match_prob_for_sto_embed(sto_embed_word, sto_embed_vis):
"""
Compute match probability for two stochastic embeddings
:param sto_embed_word: (batch_size, num_words, hidden_dim * 2)
:param sto_embed_vis: (batch_size, num_words, hidden_dim * 2)
:return (batch_size, num_words)
"""... | 0668f4bc6e3112cd63d33fcb5612368604724359 | 4,889 |
import functools
def POST(path):
"""
Define decorator @post('/path'):
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
return func(*args, **kw)
wrapper.__method__ = 'POST'
wrapper.__route__ = path
return wrapper
retu... | d2c76d57687dc0983d2f00995c7a6e6414e8201b | 4,890 |
def BatchNorm(
inputs, axis=-1, momentum=0.9, eps=1e-5,
use_stats=-1, **kwargs):
"""Batch Normalization. `[Ioffe & Szegedy, 2015] <https://arxiv.org/abs/1502.03167>`_.
We enforce the number of inputs should be *5*, i.e.,
it is implemented into a fused version.
However, you can still fix th... | 642e8ee5cafdf6a416febaff1ddcae5190e27cb1 | 4,891 |
def problem_from_graph(graph):
""" Create a problem from the given interaction graph. For each interaction (i,j), 0 <= i <= j <= 1 is added. """
n = graph.vcount()
domain = Domain.make([], [f"x{i}" for i in range(n)], real_bounds=(0, 1))
X = domain.get_symbols()
support = smt.And(*((X[e.source] <= X... | 973602abf8a20ffe45a5bcae6ec300ba749ab6d9 | 4,892 |
def rotate_points(x, y, x0, y0, phi):
"""
Rotate x and y around designated center (x0, y0).
Args:
x: x-values of point or array of points to be rotated
y: y-values of point or array of points to be rotated
x0: horizontal center of rotation
y0: vertical center of rotation
... | 8058385185e937d13e2fd17403b7653f3a5f55e7 | 4,893 |
from typing import List
def xpme(
dates: List[date],
cashflows: List[float],
prices: List[float],
pme_prices: List[float],
) -> float:
"""Calculate PME for unevenly spaced / scheduled cashflows and return the PME IRR
only.
"""
return verbose_xpme(dates, cashflows, prices, pme_prices)[0... | 4301e1e95ab4eee56a3644b132a400522a5ab173 | 4,894 |
def get_node(uuid):
"""Get node from cache by it's UUID.
:param uuid: node UUID.
:returns: structure NodeInfo.
"""
row = _db().execute('select * from nodes where uuid=?', (uuid,)).fetchone()
if row is None:
raise utils.Error('Could not find node %s in cache' % uuid, code=404)
return... | 87988d0c0baa665f1fcd86991253f8fe0cba96a1 | 4,895 |
def bisect_jump_time(tween, value, b, c, d):
"""
**** Not working yet
return t for given value using bisect
does not work for whacky curves
"""
max_iter = 20
resolution = 0.01
iter = 1
lower = 0
upper = d
while iter < max_iter:
t = (upper - lower) / 2
if twee... | f7e1dbeb000ef60a5bd79567dc88d66be9235a75 | 4,896 |
def __session_kill():
"""
unset session on the browser
Returns:
a 200 HTTP response with set-cookie to "expired" to unset the cookie on the browser
"""
res = make_response(jsonify(__structure(status="ok", msg=messages(__language(), 166))))
res.set_cookie("key", value="expired")
retu... | 9313e46e2dcd297444efe08c6f24cb4150349fdb | 4,897 |
def register_errorhandlers(app):
"""Register error handlers."""
def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, "code", 500)
return render_template(f"errors/{error_code}.html"), err... | e8e3ddf10fb6c7a370c252c315888c91b26f6503 | 4,898 |
def register(key):
"""Register callable object to global registry.
This is primarily used to wrap classes and functions into the bcdp pipeline.
It is also the primary means for which to customize bcdp for your own
usecases when overriding core functionality is required.
Parameters
----------
... | 4f3d7d9e8b49d448d338408de8ceebee58136893 | 4,899 |
import ctypes
import six
def _windows_long_path_name(short_path):
"""Use Windows' `GetLongPathNameW` via ctypes to get the canonical,
long path given a short filename.
"""
if not isinstance(short_path, six.text_type):
short_path = short_path.decode(_fsencoding())
buf = ctypes.create_unico... | 72d6b9fc1fb8acd6285019a8d48ea42e847ce8db | 4,900 |
import types
def _create_behavioral_cloning_agent(
time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec,
preprocessing_layers: types.NestedLayer,
policy_network: types.Network) -> tfa.agents.TFAgent:
"""Creates a behavioral_cloning_agent."""
network = policy_network(
time... | c3420767aaa153ef44054fdb4fbdcc9540d59775 | 4,901 |
def sidequery():
"""Serves AJAX call for HTML content for the sidebar (*query* **record** page).
Used when the user is switching between **material** and **record** pages.
See also [M:RECORD.body][record.RECORD.body].
Client code: [{sidecontent.fetch}][sidecontentfetch].
"""
session.forget(re... | 6f5c6660f25e568ea4fa2ad046eac5a57cb4f7e5 | 4,903 |
import pandas
import numpy
def random_answers_2020_ml():
"""
Generates random answers the machine learning challenge of
hackathons :ref:`l-hackathon-2020`.
"""
df = pandas.DataFrame({"index": numpy.arange(473333)})
df['label'] = numpy.random.randint(low=0, high=2, size=(df.shape[0], ))
df[... | 24a721c1c8e512ade6293644eff61b0866c3f0fe | 4,905 |
def _sizeof_fmt(num, suffix='B'):
"""Format a number as human readable, based on 1024 multipliers.
Suited to be used to reformat a size expressed in bytes.
By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254
Args:
num (int): The number to be formatted.
suffix (str... | c70c9ce46f6b391e2389329a6fcd50bf863ea041 | 4,907 |
def num_cluster_members(matrix, identity_threshold):
"""
Calculate number of sequences in alignment
within given identity_threshold of each other
Parameters
----------
matrix : np.array
N x L matrix containing N sequences of length L.
Matrix must be mapped to range(0, num_symbol... | e9034a728b22f7a594ef7842f2a4039559751e21 | 4,911 |
def get_score(command: str) -> float:
"""Get pylint score"""
output = check_output(command, shell=True).decode("utf-8")
start = output.find("Your code has been rated at ")
if start == -1:
raise ValueError(f'Could not find quality score in "{output.rstrip()}".')
start += len("Your code has ... | d32b6f9496033d4c2b569ebc7403be43bb43ceb1 | 4,912 |
import json
def __process_input(request_data: str) -> np.array:
"""
Converts input request data into numpy array
:param request_data in json format
:return: numpy array
"""
return np.asarray(json.loads(request_data)["input"]) | 7639018f69a4e72568cdf86abc503133ebd734af | 4,914 |
import math
def getDist_P2L(PointP,Pointa,Pointb):
"""计算点到直线的距离
PointP:定点坐标
Pointa:直线a点坐标
Pointb:直线b点坐标
"""
#求直线方程
A=0
B=0
C=0
A=Pointa[1]-Pointb[1]
B=Pointb[0]-Pointa[0]
C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0]
#代入点到直线距离公式
distance=0
distance=(... | ca0ec1fc25183a240179faef7473d7b86758a92b | 4,915 |
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matri... | e16c7ffd6c4f18e247a885de0b7477ddfa5ed02c | 4,916 |
def JD2RA(JD, longitude=21.42830, latitude=-30.72152, epoch='current'):
"""
Convert from Julian date to Equatorial Right Ascension at zenith
during a specified epoch.
Parameters:
-----------
JD : type=float, a float or an array of Julian Dates
longitude : type=float, longitude of observer ... | 14bb4d621449a7fd9fa57acecb107aaa4ea61010 | 4,917 |
def _average_gradients(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list is
over individual gradients. T... | 24be75daeeb1d5878a9a481c43be440ced40a0a2 | 4,918 |
import time
def get_online_users(guest=False): # pragma: no cover
"""Returns all online users within a specified time range
:param guest: If True, it will return the online guests
"""
current = int(time.time()) // 60
minutes = range_method(flaskbb_config['ONLINE_LAST_MINUTES'])
if guest:
... | 39ad71b71e8a8caac0e6a82b7992c6229f85d255 | 4,920 |
from typing import Union
def reverse_bearing(bearing: Union[int, float]):
"""
180 degrees from supplied bearing
:param bearing:
:return:
"""
assert isinstance(bearing, (float, int))
assert 0. <= bearing <= 360.
new_bearing = bearing + 180.
# Ensure strike is between zero and 360 (... | 1fd01df40a23c52ff093c17fd5752f0609cee761 | 4,921 |
def signUp_page(request):
"""load signUp page"""
return render(request, 'app/signUp_page.html') | ae28acac27264dbb8d2f6a69afb01c6f96a08218 | 4,922 |
import csv
def read_students(path):
""" Read a tab-separated file of students. The only required field is 'github_repo', which is this
student's github repository. """
students = [line for line in csv.DictReader(open(path), delimiter='\t')]
check_students(students)
return students | e64aeb1a73fb79e91d0464d6a95e509d3cc60b94 | 4,924 |
from typing import Tuple
import torch
def get_extended_attention_mask(
attention_mask: Tensor,
input_shape: Tuple[int],
device: torch.device,
is_decoder=False,
) -> Tensor:
"""
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
Arg... | 26104733e3cc970536a11c3930866dc3d11d3583 | 4,925 |
def adler32(string, start=ADLER32_DEFAULT_START):
"""
Compute the Adler-32 checksum of the string, possibly with the given
start value, and return it as a unsigned 32 bit integer.
"""
return _crc_or_adler(string, start, _adler32) | ed4a0905b4891ee931ef08f91e92032a613caee7 | 4,928 |
def find_earliest_brs_idx(g: Grid, V: np.ndarray, state: np.narray, low: int, high: int) -> int:
"""
Determines the earliest time the current state is in the reachable set
Args:
g: Grid
V: Value function
state: state of dynamical system
low: lower bound of search range (inclu... | 234a201af98f74c41785a36b3391e23700ac80e6 | 4,929 |
def italic(s):
"""Returns the string italicized.
Source: http://stackoverflow.com/a/16264094/2570866
"""
return r'\textit{' + s + '}' | 7eb9e9629e8556e9410e4d92525dd8c06c3e25de | 4,930 |
import functools
def skip_if_disabled(func):
"""Decorator that skips a test if test case is disabled."""
@functools.wraps(func)
def wrapped(*a, **kwargs):
func.__test__ = False
test_obj = a[0]
message = getattr(test_obj, 'disabled_message',
'Test disabled'... | 56d42a1e0418f4edf3d4e8478358495b1353f57a | 4,931 |
from typing import Any
import itertools
def _compare_keys(target: Any, key: Any) -> bool:
"""
Compare `key` to `target`.
Return True if each value in `key` == corresponding value in `target`.
If any value in `key` is slice(None), it is considered equal
to the corresponding value in `target`.
... | ff5c60fab8ac0cbfe02a816ec78ec4142e32cfbf | 4,932 |
import xarray as xr
import aux_functions_strat as aux
def predict_xr(result_ds, regressors):
"""input: results_ds as came out of MLR and saved to file, regressors dataset"""
# if produce_RI isn't called on data then you should explicitely put time info
rds = result_ds
regressors = regressors.sel(time=... | 458f3f9a17d9cc16200f1eb0e20eb2a43f095ea0 | 4,934 |
async def list_features(location_id):
"""
List features
---
get:
summary: List features
tags:
- features
parameters:
- name: envelope
in: query
required: false
description: If set, the returned list will be wrapped in an enve... | 0698a63af10a70cc2ae0b8734dff61fb51786829 | 4,935 |
def shot_start_frame(shot_node):
"""
Returns the start frame of the given shot
:param shot_node: str
:return: int
"""
return sequencer.get_shot_start_frame(shot_node) | f13582040ad188b6be8217a7657ce53c145fe090 | 4,936 |
def word1(x: IntVar) -> UInt8:
"""Implementation for `WORD1`."""
return word_n(x, 1) | 0cc7e254c48596d190ccb43a0e0d3c90b18f34af | 4,937 |
def _getCols1():
"""
Robs Version 1 CSV files
"""
cols = 'Date,DOY,Time,Location,Satellite,Collection,Longitude,Latitude,SolarZenith,SolarAzimuth,SensorZenith,SensorAzimuth,ScatteringAngle,nval_AOT_1020_l20,mean_AOT_1020_l20,mean_AOT_870_l20,mean_AOT_675_l20,sdev_AOT_675_l20,mean_AOT_500_l20,mean_AOT_44... | bf3148b53effc18e212e03cf70673dc25e1d0005 | 4,938 |
from typing import Optional
from pathlib import Path
def run_primer3(sequence, region, primer3_exe: str, settings_dict: dict,
padding=True, thermodynamic_params: Optional[Path] = None):
"""Run primer 3. All other kwargs will be passed on to primer3"""
if padding:
target_start = region.... | 670f70b5b50200da5c9cd13b447a5836b748fd31 | 4,939 |
import inspect
def filter_safe_dict(data, attrs=None, exclude=None):
"""
Returns current names and values for valid writeable attributes. If ``attrs`` is given, the
returned dict will contain only items named in that iterable.
"""
def is_member(cls, k):
v = getattr(cls, k)
checks ... | ce457615ba8e360243912c3bba532e8327b8def4 | 4,940 |
def fixture_loqus_exe():
"""Return the path to a loqus executable"""
return "a/path/to/loqusdb" | 647b31e37854a5cbc8fd066c982e67f976100c03 | 4,941 |
def get_reads_section(read_length_r1, read_length_r2):
"""
Yield a Reads sample sheet section with the specified R1/R2 length.
:rtype: SampleSheetSection
"""
rows = [[str(read_length_r1)], [str(read_length_r2)]]
return SampleSheetSection(SECTION_NAME_READS, rows) | 19f3e36e34471c6bac89f2a42bdcb3f4b79c22c7 | 4,942 |
def validate(number):
"""Check if the number is valid. This checks the length, format and check
digit."""
number = compact(number)
if not all(x in _alphabet for x in number):
raise InvalidFormat()
if len(number) != 16:
raise InvalidLength()
if number[-1] == '-':
raise Inv... | e191ee9d8631dfd843276b2db7ee9699b974e555 | 4,943 |
import re
def parse_directory(filename):
""" read html file (nook directory listing),
return users as [{'name':..., 'username':...},...] """
try:
file = open(filename)
html = file.read()
file.close()
except:
return []
users = []
for match in re.finditer(r'<b... | 1b7fc5b6257b5c382f520a60c9227e8b458d482d | 4,944 |
from typing import Optional
def dec_multiply(*args) -> Optional[Decimal]:
"""
Multiplication of numbers passed as *args.
Args:
*args: numbers we want to multiply
Returns:
The result of the multiplication as a decimal number
Examples:
>>> dec_multiply(3, 3.5, 4, 2.34)
... | f7d953debc5d24c97ee274ec13683be3fda302eb | 4,947 |
import json
def get_networks():
"""
Returns a list of all available network names
:return: JSON string, ex. "['bitcoin','bitcoin-cash','dash','litecoin']"
"""
return json.dumps([x[0] for x in db.session.query(Node.network).distinct().all()]) | 755e0238463aabed0a38102ca793842dd54a6c87 | 4,948 |
def get_cache_key_generator(request=None, generator_cls=None, get_redis=None):
"""Return an instance of ``CacheKeyGenerator`` configured with a redis
client and the right cache duration.
"""
# Compose.
if generator_cls is None:
generator_cls = CacheKeyGenerator
if get_redis is None:
... | 80c25a204976492e2741e46bd79d70d0e6b62b1a | 4,949 |
import pathlib
def is_from_derms(output):
"""Given an output, check if it's from DERMS simulation.
Parameters
----------
output: str or pathlib.Path
"""
if not isinstance(output, pathlib.Path):
output = pathlib.Path(output)
derms_info_file = output / DERMS_INFO_FILENAME
... | e9a9be7e18cda3b22661f773e6bb585c833b74d6 | 4,950 |
def js_squeeze(parser, token):
"""
{% js_squeeze "js/dynamic_minifyed.js" "js/script1.js,js/script2.js" %}
will produce STATIC_ROOT/js/dynamic_minifyed.js
"""
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % bi... | 30b10b85001bbb5710584fb41469e1c36d50f086 | 4,951 |
def view_extracted_data() -> str:
"""
Display Raw extracted data from Documents
"""
extracted_data = read_collection(FIRESTORE_PROJECT_ID, FIRESTORE_COLLECTION)
if not extracted_data:
return render_template("index.html", message_error="No data to display")
return render_template("index.h... | 9eccebd4952fc3c988bfc6014d2c12944a197ac4 | 4,952 |
import json
def get_lstm_trump_text():
"""Use the LSTM trump tweets model to generate text."""
data = json.loads(request.data)
sl = data["string_length"]
st = data["seed_text"]
gen_text = lstm_trump.generate_text(seed_text=st, pred_len=int(sl))
return json.dumps(gen_text) | 9fbad3e7abcfcbbbfb5919a5c37cf607e972592e | 4,953 |
def countSort(alist):
"""计数排序"""
if alist == []:
return []
cntLstLen = max(alist) + 1
cntLst = [0] * cntLstLen
for i in range(len(alist)):
cntLst[alist[i]] += 1 #数据alist[i] = k就放在第k位
alist.clear()
for i in range(cntLstLen):
while cntLst[i] > 0: #将每个位置的数据k循环输出多次
... | 6727b41794dc2a2f826023c2a53202798dfa49ab | 4,955 |
def _FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5):
"""_FloatsTraitsBase_read_values_dataset(hid_t arg2, hid_t arg3, hid_t arg4, unsigned int arg5) -> FloatsList"""
return _RMF_HDF5._FloatsTraitsBase_read_values_dataset(arg2, arg3, arg4, arg5) | 4f2cfb17e5f0b3cfc980f51ef8e9ae8d7d38ba2c | 4,956 |
import requests
from bs4 import BeautifulSoup
import io
def TRI_Query(state=None, county=None,area_code=None, year=None,chunk_size=100000):
"""Query the EPA Toxic Release Inventory Database
This function constructs a query for the EPA Toxic Release Inventory API, with optional arguments for details such ... | 48eef06d1409dfe4404c6548435196cc95baff62 | 4,957 |
import requests
import html
def get_monthly_schedule(year, month):
"""
:param year: a string, e.g. 2018
:param month: a string, e.g. january
:return schedule: a pd.DataFrame containing game info for the month
"""
url = f'https://www.basketball-reference.com/leagues/NBA_{year}_games-{month}.h... | 1aa48abaa274166110df8dfd55b49560f72db054 | 4,958 |
import csv
import zlib
def get_gzip_guesses(preview, stream, chunk_size, max_lines):
"""
:type preview: str
:param preview: The initial chunk of content read from the s3
file stream.
:type stream: botocore.response.StreamingBody
:param stream: StreamingBody object of the s3 dataset file.
... | aa6185ed31fc4bb5d85e991702925502beff86c0 | 4,959 |
from typing import List
def make_preds_epoch(classifier: nn.Module,
data: List[SentenceEvidence],
batch_size: int,
device: str=None,
criterion: nn.Module=None,
tensorize_model_inputs: bool=True):
"""Predi... | 67cecfc6648ef4ad10531b086dab2fc9e6e2f6f3 | 4,960 |
def array_3_1(data):
"""
功能:将3维数组转换成1维数组 \n
参数: \n
data:图像数据,3维数组 \n
返回值:图像数据,1维数组 \n
"""
# 受不了了,不判断那么多了
shape = data.shape
width = shape[0]
height = shape[1]
# z = list()
z = np.zeros([width * height, 1])
for i in range(0, width):
for j in range(0, heigh... | 0b2991da94102e5ecf47d037f995b95a3fd28ac8 | 4,961 |
import json
def UpdateString(update_intervals):
"""Calculates a short and long message to represent frequency of updates.
Args:
update_intervals: A list of interval numbers (between 0 and 55) that
represent the times an update will occur
Returns:
A two-tuple of the long and short message (resp... | 35ba60e028c238f304bcf03d745865c93408b9c1 | 4,962 |
from typing import Optional
from re import T
def coalesce(*xs: Optional[T]) -> T:
"""Return the first non-None value from the list; there must be at least one"""
for x in xs:
if x is not None:
return x
assert False, "Expected at least one element to be non-None" | fe388a40ff200f9988514563d0e37d2d604317a7 | 4,963 |
def check_phil(phil, scope=True, definition=True, raise_error=True):
"""
Convenience function for checking if the input is a libtbx.phil.scope
only or a libtbx.phil.definition only or either.
Parameters
----------
phil: object
The object to be tested
scope: bool
Flag to check if phil is a... | 11a59bb25689bfc5882b8e0b0b9c2e9a5f233db0 | 4,964 |
import json
def get_ssm_environment() -> dict:
"""Get the value of environment variables stored in the SSM param store under $DSS_DEPLOYMENT_STAGE/environment"""
p = ssm_client.get_parameter(Name=fix_ssm_variable_prefix("environment"))
parms = p["Parameter"]["Value"] # this is a string, so convert to dic... | 2f5a44c7e01f87c0aff092f9fed83f0030d4f7da | 4,965 |
from datetime import datetime
def get_default_date_stamp():
"""
Returns the default date stamp as 'now', as an ISO Format string 'YYYY-MM-DD'
:return:
"""
return datetime.now().strftime('%Y-%m-%d') | 672cd98265b19da2df92c7849f1059e5988473d7 | 4,966 |
import re
def check_for_launchpad(old_vendor, name, urls):
"""Check if the project is hosted on launchpad.
:param name: str, name of the project
:param urls: set, urls to check.
:return: the name of the project on launchpad, or an empty string.
"""
if old_vendor != "pypi":
# XXX This ... | 87fc4be32cd93671b5d9fe43697d9e6918675843 | 4,967 |
import torch
def constructRBFStates(L1, L2, W1, W2, sigma):
"""
Constructs a dictionary dict[tuple] -> torch.tensor that converts
tuples (x,y) representing positions to torch tensors used as input to the
neural network. The tensors have an entry for each valid position on the
race track. For each ... | 575572e40f66c121468d547b45fa92c23f78f99f | 4,969 |
from typing import Union
from typing import Iterator
def tile_grid_intersection(
src0: DatasetReader,
src1: DatasetReader,
blockxsize: Union[None, int] = None,
blockysize: Union[None, int] = None
) -> tuple[Iterator[Window], Iterator[Window], Iterator[Window], Affine, int, int]:
"""Generate tiled ... | 847092e1a02ed446d7873658340d578248b1e80c | 4,971 |
def etapes_index_view(request):
"""
GET etapes index
"""
# Check connected
if not check_connected(request):
raise exc.HTTPForbidden()
records = request.dbsession.query(AffaireEtapeIndex).filter(
AffaireEtapeIndex.ordre != None
).order_by(AffaireEtapeIndex.ordre.asc()).al... | a79ec31c3849a7e77528d4607859f9bf77899ffb | 4,972 |
from typing import Optional
def brute_force(ciphered_text: str, charset: str = DEFAULT_CHARSET, _database_path: Optional[str] = None) -> int:
""" Get Caesar ciphered text key.
Uses a brute force technique trying the entire key space until finding a text
that can be identified with any of our languages.
... | 9b23b4b5068dd36345d6aa43f71bd307f8b24e0c | 4,973 |
def SqZerniketoOPD(x,y,coef,N,xwidth=1.,ywidth=1.):
"""
Return an OPD vector based on a set of square Zernike coefficients
"""
stcoef = np.dot(zern.sqtost[:N,:N],coef)
x = x/xwidth
y = y/ywidth
zm = zern.zmatrix(np.sqrt(x**2+y**2),np.arctan2(y,x),N)
opd = np.dot(zm,stcoef)
return opd | 4243f2c4106d5de0b7f6966cfb3244644beff100 | 4,974 |
import random
def build_voterinfo(campaign, state):
"""Render a tweet of voting info for a state"""
state_info = campaign.info_by_state[state]
num_cities = len(state_info[CITIES])
assert num_cities == len(set(state_info[CITIES])), f"Duplicate entries in CITIES for {state}."
city_ct = num_cities
effective_lengt... | a3f6b7aea9b84174ed1e825cacb38966e099c7eb | 4,975 |
def train_model(training_df, stock):
"""
Summary: Trains XGBoost model on stock prices
Inputs: stock_df - Pandas DataFrame containing data about stock price, date, and daily tweet sentiment regarding that stock
stock - String representing stock symbol to be used in training
Return value: T... | be28e84c6796bd002217ab56c85958b52fbc199c | 4,976 |
def create_test_node(context, **kw):
"""Create and return a test Node object.
Create a node in the DB and return a Node object with appropriate
attributes.
"""
node = get_test_node(context, **kw)
node.create()
return node | 21ff9931a7c6859bbe924014cb3a06b9890f7a63 | 4,978 |
def get_physical_id(r_properties):
""" Generated resource id """
bucket = r_properties['Bucket']
key = r_properties['Key']
return f's3://{bucket}/{key}' | 2cd467d9b1df72a4573d99f7a5d799f9612239c9 | 4,979 |
def entity_test_models(translation0, locale1):
"""This fixture provides:
- 2 translations of a plural entity
- 1 translation of a non-plural entity
- A subpage that contains the plural entity
"""
entity0 = translation0.entity
locale0 = translation0.locale
project0 = entity0.resource.pr... | 36c6962a69d241e395af1c7ebe16271dcaed975d | 4,980 |
def paris_topology(self, input_path):
"""Generation of the Paris metro network topology
Parameters:
input_path: string, input folder path
Returns:
self.g: nx.Graph(), Waxman graph topology
self.length: np.array, lengths of edges
"""
adj_file = open(input_path + "adj.dat", ... | 9f81e111cfe9adf265b9a3aa58390935b752f242 | 4,981 |
def _rescale(vector):
"""Scale values in vector to the range [0, 1].
Args:
vector: A list of real values.
"""
# Subtract min, making smallest value 0
min_val = min(vector)
vector = [v - min_val for v in vector]
# Divide by max, making largest value 1
max_val = float(max(vector)... | 0091deb65c67ef55b2632ac8d5ff8a15b275d12e | 4,982 |
from datetime import datetime
def validate_travel_dates(departure, arrival):
"""It validates arrival and departure dates
:param departure: departure date
:param arrival: arrival date
:returns: error message or Boolean status
"""
date_format = "%Y-%m-%dT%H:%M:%SZ"
status = True
error_m... | 41759684517daece729ba845b7afc80c6e6b01ea | 4,983 |
def xmatch_arguments():
""" Obtain information about the xmatch service
"""
return jsonify({'args': args_xmatch}) | 393e74df6900b8c4ed6f0eac82c162a7287a9b6d | 4,984 |
def rosenbrock_func(x):
"""Rosenbrock objective function.
Also known as the Rosenbrock's valley or Rosenbrock's banana
function. Has a global minimum of :code:`np.ones(dimensions)` where
:code:`dimensions` is :code:`x.shape[1]`. The search domain is
:code:`[-inf, inf]`.
Parameters
--------... | 5d89e22fde50032175b69f36a4c0031bfc07c2bb | 4,985 |
def isHdf5Dataset(obj):
"""Is `obj` an HDF5 Dataset?"""
return isinstance(obj, h5py.Dataset) | b674106e05d5f10585b58d246654987f174d2048 | 4,986 |
import numpy
def writing_height(sample_wrapper, in_air):
"""
Returns writing height.
:param sample_wrapper: sample wrapper object
:type sample_wrapper: HandwritingSampleWrapper
:param in_air: in-air flag
:type in_air: bool
:return: writing height
:rtype: float
"""
# Get the o... | fce6c0abcc65484088278eddd3bb77541725934c | 4,987 |
def simplify_index_permutations(expr, permutation_operators):
"""
Performs simplification by introducing PermutationOperators where appropriate.
Schematically:
[abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij]
permutation_operators is a list of PermutationOperators to consider.
If ... | 3a72459c9f9ee9e1f0f030fa96f5a38c0a1985c0 | 4,988 |
from typing import Set
from typing import Any
from typing import Tuple
def get_classification_outcomes(
confusion_matrix: pd.DataFrame,
classes: Set[Any],
class_name: str,
) -> Tuple[int, int, int, int]:
"""
Given a confusion matrix, this function counts the cases of:
- **True Positives** : c... | c8d84aa5d84e9405539fa40cd05101ac84eda871 | 4,989 |
def points_in_convex_polygon_3d_jit(points,
polygon_surfaces,
):
"""check points is in 3d convex polygons.
Args:
points: [num_points, 3] array.
polygon_surfaces: [num_polygon, max_num_surfaces,
max_num_points_of... | b3834ec647fcb6b156f57a36e11dd5dd22bec1d9 | 4,990 |
def _get_spamassassin_flag_path(domain_or_user):
"""
Get the full path of the file who's existence is used as a flag to turn
SpamAssassin on.
Args:
domain_or_user - A full email address or a domain name
"""
domain = domain_or_user.lower()
user = False
if '@' in domain:
u... | e29055f2cbe81dd7ad2083f5bfdc46d02b354dba | 4,991 |
def format(number):
"""Reformat the passed number to the standard format."""
number = compact(number)
return '-'.join((number[:3], number[3:-1], number[-1])) | 90ad8360ef773a9386a122d3f44870a6b371d370 | 4,992 |
def get_terms(request):
"""Returns list of terms matching given query"""
if TEST_MODE:
thesaurus_name = request.params.get('thesaurus_name')
extract_name = request.params.get('extract_name')
query = request.params.get('term')
else:
thesaurus_name = request.validated.get('thes... | b6e6810a1858de9da609b2e42b39a933ee9fbb04 | 4,993 |
from .. import sim
import __main__ as top
def createExportNeuroML2(netParams=None, simConfig=None, output=False, reference=None, connections=True, stimulations=True, format='xml'):
"""
Wrapper function create and export a NeuroML2 simulation
Parameters
----------
netParams : ``netParams object``
... | 84b3fb607ab30b17222143c46d839bab087c4916 | 4,994 |
def better_get_first_model_each_manufacturer(car_db):
"""Uses map function and lambda to avoid code with side effects."""
result = map(lambda x: x[0], car_db.values())
# convert map to list
return list(result) | 8969c23bfe4df2b1c164dca6c4f929a62de5ba2a | 4,996 |
from collections import Iterable
def _is_scalar(value):
"""Whether to treat a value as a scalar.
Any non-iterable, string, or 0-D array
"""
return (getattr(value, 'ndim', None) == 0
or isinstance(value, (str, bytes))
or not isinstance(value, (Iterable,))) | 725aa4a6002146ecb3dca3a17faa829e213cb3f7 | 4,998 |
def copy_random(x, y):
""" from 2 randInt calls """
seed = find_seed(x, y)
rand = JavaRandom(seed)
rand.next() # this will be y so we discard it
return rand | f1a1019ed7f012d83edca77ba3c7ccd2a806ee01 | 4,999 |
def build_tree(train, max_depth, min_size, n_features):
"""build_tree(创建一个决策树)
Args:
train 训练数据集
max_depth 决策树深度不能太深,不然容易导致过拟合
min_size 叶子节点的大小
n_features 选取的特征的个数
Returns:
root 返回决策树
"""
# 返回最优列和相关的信息
root = get_sp... | 5afd343436f14d9ab704636eb480d92a31d59f04 | 5,000 |
import pprint
def delete_bucket(bucket_name: str, location: str, verbose: bool) -> bool:
"""Delete the specified S3 bucket
Args:
bucket_name (str): name of the S3 bucket
location (str): the location (region) the S3 bucket resides in
verbose (bool): enable verbose output
Returns:
... | 79c225c9f8caa0d8c3431709d3f08ccaefe3fc1c | 5,001 |
import re
def generate_ordered_match_str_from_subseqs(r1,
subseqs_to_track,
rc_component_dict,
allow_overlaps=False):
"""Generates an ordered subsequences match string for the input se... | 202f228b40b73518342b1cc2419ca466626fc166 | 5,002 |
def combination(n: int, r: int) -> int:
""":return nCr = nPr / r!"""
return permutation(n, r) // factorial(r) | 6cf58428cacd0e09cc1095fb120208aaeee7cb7c | 5,003 |
def _extract_operator_data(fwd, inv_prep, labels, method='dSPM'):
"""Function for extracting forward and inverse operator matrices from
the MNE-Python forward and inverse data structures, and assembling the
source identity map.
Input arguments:
================
fwd : ForwardOperator
... | 6daded6f6df4abbd3dea105927ca39e02e64b970 | 5,004 |
from prompt_toolkit.interface import CommandLineInterface
from .containers import Window
from .controls import BufferControl
def find_window_for_buffer_name(cli, buffer_name):
"""
Look for a :class:`~prompt_toolkit.layout.containers.Window` in the Layout
that contains the :class:`~prompt_toolkit.layout.co... | 7912cc96365744c3a4daa44a72f272b083121e3c | 5,006 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.