content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def ensuredir(path):
"""
Creates a folder if it doesn't exists.
:param path: path to the folder to create
"""
if len(path) == 0:
return
if not os.path.exists(path):
os.makedirs(path) | 5,331,400 |
def get_language_titles():
""" Extract language and title from input file. """
language_titles = {}
input_file = open("resources/events/%s.tsv" % args.event).readlines()
for line in sorted(input_file):
try:
language, title = line.split('\t')[0], line.split('\t')[1].strip()
except IndexError:
language, t... | 5,331,401 |
def _find_additional_age_entities(request, responder):
"""
If the user has a query such as 'list all employees under 30', the notion of age is
implicit rather than explicit in the form of an age entity. Hence, this function is
beneficial in capturing the existence such implicit entities.
Returns a ... | 5,331,402 |
def stop_flops_count(self):
"""Stop computing the mean flops consumption per image.
A method to stop computing the mean flops consumption per image, which will
be available after ``add_flops_counting_methods()`` is called on a desired
net object. It can be called to pause the computation whenever.
"... | 5,331,403 |
def drawRectangle(x_cor, y_cor, width, height, color):
"""
Draws rectangle on the screen
"""
pygame.draw.rect(DISPLAY_SURFACE, color, (x_cor, y_cor, width, height)) | 5,331,404 |
def metrics():
"""
selected linecounts:
356 ascoltami (music player)
318 curvecalc (curve and expression editor)
279 keyboardcomposer
189 dmxserver (hardware output)
153 subcomposer
17 wavecurve (create smoothed waveforms f... | 5,331,405 |
def merge_local_and_remote_resources(resources_local, service_sync_type, service_id, session):
"""
Main function to sync resources with remote server.
"""
if not get_last_sync(service_id, session):
return resources_local
remote_resources = _query_remote_resources_in_database(service_id, sess... | 5,331,406 |
def alertmanager():
"""
to test this:
$ curl -H "Content-Type: application/json" -d '[{"labels":{"alertname":"test-alert"}}]' 172.17.0.2:9093/api/v1/alerts
or
$ curl -H "Content-Type: application/json" -d '{"alerts":[{"labels":{"alertname":"test-alert"}}]}' 127.0.0.1:5000/alertmanager
"""
alert_json=request.get_... | 5,331,407 |
def task_build():
"""build code and intermediate packages"""
if C.TESTING_IN_CI or C.DOCS_IN_CI:
return
if not (C.RTD or C.CI):
yield dict(
name="docs:favicon",
doc="rebuild favicons from svg source, requires imagemagick",
file_dep=[P.DOCS_ICON],
... | 5,331,408 |
def parse_args():
"""Process arguments"""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--train', '-t', required=True, type=str, help="Training ProteinNet data")
parser.add_argumen... | 5,331,409 |
def RefundablePayrollTaxCredit(was_plus_sey_p, was_plus_sey_s,
RPTC_c, RPTC_rt,
rptc_p, rptc_s, rptc):
"""
Computes refundable payroll tax credit amounts.
"""
rptc_p = min(was_plus_sey_p * RPTC_rt, RPTC_c)
rptc_s = min(was_plus_sey_s * RP... | 5,331,410 |
def test_load_extra_first():
"""Test that solutions that refer to a requirement with an extra before it is defined correctly
add the requirement with the extra"""
solution_repo = SolutionRepository(
os.path.join(os.path.dirname(__file__), "extra_only_solution.txt")
)
assert solution_repo.sol... | 5,331,411 |
def open_and_swap(filename, mode="w+b", buffering=-1, encoding=None, newline=None):
"""
Open a file for writing and relink it to the desired path in an atomic
operation when the file is closed without an exception. This prevents
the existing file data from being lost if an unexpected failure occurs
... | 5,331,412 |
def is_stable(A, domain='z'):
"""Determines if a linear state-space model is stable from eigenvalues of `A`
Parameters
----------
A : ndarray(n,n)
state matrix
domain : str, optional {'z', 's'}
'z' for discrete-time, 's' for continuous-time state-space models
returns
------... | 5,331,413 |
def email_sent_ipn(path: str) -> tuple:
"""
**email_sent_ipn**
Delivered ipn for mailgun
:param path: organization_id
:return: OK, 200
"""
# NOTE: Delivered ipn will end up here
if path == "delivered":
pass
elif path == "clicks":
pass
elif path == "op... | 5,331,414 |
def decode(path: str) -> str:
"""
utility fct to encode/decode
"""
return path.encode(sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) | 5,331,415 |
def db_manage():
""" Database management commands """
pass | 5,331,416 |
def load_posts_view(request):
"""Load posts view, handles asynchronous queries to retrieve more posts.
"""
import json
if request.method == 'GET':
results, start = get_more_posts(request.GET)
json_result = json.dumps({'posts': results,
'start': start
... | 5,331,417 |
def create_dataset(m, timestep, var='all', chunks=(10, 300, 300)):
"""
Create xarray Dataset from binary model data
for one time step. This also incorporates all model
grid information and dimensions, regardless of the variable selected.
Parameters
----------
m : LLCRegion
Model cla... | 5,331,418 |
def fetchnl2bash(m:Manager, shuffle:bool=True)->DRef:
"""
FIXME: Unhardcode '3rdparty'-based paths
"""
allnl=fetchlocal(m,
path=join('3rdparty','nl2bash_essence','src','data','bash','all.nl'),
sha256='1db0c529c350b463919624550b8f5882a97c42ad5051c7d49fbc496bc4e8b770',
mode='asis',
output=[promise... | 5,331,419 |
def mummer_cmds_four(path_file_four):
"""Example MUMmer commands (four files)."""
return MUMmerExample(
path_file_four,
[
"nucmer --mum -p nucmer_output/file1_vs_file2 file1.fna file2.fna",
"nucmer --mum -p nucmer_output/file1_vs_file3 file1.fna file3.fna",
"n... | 5,331,420 |
def Exponweibull(a=1, c=1, scale=1, shift=0):
"""
Expontiated Weibull distribution.
Args:
a (float, Dist) : First shape parameter
c (float, Dist) : Second shape parameter
scale (float, Dist) : Scaling parameter
shift (float, Dist) : Location parameter
"""
dist = core... | 5,331,421 |
def test_run_ml_with_segmentation_model(test_output_dirs: OutputFolderForTests) -> None:
"""
Test training and testing of segmentation models, when it is started together via run_ml.
"""
config = DummyModel()
config.num_dataload_workers = 0
config.restrict_subjects = "1"
# Increasing the tes... | 5,331,422 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up device tracker for Keenetic NDMS2 component."""
router: KeeneticRouter = hass.data[DOMAIN][config_entry.entry_id][ROUTER]
tracked = set()
@callback
... | 5,331,423 |
def authed_request_for_id(gplus_id, request):
"""Adds the proper access credentials for the specified user and then makes an HTTP request."""
# Helper method to make retry easier
def make_request(retry=True):
token = get_access_token_for_id(gplus_id)
request.headers['Authorization'] = 'Bear... | 5,331,424 |
def test_suggest_regex_for_string(input, output, expected_exception):
"""Test different strings to represent them as a regex."""
with expected_exception:
if output is not None:
assert suggest_regex_for_string(**input) == output
else:
assert suggest_regex_for_string(**inpu... | 5,331,425 |
def _bool_method_SERIES(op, name, str_rep):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
if isinstance(y, list):
y = lib.list_to_object_array(y)
... | 5,331,426 |
def get_playlist_by_id(playlist_id):
""" Returns a playlist by playlist id """
return Playlist.query.filter(Playlist.playlist_id == playlist_id).first() | 5,331,427 |
def section_cfield(xs, x_a, c_field, rmax = 60e3):
"""
extract a section of a sound speed transcet for use in xmission calculation
"""
x_i = np.bitwise_and(x_a >= xs, x_a <= xs + rmax)
return x_a[x_i], c_field[:, x_i] | 5,331,428 |
def main_cli(ctx, instance_name=None, init=False, settings=False, checkversion=False, history=False, identifier=None, websearch=None):
"""
Python client for the Dimensions Analytics API.
More info: https://github.com/digital-science/dimcli
"""
if not (identifier or websearch):
click.secho("D... | 5,331,429 |
def shared_dropout(shape, use_noise, trng, value):
"""
Shared dropout mask (pervasive dropout)
:param shape:
:param use_noise:
:param trng:
:param value:
:return:
"""
return tensor.switch(use_noise,
trng.binomial(shape, p=value, n=1,
... | 5,331,430 |
def setup_flow_assembler(gb, method, data_key=None, coupler=None):
"""Setup a standard assembler for the flow problem for a given grid bucket.
The assembler will be set up with primary variable name 'pressure' on the
GridBucket nodes, and mortar_flux for the mortar variables.
Parameters:
gb: G... | 5,331,431 |
def get_article(article_id: str, db: Session = Depends(deps.get_db),
current_user: schemas.UserVerify = Depends(
deps.get_current_user)) -> JSONResponse:
""" Return Single Article"""
data = crud_articles.get_article(article_id=article_id, db=db)
if data is None:
... | 5,331,432 |
def _get_sp_instance():
"""Create an spotify auth_manager and check whether the current user has
a token (has been authorized already). If the user has a token, then they
are authenticated -- return their spotipy instance. If the user does not have
a token, then they are not authenticated -- raise an ex... | 5,331,433 |
def get_func_global(op_type, dtype):
"""Generate function for global address space
Used as `generator(op_type, dtype)`.
"""
op = getattr(dppy.atomic, op_type)
def f(a):
op(a, 0, 1)
return f | 5,331,434 |
def klucb(x, d, div, upperbound, lowerbound=-float("inf"), precision=1e-6):
"""The generic klUCB index computation.
Input args.:
x,
d,
div:
KL divergence to be used.
upperbound,
lowerbound=-float('inf'),
precision=1e-6,
"""
l = max(x, lowerbound)
u = upperbound
while... | 5,331,435 |
def convert_pk_to_index(pk_tuples, indices):
"""
For a list of tuples with elements referring to pk's of indices,
convert pks to 0-index values corresponding to order of queryset
:param pk_tuples: list of tuples [(row_pk, col_pk), ... ]
:param indices: list of querysets
:return: list of tuples [... | 5,331,436 |
def device_path_to_str(path: Union[bytes, str]) -> str:
"""
Converts a device path as returned by the fido2 library to a string.
Typically, the path already is a string. Only on Windows, a bytes object
using an ANSI encoding is used instead. We use the ISO 8859-1 encoding to
decode the string whi... | 5,331,437 |
def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov) | 5,331,438 |
def emitir_extrato(contas, numero_conta, movimentacoes, data_inicial):
"""
Retorna todas as movimentações de <movimentacoes> feitas pela conta
com o <numero_conta> a partir da <data_inicial>
"""
historico_movimentacoes = []
if numero_conta in contas:
minhas_movimentacoes = movimentac... | 5,331,439 |
def wavelength_to_energy(wavelength):
"""
Converts wavelength (A) to photon energy (keV)
"""
return 12.39842/wavelength | 5,331,440 |
def torch_dataset_download_helper():
"""Call this function if you want to download dataset via PyTorch API"""
from six.moves import urllib
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener) | 5,331,441 |
def calculate_hash_512(filepath, verbose):
"""
SHA512 Hash Digest
"""
if verbose:
print 'Calculating hash...'
sha512_hash = hashlib.sha512()
with open(filepath, 'rb') as f:
statinfo = os.stat(filepath)
block_size = 100 * (2**20) #Magic number: 100 * 1MB blocks
... | 5,331,442 |
def _crop_after_rotation(im, angle, xres, yres, surroundings):
"""Crop image to the bounding box of bite's surroundings.
Arguments:
im: PIL.Image, rotated map part
angle: by which the map has been rotated, in degrees (counterclockwise)
xres: width of one tile in pixels
yres: height of one tile... | 5,331,443 |
def get_custom_scorer(metric, gib=True, needs_proba=False, needs_threshold=False):
"""Get a scorer from a str, func or scorer.
Scorers used by ATOM have a name attribute.
Parameters
----------
metric: str, func or scorer
Name, metric or scorer to get ATOM's scorer from.
gib: bool, opt... | 5,331,444 |
def julian_day(t='now'):
"""
Wrap a UTC -> JD conversion from astropy.
"""
return Time(parse_time(t)).jd | 5,331,445 |
def add_stop_words(dataframe: pd.DataFrame,
k_words: int) -> list:
"""
Получить список стоп-слов, которые наиболее часто встречаются в документе
:param dataframe:
:param k_words: кол-во наиболее часто повторяющихся уникальных слов
:return:
"""
split_words = dataframe['tex... | 5,331,446 |
def get_batch(data_iterator):
"""Build the batch."""
# Items and their type.
keys = ['text', 'types', 'labels', 'is_random', 'loss_mask', 'padding_mask']
datatype = torch.int64
# Broadcast data.
data = next(data_iterator) if data_iterator is not None else None
data_b = mpu.broadcast_data(k... | 5,331,447 |
def test_interruption(env):
"""With asynchronous interrupts, the victim expects an interrupt
while waiting for an event, but will process this even if no
interrupt occurred.
"""
def interruptee(env):
try:
yield env.timeout(10)
pytest.fail('Expected an interrupt')
... | 5,331,448 |
def outcomes_by_resected_lobe(directory='L:\\', filename='All_Epilepsy_Ops_CROSSTAB_Statistics_YAY_2019.xlsx',
lobes=['T Lx', 'T Lesx']):
"""
Creates the list of Gold_standard post-operative ILAE 1 at all follow up years MRNs in patients who had only
specific lobe resections.
... | 5,331,449 |
def run_experiment_rotated_mnist_SVIGP_Hensman(args, args_dict):
"""
Function with tensorflow graph and session for SVIGP_Hensman experiments on rotated MNIST data.
:param args:
:return:
"""
# define some constants
n = len(args.dataset)
N_train = n * 4050
N_eval = n * 640
N_tes... | 5,331,450 |
def search_file_for_monkeys(file_name, threshold_confidence, wav_folder, model, tidy=True, full_verbose=True, hnm=False, summary_file=False):
"""
Splits 60-second file into 3-second clips. Runs each through
detector. If activation surpasses confidence threshold, clip
is separated.
If hard-negative m... | 5,331,451 |
def register_metric(cls: Type[Metric]):
"""Registers metric under the list of standard TFMA metrics."""
_METRIC_OBJECTS[cls.__name__] = cls | 5,331,452 |
def pool(sparkdf, start_column, end_column, var):
"""
Generate pools and calculate maximum var unpooled.
:param sparkdf: Input Spark dataframe.
:param start_column: Start time column name.
:param end_column: End time column name.
:param var: Variable for which to calculate metric.
:return: A... | 5,331,453 |
def jwt_response_payload_handler(token, user=None, request=None):
"""
自定义jwt返回
def jwt_response_payload_handler(token, user=None, request=None):
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data
}
:param token:
:param... | 5,331,454 |
def query_yelp_lookup(biz_id):
""" Lookup resturant using id """
headers = {'Authorization': ('Bearer '
'w5JFtwCUKq05GlSpm8cKo51dBYDQ6r9tyzo-qRsKt4wDyB5'
'_ro6gW5gnG9hS6bvnNHNxOQLHfw7o_9S1e86nkvgcU7DQI_'
'sM6GVt9rqcq_rRYKtagQrexuH0zsU0WXYx')}
url = 'https://api.y... | 5,331,455 |
def dashboard(request, condition='recent'):
"""Dashboard"""
post_count = settings.DASHBOARD_POST_COUNT
comment_count = settings.DASHBOARD_COMMENT_COUNT
if condition == 'recent':
order = '-id'
elif condition == 'view':
order = '-view_count'
elif condition == 'like':
order... | 5,331,456 |
def read_manifest(path):
"""Read dictionary of workflows from the Packal manifest.xml file."""
workflows = {}
tree = ET.parse(path)
root = tree.getroot()
for workflow in root:
data = {"packal": True}
for child in workflow:
if child.tag == "short":
data["de... | 5,331,457 |
def _load_v1_txt(path):
"""Parses a SIF V1 text file, returning numpy arrays.
Args:
path: string containing the path to the ASCII file.
Returns:
A tuple of 4 elements:
constants: A numpy array of shape (element_count). The constant
associated with each SIF element.
ce... | 5,331,458 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensor platform."""
_LOGGER.info("setup_platform called for Webcomic")
add_devices([ComicSensor(hass, config)]) | 5,331,459 |
def split_model_name(model):
"""
Split model names by _
Takes into account packages with _ and processor types with _
"""
model = model[:-3].replace('.', '_')
# sort by key length so that nertagger is checked before tagger, for example
for processor in sorted(ending_to_processor.keys(), key... | 5,331,460 |
def dg83_setup(
ghz = 95,
lat_of_cen = 10,
cml = 20,
n_alpha = 10,
n_E = 10,
E0 = 0.1,
E1 = 10.,
nn_dir = None,
no_synch = False,
):
"""Create and return a VanAllenSetup object prepared to use the Divine &
Garrett 1983 model of Jupiter's ma... | 5,331,461 |
def test_shell_cmd_inputs_list_sep_1():
"""providing list as an additional input:, sep, no argstr"""
my_input_spec = SpecInfo(
name="Input",
fields=[
(
"inpA",
attr.ib(
type=str,
metadata={
... | 5,331,462 |
def jump_to_start(self, line_start, line_end, letter_start, letter_end) -> None:
"""
Chosen LineIndex set to start of highlighted area
"""
if line_start <= line_end:
# downward highlight or the same line
self.chosen_LineIndex = line_start
self.chosen_LetterIndex = letter_start
... | 5,331,463 |
def compute() -> int:
"""
Returns the sum of all numbers whose
sum of the factorials of all digits
add up to the number itself.
>>> compute()
40730
"""
return sum(
num
for num in range(3, 7 * factorial(9) + 1)
if sum_of_digit_factorial(num) == num
... | 5,331,464 |
def dijkstra(matrix, start=None, end=None):
"""
Implementation of Dijkstra algorithm to find the (s,t)-shortest path between top-left and bottom-right nodes
on a nxn grid graph (with 8-neighbourhood).
NOTE: This is an vertex variant of the problem, i.e. nodes carry weights, not edges.
:param matrix ... | 5,331,465 |
def is_finally_visible_segm(*args):
"""is_finally_visible_segm(segment_t s) -> bool"""
return _idaapi.is_finally_visible_segm(*args) | 5,331,466 |
def make_course_dictionary(debug=False):
"""
Make a course dictionary from VIVO contents. Key is course number
such as ABF2010C. Value is URI.
"""
from vivofoundation import vivo_sparql_query
query = """
SELECT ?x ?label ?coursenum
WHERE {
?x a ufVivo:Course .
?x ufVivo:cou... | 5,331,467 |
def get_undisbursed_principal(loan):
"""Gets undisbursed principal"""
principal = frappe.get_value("Microfinance Loan", loan, "loan_principal")
if not principal:
raise frappe.DoesNotExistError("Loan: {} not found".format(loan))
return principal - get_disbursed(loan) | 5,331,468 |
def northing_and_easting(dictionary):
"""
Retrieve and return the northing and easting strings to be used as
dictionary keys
Parameters
----------
dictionary : dict
Returns
-------
northing, easting : tuple
"""
if not 'x' and 'y' in dictionary.keys():
northing = 'l... | 5,331,469 |
def update():
""" re read the config """
sudo("supervisorctl update") | 5,331,470 |
def test_get_fgco2_fix():
"""Test getting of fix."""
fix = Fix.get_fixes('CMIP6', 'GFDL-ESM4', 'Omon', 'fgco2')
assert fix == [Fgco2(None), Omon(None)] | 5,331,471 |
def visual_encrypt(fi):
"""
Encode selected region with visual encrypt algorithm
"""
offset = fi.getSelectionOffset()
length = fi.getSelectionLength()
if length > 0:
data = list(fi.getDocument())
# Do not show command prompt window
startupinfo = subprocess.ST... | 5,331,472 |
def decode_path(name):
""" Attempt to decode path with correct encoding """
return name.decode(sys.getfilesystemencoding()) | 5,331,473 |
def save_account(account):
"""
Function that serializes the account such
that it can be saved.
"""
root_dir = "./accounts/"+account.name+"/"
if not os.path.exists(root_dir):
os.makedirs(root_dir)
with open(root_dir+account.name, "wb+") as f:
pickle.dump(account, f)
retur... | 5,331,474 |
def create_simulation_job(clientRequestToken=None, outputLocation=None, loggingConfig=None, maxJobDurationInSeconds=None, iamRole=None, failureBehavior=None, robotApplications=None, simulationApplications=None, dataSources=None, tags=None, vpcConfig=None, compute=None):
"""
Creates a simulation job.
See als... | 5,331,475 |
def affine(p, scale, theta, offset):
""" Scale, rotate and translate point """
return arcpy.Point((p.X * math.cos(theta) - p.Y * math.sin(theta)) * scale.X + offset.X,
(p.X * math.sin(theta) + p.Y * math.cos(theta)) * scale.Y + offset.Y) | 5,331,476 |
def test_interface_two_segments_noweek_nomonth(constant_days_two_segments_df: pd.DataFrame):
"""This test checks that bad-inited SpecialDaysTransform raises AssertionError during fit_transform."""
with pytest.raises(ValueError):
_ = SpecialDaysTransform(find_special_weekday=False, find_special_month_day... | 5,331,477 |
def GetMarkedPos(slot):
"""
Get marked position
@param slot: slot number: 1..1024 if the specifed value is <= 0
range, IDA will ask the user to select slot.
@return: BADADDR - the slot doesn't contain a marked address
otherwise returns the marked address
"""
curlo... | 5,331,478 |
def elslib_CylinderParameters(*args):
"""
* parametrization P (U, V) = Location + V * ZDirection + Radius * (Cos(U) * XDirection + Sin (U) * YDirection)
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param P:
:type P: gp_Pnt
:param U:
:type U: float &
:param... | 5,331,479 |
def test_no_output():
"""Makes sure that when no output flag is on, no files are created.
Should be run first so that other tests haven't created files"""
args = Arguments(
src_dir="src",
extra_data=["gbextradata"],
pkg_dir=os.path.join("tests", "gbtestapp"),
clean=True,
... | 5,331,480 |
def totaled_no_review_url(cc, sql_time_specification): # pragma: no cover
"""Counts the number of commits with no review url in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
count(in... | 5,331,481 |
def is_sat(formula, solver_name=None, logic=None, portfolio=None):
""" Returns whether a formula is satisfiable.
:param formula: The formula to check satisfiability
:type formula: FNode
:param solver_name: Specify the name of the solver to be used
:type solver_name: string
:param logic: Speci... | 5,331,482 |
def bounds(*tile):
"""Returns the bounding box of a tile
Parameters
----------
tile : Tile or tuple
May be be either an instance of Tile or 3 ints (X, Y, Z).
Returns
-------
LngLatBbox
"""
tile = _parse_tile_arg(*tile)
xtile, ytile, zoom = tile
Z2 = math.pow(2, zo... | 5,331,483 |
def make_evo_plots(x_dot, x_dot_train, x_dot_sim,
x_true, x_sim, time, t_train, t_test):
"""
Plots the true evolution of X and Xdot, along with
the model evolution of X and Xdot, for both the
training and test data.
Parameters
----------
x_dot: 2D numpy array of floats
... | 5,331,484 |
def http(func: str, arg: Tuple[str]) -> int:
"""Summary.
Args:
func (str): Path to a function.
arg (Tuple[str]): Description
Returns:
int: Description
"""
return ERGO_CLI.http(func, *list(arg)) | 5,331,485 |
def formatting(session: Session) -> None:
"""Run formatter (using black)."""
args = session.posargs or locations
session.install("black")
session.run("black", *args) | 5,331,486 |
def isMWS_bhb(primary=None, objtype=None,
gaia=None, gaiaaen=None, gaiadupsource=None, gaiagmag=None,
gflux=None, rflux=None, zflux=None,
w1flux=None, w1snr=None, maskbits=None,
gnobs=None, rnobs=None, znobs=None,
gfracmasked=None, rfracmasked=None, ... | 5,331,487 |
def bernpoly(n, z):
"""
Evaluates the Bernoulli polynomial `B_n(z)`.
The first few Bernoulli polynomials are::
>>> from sympy.mpmath import *
>>> mp.dps = 15
>>> for n in range(6):
... nprint(chop(taylor(lambda x: bernpoly(n,x), 0, n)))
...
[1.0]
... | 5,331,488 |
def sort(obs, pred):
"""
Return sorted obs and pred time series'
"""
obs = obs.sort_values(ascending=True)
pred = pred.sort_values(ascending=True)
return obs,pred | 5,331,489 |
def random_point_of_triangle(vertices):
"""Compute a random point of the triangle with given vertices"""
p, q, r = vertices
pq = q-p
pr = r-p
while True:
x = random.random()
y = random.random()
if x + y <= 1:
return p + pq*x + pr*y | 5,331,490 |
def get_minutes(hour:str) -> int:
""" Get total number of minutes from time in %H:%M .
Args:
hour (str): String containing time in 24 hour %H:%M format
Returns:
int: Returns total number of minutes
"""
t = time.strptime(hour, '%H:%M')
minutes = t[3] * 60 + t[4]
return minut... | 5,331,491 |
def get_rotation_scale_from_transformation(matrix: np.array) -> Tuple[np.array,np.array] :
"""
This function breaks the given transformation matrix into a Rotation matrix and a Scale matrix
as described in "As-Rigid-As-Possible Shape Interpolation" by Alexa et al
Arguments:
matrix : Any transformat... | 5,331,492 |
def test_read_compressed_file(compressed_file):
"""Test that wkr.open can read compressed file formats."""
with wkr.open(compressed_file, 'rb') as input_file:
data = input_file.read()
assert isinstance(data, binary_type)
assert data == BINARY_DATA | 5,331,493 |
def cls():
"""
Purpose
-------
Clears the current line in the terminal with whitespace and carriage
returns to the begining of the line.
"""
sys.stdout.write('\r' + blnk_ln)
sys.stdout.flush() | 5,331,494 |
def calc_check_digit(number):
"""Calculate the check digit."""
weights = (7, 9, 8, 6, 5, 4, 3, 2)
check = sum(w * int(n) for w, n in zip(weights, number)) % 11
return str((10 - check) % 9 + 1) | 5,331,495 |
def leave_studygroup(request):
"""
Remove a student from the list of participants of a study group.
"""
body = json.loads(request.body)
group_id = body['id']
token = body['token']
rcs = Student.objects.get(token=token).rcs
group = Studygroup.objects.get(id=group_id)
participants = ... | 5,331,496 |
def list_revisions_courses(request_ctx, course_id, url, per_page=None, **request_kwargs):
"""
List the revisions of a page. Callers must have update rights on the page in order to see page history.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param c... | 5,331,497 |
def test():
"""Just print count every five seconds to test progress"""
for n in range(0,10):
time.sleep(5)
print(n) | 5,331,498 |
def corpus():
"""循环读取语料
"""
while True:
with open(args.train_data_path) as f:
for l in f:
l = json.loads(l)
yield l | 5,331,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.