content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_actor():
"""
Add new actor
"""
data = get_request_data()
### YOUR CODE HERE ###
# creating date
cr_date = data['date_of_birth']
cr_date = dt.strptime(cr_date, '%d.%m.%Y')
cr_date = cr_date.strftime("%a, %d %b %Y %H:%M:%S" + " GMT")
# use this for 200 response code
n... | 72ee6ef0b02fe0ed8dbf2a4d119feba1ecf5a647 | 75,859 |
def _mask_k2_products(products, campaign=None, filetype='Target Pixel'):
"""Returns a mask flagging the K2 products that match the criteria."""
mask = np.array([prov.lower() == 'k2' for prov in products['provenance_name']])
if mask.sum() == 0:
return mask
# Filter on product type
mask &= np... | a5914255f2ffffa1aeb7146034a2d6e3e32e8095 | 75,861 |
def rtiInputFixture(rtiConnectorFixture):
"""
This `pytest fixture <https://pytest.org/latest/fixture.html>`_
creates a session-scoped :class:`rticonnextdds_connector.Input` object
which is returned everytime this fixture method is referred.
The initialized Input object is cleaned up at the end
of a testing... | b9fbd841e1640fb77b2991583a2b167e714a0a7b | 75,862 |
def run_cv(data_types, patient_data):
"""
Predicts samples with known outcomes via cross-validation.
Parameters:
data_types (list[tuple]): data sources to predict
patient_data (pandas.DataFrame): patient metadata
Returns:
predictions (pandas.Series): predictions for each data s... | 7eb0ebdf7c244cafeb90aebd08cc24aa38e91dc4 | 75,863 |
from typing import Optional
def Sign(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Takes the sign of a vertex
:param input_vertex: the vertex
"""
return Vertex(context.jvm_view().SignVertex, label, cast_to_vertex(input_vertex)) | 8386f678488def5e06b6276156b41db0f2213fc3 | 75,865 |
from typing import Dict
def readPopulationAgeStructured(table: pd.DataFrame) -> Dict[NodeName, Dict[Age, int]]:
"""Read a file containing population data.
Population is labelled by node ID, sex and age. Sex is currently ignored.
:param table: Population data
:return: Nested dict with age-stratified ... | 796cc5b84691c46071b369d24b6c0409f87047aa | 75,866 |
from functools import reduce
from operator import mul
def multiply(*args):
"""\
这里可以写单元测试
>>> multiply(2,3)
6
>>> multiply('baka~',3)
'baka~baka~baka~'
"""
return reduce(mul,args) | c09f240ce67192e5d079569c75e2c1d852b6d0e7 | 75,867 |
from bigflow import serde
def group_by_every_record(pvalue, **options):
"""
group by every record
"""
pipeline = pvalue.pipeline()
node = pvalue.node()
plan = node.plan()
scope = node.scope()
shuffle = plan.shuffle(scope, [node])
shuffle_node = shuffle.node(0).distribute_every()
... | 0f922da377a7fd6dee73124b048398062d82a374 | 75,868 |
def lslownie(liczba, plec='M'):
"""Liczba całkowita słownie"""
trojki = []
if liczba==0:
return u'zero'
while liczba>0:
trojki.append(liczba % 1000)
liczba = liczba // 1000
slowa = []
for i,n in enumerate(trojki):
if n>0:
if i>0:
p = _p... | cbf844abb7463f6cba8d4dba7c644876715d0366 | 75,869 |
def _check_clip_range(in_range, img):
"""
Called in clip_outliers() and rescale_intensity().
"""
lower, upper = in_range
if isinstance(lower, str) and lower.endswith("%"):
lower = float(lower[:-1])
lowerlim = np.percentile(img, lower)
elif lower is None:
lowerlim = np... | 141f5cd033677f4daf497d53dcf79755646e8ad0 | 75,870 |
def is_distributed():
"""Returns True if there is more than one processor/MPI worker and mpi4py
was imported properly."""
return _is_distributed | b7dfbdadb1d8ee3339a6021f62a3e7828f0d6bef | 75,871 |
import struct
def read_attribute(fobj, keydb):
""" Read SIGPROC {key, value} pair from open binary file object. """
key = read_str(fobj)
if key == HEADER_END:
return key, None
atype = keydb.get(key, None)
if atype is None:
errmsg = 'Type of SIGPROC header attribute \'{0:s}\' is un... | c6bd19f608192996fdc733d31197203cd8625019 | 75,872 |
def pell_solve_2(D, m):
"""
Algorithm 2 Pell Equation Solver 2
Input: D ∈ ZZ, m ∈ ZZ \ {0} : D ≤ m^2, D is not a perfect square
Output: all fundamental solutions (x, y) : x^2 - Dy^2 = m
"""
assert m != 0
assert D <= m**2
assert not is_square(D)
u, v = pell_solve_1(D, 1)[0]
if m ... | b5b9d8e1bd63ea62667c56f6f4f4acc26646d853 | 75,873 |
def unfreeze_net(net):
"""
Unfreezing all net to make all params trainable
Args:
net: net to unfreeze
Returns:
unfreezed net
"""
print("SystemLog: Unfreezing all net to make all params trainable")
for p in net.parameters():
p.requires_grad = True
return net | a3deb31271c34c072c59f609f6520a29be8979ed | 75,874 |
def export_template(template, metadata, base_url):
"""Generates a Project export from the ``Template`` and ``metadata``
- Gets the skeleton from the template HTML
- Removes any Butter reference
- Imports the plugin from the template config file
- Adds popcorn functionality from the metadata.
"""... | bfc4575c77d957eab815bdae3c39976ea4c62c1b | 75,875 |
def reproject_points(pts, in_crs, out_crs):
"""
Reproject a set of point from input_crs to output_crs.
:param pts: Input points to be reprojected. Must be of shape (2, N), i.e (x coords, y coords)
:type pts: list, tuple, np.ndarray'
:param in_crs: Input CRS
:type in_crs: rasterio.crs.CRS
:p... | e1e9b232e9101a734858664449853c853637019a | 75,876 |
def ground_truth_rotation(ground_truth, current_point):
"""
Returns the found orthogonal matrix R that minimizes the distance between
the given point and ground truth in Frobenius norm.
"""
dim = ground_truth.ravel().shape[0]
zeros = np.zeros(dim).reshape((-1, 1))
ground_truth = ground_trut... | d01db15b41bae6f01c775a66bb0fc742598d1acd | 75,877 |
def context_processor():
"""Now forms will be available globally across all jinja templates"""
login_form = LoginForm()
signup_form = UserAddForm()
classes = ["fa fa-user","fa fa-paper-plane","fa fa-lock","fa fa-check-circle"]
return dict(login_form=login_form,signup_form=signup_form,classes=classe... | 0f13fb581216795b477ba7689f2342b25811fe32 | 75,878 |
def _muuid_to_mselectionlist(uid):
"""
:type uid: MUuid
:rtype: MSelectionList
"""
sel = MSelectionList()
sel.add(uid)
return sel | c0b171c02c715fbe19475850706f743a6ae05299 | 75,879 |
def softmax(x):
"""Calculates the softmax for each row of the input x.
Your code should work for a row vector and also for matrices of shape (n, m).
Argument:
x -- A numpy matrix of shape (n,m)
Returns:
s -- A numpy matrix equal to the softmax of x, of shape (n,m)
"""
### START CODE ... | 3ab7294314c3c5fd46dc7d78380dd8750293264c | 75,880 |
def _computer_added(data):
"""Return a formatted Slack message for the 'ComputerAdded' event.
:param dict data: The ``event`` data from a Jamf Pro webhook.
:returns: Formatted Slack message.
:rtype: dict
"""
return _message(
'A new computer has been added!\n'
'*ID:* {} ... | 08cc3fba9449ed8560ab6c8f4395e9c07f0596a9 | 75,881 |
from datetime import datetime
def jy_instrument_industry(order_book_ids, date=None, level=1, expect_df=False, market="cn"):
"""获取股票对应的聚源行业
:param order_book_ids: 股票列表,如['000001.XSHE', '000002.XSHE']
:param date: 如 '2015-01-07' (Default value = None)
:param level: 聚源等级,0, 1, 2, 3, 'customized' (Defaul... | 79589a23cc6c80a9290fa2b9d994cc5f47bc352a | 75,882 |
def generate_roommates_malasym_votes(num_agents: int = None, params=None):
""" Mallows on top of Asymmetric instance """
votes = [list(range(num_agents)) for _ in range(num_agents)]
votes = [rotate(vote, shift) for shift, vote in enumerate(votes)]
if 'norm-phi' not in params:
params['norm-phi... | d9ec8dfdaac3b7b1565f9c2fb5388c50f337f03c | 75,883 |
from datetime import datetime
import random
def random_datetime(min_year: int = 1900, max_year: int = 2025) -> Datetime:
"""Generate a random date between the min max dates.
Args:
min_year (int): Optional. Don't generate a date before this year.
max_year (int): Optional. Don't generate a date... | d83bc2bf76c6b7fb2f1e129eb4126d7f9313c7db | 75,884 |
def dynamic_dataset(iterated):
"""Implementartion of smart tf.data.Dataset epoch wrapping.
The function checks if the input is a tf.data.Dataset and if so then wraps it
so that for each element it returns it also returns the current epoch the
dataset iteration is in, for two epochs. If the input is not a
tf... | 79b0d62476167c7df7c23a1d21021235bd8400ec | 75,885 |
import binascii
def base64(data):
"""
Get base64 string (1 line) from binary "data".
:param (bytes, bytearray) data: Data to format.
:raises TypeError: Raises an error if the data is not a bytearray of bytes
instance
:return str: Empty string if this failed, otherwise the base64 encoded
... | a51e138beddb788c248c5f2423b3fde2faacdb63 | 75,886 |
def calc_hf_energy(D, hf):
""" Computes the expectation value for Hartree-Fock energy
Uses the expression
E[Φ] = Σ_iΣ_αβ C*_αβ C_iβ ⟨ϕ_α |h_0| ϕ_β⟩
+ 1/2 ∑_ij∑_αβγδ C*_iα C*_jβ C_iγ C_jδ ⟨ϕ_αϕ_β |v| ϕ_γϕ_δ⟩
"""
E = np.einsum('ab,ab->', D, hf.h) + 0.5 * \
np.einsum('ag,b... | 16ba3980bc50e5dd463176e41bad83213c4a99f1 | 75,887 |
def get_device_type_id(name):
"""
Returns the ATCADeviceType value based on the device name
"""
devices = {'ATSHA204A': 0,
'ATECC108A': 1,
'ATECC508A': 2,
'ATECC608A': 3,
'UNKNOWN': 0x20}
return devices.get(name.upper()) | ace634d05ffefbbc668b7d87ceef65e073806ee7 | 75,889 |
def UNetWide48(length, n_channel=1):
"""
Wider U-Net with kernels multiples of 48
Arguments:
length {int} -- length of the input signal
Keyword Arguments:
n_channel {int} -- number of channels in the output (default: {1})
Returns:
keras.model -- created mode... | 89c837cefaf5d8ef2865b554df2a29544cb18431 | 75,891 |
def top(__opts__=None, grains=None, **kwargs):
""" The main entry point for the external_tops extension
"""
path = __opts__['master_tops']['toast']['path']
grains = grains if grains else {}
toaster = toast.Toaster(path, grains)
return toaster.states() | d47869e515af9b4f21aa8197c3ed7460fd4f133b | 75,892 |
import datasets
import hashlib
def fetch(dataset="mi", datadir=datadir):
"""Fetch example dataset.
If the requested dataset is not found in the location specified by
`datadir`, the function attempts to download it.
Parameters
----------
dataset : str
Which dataset to load. Currently ... | 1b1c241082c1421de353f20c5c5f3bd577d86961 | 75,893 |
def split_name_version(script_name):
""" 返回分割的脚本名称,版本。"""
name_version = script_name.rsplit('-', 1)
if len(name_version) == 1:
name, version = name_version[0], None
else:
name, version = name_version
try:
version = float(version)
except ValueError:
... | 7ca30aa26eb07faa75f206574d083c7f13f89625 | 75,894 |
def native_word(word: str, encoding="UTF-8"):
"""
:param word:
:param encoding:
:return:
"""
if not is_py3:
return word.encode(encoding)
else:
return word | a8ce6762f083a6d8bd6cd4c7f7731b24648e0506 | 75,896 |
from typing import Any
import json
def rawdata() -> Any:
"""rawdata"""
print('rawdata')
raw_data = lib.read_raw_no_header(RAW_DATA_FILENAME)
json_payload = json.dumps(raw_data.to_records().tolist()) #type:ignore
return Response(json_payload, mimetype='application/json') | cc06cb44443e040e2ec8f6a3980796a2b7bf6660 | 75,897 |
def checkMgtKeyInUse(request):
"""
파트너가 전자명세서 관리 목적으로 할당하는 문서번호의 사용여부를 확인합니다.
- 최대 24자, 영문 대소문자, 숫자, 특수문자('-','_')만 이용 가능
- https://docs.popbill.com/statement/python/api#CheckMgtKeyInUse
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 문서번호, 1~24자리, (영문,숫자,'-','_')... | 264422b0f6ec1aa0826d4ace8a06481d8f4ee2b1 | 75,898 |
import time
def set_time_stamp(actual_log_size, log_file):
"""
Write the time stamp for each sample of cpu performance to the file
:param actual_log_size: Number of
:param log_file: log_file_pointer
:return:
"""
if(log_file):
time_stamp = "[ " + str(time.time()) + " ]\n"
lo... | 668b40b3a3b689cb96e483b74dd38f517b3cc0e1 | 75,899 |
def _sort_fnames(fnames):
"""Sort fnames based on date.
Args:
fnames (list of str): a list of fnames.
Returns:
list of str: a list of sorted fname.
"""
dates = list(map(lambda fname: _get_date(fname), fnames))
fnames = [fnames[i] for i in np.argsort(dates)]
return fname... | af798bbc61554536fdad26b2383dfb8de290b581 | 75,900 |
def _get_state_names():
"""Access Vote Smart API and return generator of all stateIds."""
# Use Vote Smart API call counter to track the number of queries we are doing each day
vote_smart_api_counter_manager = VoteSmartApiCounterManager()
vote_smart_api_counter_manager.create_counter_entry('State.getSta... | 364522d41a1da97561bc523e3bbb35ddc31e72ef | 75,901 |
def average_by_degeneracy(imag_self_energy, band_indices, freqs_at_gp):
"""Take averages of values of energetically degenerated bands."""
deg_sets = degenerate_sets(freqs_at_gp)
imag_se = np.zeros_like(imag_self_energy)
for dset in deg_sets:
bi_set = []
for i, bi in enumerate(band_indice... | da51927953d94f54614cff7dc593dfea046046c3 | 75,902 |
from typing import Type
def get_type(type_: Type[_T]) -> TypeInfo[_T]:
"""Retrieve the type information previously registered with :func:`register_type`.
It returns the last type info registered that is a superclass of `type_` (according
to ``issubclass``.
Raises
------
TypeError
if ... | c15f343373aaaefad5b7e09e61cdf1f710c7c9b1 | 75,903 |
import typing
import timeit
import itertools
def auto_arima(x,
max_p: int = 5,
max_d: int = 2,
max_q: int = 5,
max_P: int = 2,
max_D: int = 2,
max_Q: int = 2,
max_order: int = 5,
m: int = 0,
... | 4278c7958c7df529c76c1cbbe398d048ac4cbd2e | 75,904 |
def RotorAndMagnetsDesign(main):
"""Definition of the rotor and magnets design on ANSYS.
Args:
main (Dic): Contains the parameters of the rotor and magnets design.
Returns:
Dic: The same input dont modified only is readed by the following lines.
"""
# oEditor definition
oEdito... | 03c83eaf8ca28514cf836119ee45c7befd4fed7d | 75,905 |
import collections
def findSingletonWords(text):
"""
Splits the string |text| by whitespace and returns the set of words that
occur exactly once.
You might find it useful to use collections.defaultdict(int).
"""
# BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate... | 7a10ac5c134973a21f9148f6ade7c42c753d83c7 | 75,906 |
def create_arrow(origin=[0, 0, 0], end=None, color=[1, 0, 0], vec=None):
"""
Creates an arrow from an origin point to an end point,
or create an arrow from a vector vec starting from origin.
Args:
- end (): End point. [x,y,z]
- vec (): Vector. [i,j,k]
"""
scale = 10
Ry = Rz =... | fd166afce8e37116b990af26680bb9b856c76320 | 75,907 |
import time
def _detect_thread_time():
"""
Return a per-thread CPU timer function if possible, otherwise
a per-process CPU timer function, or at worse a wall-clock timer.
"""
for func in [_native_thread_time, _linux_thread_time, _native_process_time]:
try:
func()
re... | 914e34f91ffcca3759b65ba4fa7bbd63e8864835 | 75,908 |
def get_exp_data(diff_fname):
"""
Parse genes with differential expression score.
The file expects genes with a score in a tab delimited format.
"""
gene_exp_rate=dict()
dfh=open(diff_fname, "rU")
for line in dfh:
parts=line.strip('\n\r').split('\t')
try:
float(pa... | b376f9e8f42ed2e1f3c0209696de7e85b8bed082 | 75,909 |
import struct
def readhtk_segment(file, start, end, return_parmKind_and_sampPeriod=False):
""" Read segment from htk feature file
Input:
file - file name or file-like object alowing to seek in the file
start, end - only frames in the range start:end are extracted.
If start is nega... | 52b6d88037897c4c66777d03a553336e3855f93f | 75,910 |
def find_isolated_nodes(graph):
""" returns a list of isolated nodes. """
isolated = []
for node in graph:
if not graph[node]:
isolated += node
return isolated | 8050efa8644016878f898ad6276c66a14681b9e2 | 75,911 |
import time
def timestamp() -> float:
"""
Returns fractional seconds of a performance counter.
It does include time elapsed during sleep and is system-wide
Note: The reference point of the returned value is undefined,
so that only the difference between the results of two calls is valid.
Ret... | e2c4d8c06d8d07ca67ec4f857a464afde19b6c2a | 75,912 |
def resize_psf(psf, shape):
"""Resize centered (0,0) psf to larger shape"""
psf_extended = np.pad(psf, ((0, shape[0] - psf.shape[0]), (0, shape[1] - psf.shape[1])),
mode='constant', constant_values=0.)
return psf_extended | c8b67660523ef9b34c0ff077ea0ecc74b22c7efb | 75,913 |
def do_simulation_step(old_grid):
""" Run a step of the cellular automaton. """
height = len(old_grid)
width = len(old_grid[0])
new_grid = create_grid(width, height)
for x in range(width):
for y in range(height):
alive_neighbors = count_alive_neighbors(old_grid, x, y)
... | 5c8dbf46fe1b4d577ff3034c0d6472af6e7cfb37 | 75,914 |
def modulate_pulse(pulse, space=TIMESTRETCH, dco=0):
"""
Perform steps 1 and 2 of transmission. space is an integer corresponding
to the number of samples to stretgth the pulse, and dco is the constant
offset to use in amplitude modulation (ie, mls(t) * (dco + cos(t))).
"""
pulse = stretch(pulse... | 7ff2b1a67dfb572c34642de4a3623e805f527373 | 75,915 |
import psutil
def MAExecutorMP(obj, file_name, collection_name, max_threads=None):
"""
Function to call the parallel insertion of data by chunks
using multiprocessing module.
Keyword arguments:
obj -- Object from class MABase
max_threads -- total number processors to use in parallel
"""
... | 4446b047bd7414720a017ea6d57a8f861fac942f | 75,916 |
def get_selected_elements():
"""Return Selected Elements as a list[]. Returns empty list if no elements are selected.
Usage:
- Select 1 or more elements
> selected_elements = get_selected_elements()
> [<Autodesk.Revit.DB.FamilyInstance object at 0x0000000000000034 [Autodesk.Revit.DB.FamilyInstance]>... | ee351976d22b639a8669f1758401ea59f0330467 | 75,918 |
def detail(probe):
""" returns list of data we have for this probe from wolfram alpha
url = /<probe_name>
ie
</Cassini>
"""
return get_detail(probe), 200 | b8c321725d54d0e220545e30d687488e026eb28a | 75,919 |
def verify_user_prediction(user_inputs_dic: dict, correct_definition_dic: dict):
"""
Verifies user prediction json against correct json definition
returns true if correct format, false if not
"""
if user_inputs_dic.keys() != correct_definition_dic.keys():
return False
for user_key, use... | de1d2b579ab312929f64196467a3e08874a5be42 | 75,921 |
def select_runner(name):
"""
Return runner based on name ( worker or timer ) and settings.TASK_RUNNER.
"""
mapper = {
'block': {'worker': b_worker, 'timer': b_timer},
'uwsgi': {'worker': u_worker, 'timer': u_timer},
'celery': {'worker': c_worker, 'timer': c_timer},
'threa... | 5c096375c08c4f14246968859c244f5024c3cd7c | 75,923 |
from typing import Optional
from typing import Union
from typing import List
from typing import Dict
from typing import Any
def sql(
query: str,
index_col: Optional[Union[str, List[str]]] = None,
globals: Optional[Dict[str, Any]] = None,
locals: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) ->... | 3bc612d70688c0f5f385f258121bd9ffacce95ec | 75,924 |
import scipy
def mle_phases(seeds, phases, poly_mesh=None, verif_mask=None):
"""Get maximum likelihood estimators (MLEs) for phases
This function finds distributions in the list of phases and computes the
MLE parameters for those distributions. The returned value is a list of
phases with the same len... | ebda64000ab0131390083e02f861642b3a896ed1 | 75,926 |
import requests
from bs4 import BeautifulSoup
def search_game_id(search_term, all_results=False):
"""Return Dataframe of game ids of the search term from Steam's search result page.
Args:
search_term (str): Game name to search.
all_results (bool, optional): Whether to return all games result... | cbc70fba7aa8539e0de7eea268d8c482357539bc | 75,928 |
def matmul(x, y, transpose_x=False, transpose_y=False, alpha=1.0, name=None):
"""
Applies matrix multiplication to two tensors.
Currently, the input tensors' rank can be any, but when the rank of any
inputs is bigger than 3, this two inputs' rank should be equal.
The actual behavior depends on the... | e6c233830b8f175fdc613297065f3f376853afe8 | 75,929 |
def _maybe_format_css_class(val: str, prefix: str = ""):
"""
Create a CSS class name for the given string if it is safe to do so.
Otherwise return nothing
"""
if val.replace("-", "_").isidentifier():
return f"{prefix}{val}"
return "" | c5c615b9e0894807a020186cdade9c031f904c06 | 75,930 |
def oplist_commutation_grad(C, op_list):
"""
Compute the gradient of the operator commutativity constraint for a list of pairs of operators
Can be used with a list of descriptor multiplication operator
Parameters
---------------------
C : (K2,K1) Functional map
op_list : list of tuple( (K... | 719bbe764ad5c38b42219e19232aa6c0deca66cd | 75,931 |
def canStartSisScan(measuremode):
"""Check whether the SIS detector is ready for a measurement of the
specified type. Wait for up to the doppler's maxacqdelay just in case the
doppler is still adjusting."""
if session.mode == SIMULATION:
return True
doppler = getDoppler()
sis = getSisI... | 105468f93b76496bf229d929c5ae20763402298b | 75,933 |
def index(request):
"""Главная страница."""
template = 'posts/index.html'
title = 'Последние обновления на сайте'
posts = Post.objects.all()[:POST_COUNT]
context = {
'title': title,
'posts': posts,
}
return render(request, template, context) | 86893310f437510bef9f6f0d37d01ba05df3e6ea | 75,934 |
import math
def bd2gcj(bd_lat, bd_lng):
"""
百度转GCJ-2
:param bd_lat:
:param bd_lng:
:return:
"""
if out_of_china(bd_lat, bd_lng):
return bd_lat, bd_lng
x = bd_lng - 0.0065
y = bd_lat - 0.006
z = math.hypot(x, y) - 0.00002 * math.sin(y * math.pi)
theta = math.atan2(y... | 0ac035a30d22b2b498cb1ead0af9592afbe6a22f | 75,935 |
def build_dataset_storage_manager() -> DatasetStorageManager:
"""Factory function"""
remote_data_dir = gs_url.build_raw_data_dir()
local_data_dir = raw_data_dir()
return DatasetStorageManager(remote_data_dir, local_data_dir) | 57194f855ebd2023030aa937847ed44dfec43995 | 75,936 |
def elliptical_arc_to_cubic_bezier(x1, y1, rx, ry, phi, fA, fS, x2, y2):
"""Generate cubic bezier points to approximate SVG elliptical arc.
See: http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
"""
# Out of range parameters
# See: https://www.w3.org/TR/SVG11/implnote.html#ArcOutOfRan... | 477a39c093a45e2ca8c1e0b8d1d031dfecca703b | 75,937 |
import string
def rhyme_codes_to_letters(rhymes, unrhymed_verse_symbol="-"):
"""Reorder rhyme letters so first rhyme is always an 'a'."""
sorted_rhymes = []
letters = {}
for rhyme in rhymes:
if rhyme < 0: # unrhymed verse
rhyme_letter = unrhymed_verse_symbol
else:
... | f0cbeac514be1f67e2487cf1fe267445a89d1485 | 75,938 |
def get_elasticsearch():
"""Devuelve la conexión a Elasticsearch activa para la sesión
de flask. La conexión es creada si no existía.
Returns:
Elasticsearch: conexión a Elasticsearch.
Raises:
data.DataConnectionException: En caso de ocurrir un error de
conexión con la capa ... | a30d3ee976f0fb0e71bc4225730c238dece34878 | 75,939 |
def ListMessagesMatchingQuery(service, user_id, query=''):
"""List all Messages of the user's mailbox matching the query.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
query: St... | 28d22e18c6da9d068a144b5373f79be36d67a1bc | 75,941 |
def pt2(t, K, T):
""" time-domain solution/formula for
a second-order/pt2 system with
critical damping, d = 1, T = T1 = T2
Args:
t (float): time
K (float): gain
T (float): time-constant
Returns:
float: f(t)
"""
return K * (1 - np.exp(-t/T) - ((t/T) * np.exp(-t/T))) | c1ea56247da5b0e2637ccacddc219ff77196f025 | 75,943 |
def load(path, tc=TkContext.implicit):
"""load CoxProportionalHazardsModel from given path"""
TkContext.validate(tc)
return tc.load(path, CoxProportionalHazardsModel) | 7083607a9233b8950e9e7e544f625988730c8284 | 75,944 |
from .source import importable, getname
from io import BytesIO as StringIO
from StringIO import StringIO
def dumpIO_source(object, **kwds):
"""write object source to a buffer (instead of dill.dump)
Loads by with dill.temp.loadIO_source. Returns the buffer object.
>>> f = lambda x:x**2
>>> pyfile = dill.... | 9a6a82c17d92bae7168646fee0dcf0010b1daa50 | 75,945 |
def get_option_value(section_name, option_name):
""" Takes two str and returns the option as string, exceptions are NoOptionError and NoSectionError"""
return (SAMBA_CONFIG_PARSER.get(section_name, option_name)) | cdf70f92c9e67818ece17d7c20b9bba88a0b7c05 | 75,946 |
from typing import Any
def fct_drop(_f: ForcatsType, only: Any = None) -> Categorical:
"""Drop unused levels
Args:
_f: A factor
only: A character vector restricting the set of levels to be dropped.
If supplied, only levels that have no entries and appear in
this vector... | ce4de31e8343b0387571cb505d860dfafa7ce162 | 75,947 |
import io
def _calc_flux_from_coeffs(conf, frequency, bandwidth=1, time=0):
"""Return the flux of a calibrator at a given frequency.
Uses Perley & Butler ApJS 204, 19 (2013).
"""
coefftable = conf["CoeffTable"]["coeffs"]
fobj = io.BytesIO(standard_byte(coefftable))
table = Table.read(fobj, fo... | 489fb7caabb5960ed3584dca0d34eec2c29f76fa | 75,948 |
def cacheAnnouncement():
"""Create Announcement & assign to memcache; used by
memcache cron job & putAnnouncement().
"""
confs = models.Conference.query(ndb.AND(
models.Conference.seatsAvailable <= 5,
models.Conference.seatsAvailable > 0)
).fetch(projection=[models.Conference.name])
... | 3fdd760695630195f37460b556eaa9a6135d1295 | 75,949 |
def _render_dd(node: RenderTreeNode, context: RenderContext) -> str:
"""Render the definition body."""
tight_list = all(
child.type != "paragraph" or child.hidden for child in node.children
)
marker = ": "
indent_width = len(marker)
context.env["indent_width"] += indent_width
try:
... | 440e2ca0451844ac0bd065c8e4c8b3af86258cc3 | 75,950 |
def display_domain_limits(sender, user, domain, **kwargs):
"""Display resources usage for domain."""
if parameters.get_admin("ENABLE_DOMAIN_LIMITS") == "no":
return []
return [{
"column": "right",
"template": "limits/resources_widget.html",
"context": {
"limits": ... | 820bfc2867163a6317bec0ce2aedd144222068aa | 75,951 |
import re
def parse_name(filename):
"""
Percent is not digit! Also it can be str('na').
"""
# Search original TIFF name and human labeling index
# example: `20150126-145740[35].tif`
match = re.search(r"(^.+)\[(.+(?=\]))", filename)
identifer = match.group(1) # 20150126-145740
percent ... | 6353c725d6bd761daefede55e84edb8e23595ea7 | 75,952 |
def valid_notification_recipient(request):
"""
Recipients must exist, author and recipient must be different users.
:param request:
:return:
"""
_tn = Translator(get_language_from_cookie(request))
if not valid_user(request):
add_error(request, 'Not logged in', _tn.get(_.notLoggedIn)... | d7407c3b04e4981019b7f3aa2fa8f4094ff06b87 | 75,953 |
def ds1():
"""Small plain multi-dimensional coords xr.Dataset."""
return xr.Dataset(
{"air": (("lon", "lat"), [[0, 1, 2], [3, 4, 5], [6, 7, 8]])},
coords={"lon": [1, 3, 4], "lat": [5, 6, 7]},
) | fd767e613bfe993a02738ae6b9f38cb51f11f0e9 | 75,954 |
def create_resource_s3(aws_access_key_id, aws_secret_access_key):
"""
returns an S3 resource
"""
return boto3.resource("s3", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) | ba473fdcd562b56c88f988478dc81cbe6380e783 | 75,955 |
def waitOnJobName(jobName, maxWaitForLaunch=None):
"""Waits on the given job name to enter and then leave the queue.
@type jobName: str
@param jobName: Full name of the job
@type maxWaitForLaunch: int
@param maxWaitForLaunch: (Optional) The maximum number of seconds to wait
... | d4a589e10442cda41a582fbf68e440cef6839821 | 75,956 |
def format_isodate_for_user_timezone(value):
"""
Format the provided ISO date time string for human friendly display taking into user timezone
specific in the config.
"""
config = get_config()
timezone = config.get('cli', {}).get('timezone', 'UTC')
result = format_isodate(value=value, timezo... | 0bfc427eddf205769815b6bff8c8ab35c1bcf81f | 75,957 |
def to_days(astring, unit):
""" No weeks in QUDT unit library: days or years """
factors = {
"week": 7.0, "weeks": 7.0,
"Week": 7.0, "Weeks": 7.0,
"day": 1.0, "Day": 1.0,
"days": 1.0, "Days": 1.0,
... | b3cb66d0db77c394aa932aba8200c116f7eae6ae | 75,959 |
def get_sorties():
"""Get today's sortie missions.
Return a formatted string which contains today's sorties.
"""
try:
ws = get_worldstate()
except BaseException:
return '[ERROR] 获取世界状态失败'
sorties = ws['Sorties'][0]['Variants']
sortie_level = ['50-60', '65-80', '80-100']
... | 3d4f7cb167e6c6456a9a835ef3e07c66fc56e641 | 75,960 |
def get_data_loaders(data_config, collate_fn):
"""Get data loaders for training and validation.
Args:
data_config (dict): Data configuration.
collate_fn (callable): Collate function.
Returns:
dict: Data loaders.
"""
data_loaders = {}
for phase in ["train_no_dev", "dev"]... | d69b014fc8ca3cdb532701e12127558fc8b5cced | 75,961 |
def _toolkits_select_columns(dataset, columns):
"""
Same as select columns but redirect runtime error to ToolkitError.
"""
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise Tool... | d3b6a35e743fa9ad181edbf01a4eaba1e127fad1 | 75,962 |
def HighlightAlignedHtml(hyp, ref, err_type):
"""Generate a html element to highlight the difference between hyp and ref.
Args:
hyp: Hypothesis string.
ref: Reference string.
err_type: one of 'none', 'sub', 'del', 'ins'.
Returns:
a html string where disagreements are highlighted.
Note `hyp... | 057358da926a4689d31d518bdb406a8a4d301084 | 75,963 |
def get_most_popular_authors():
"""Connects to DB, executes the SQL query (view) most_popular_authors_view
and returns the results. most_popular_authors_view describes most
popular article authors of all time.
Attributes: None
Returns: Set of rows
"""
db, cursor = dbconnect()
... | 45fc9409842a7939c110cd3320d7cb0c90a88dc8 | 75,964 |
def index(username):
"""
List all workflows from the master database.
"""
try:
dashboard = Dashboard(g.master_db_url)
args = __get_datatables_args()
if request.is_xhr:
count, filtered, workflows, totals = dashboard.get_root_workflow_list(
**args
... | 608f315593ff6c41652ca24c377084bb3c10efd9 | 75,965 |
def get_text(soup, file_path):
"""Read in a soup object and path to the soup source file,
and return an object with the record's text content"""
text = ""
text_soup = soup.find('div', {'id': 'Text2'})
for o in text_soup.findAll(text=True):
text += o.strip() + "\n"
return {
"text": text
} | 764d3751742584c657613f5c2d00ef544a060a1d | 75,966 |
def get_item_from_list_by_key_value(items, key, value):
"""Get the item from list containing sequence of dicts."""
for item in items:
if item[key] == value:
return item
return None | fcf70b8fccebfc2995fb4fec903559bc587b4576 | 75,969 |
def list_to_string_with_comma(thing):
"""Input a list, returns every item in the list as a string with commas in between"""
string = ""
for item in thing:
string += str(item) + ','
return string[:-1] | a7fff928137c3f7041b030c1fe4dd099f0ff8ca2 | 75,970 |
def read_bytes(buf, size):
"""
Reads bytes from a buffer.
Returns a tuple with buffer less the read bytes, and the bytes.
"""
res = buf[0:size]
return (buf[size:], res) | e0f270540dcfceed86805231424e959e361b1789 | 75,971 |
def try_section(line):
"""
Checks to see if the given line is a section. If so return the section
name, otherwise return 'None'.
"""
# leading spaces were stripped when checking for comments
if not line.startswith('['):
return None, False, []
section, delim, templates = line.partiti... | 30a1043651e4a8ce3949d2d13d64c8310d5d8336 | 75,972 |
import json
def read_geo_info(file_path):
"""
Reads geographic point and region infomation from a json containing
individual locations and regions.
Parameters:
file_path (str) : path to the json file
Return:
dictionary with geographic info
"""
with open(file_path) as json... | d4e8b34bee16183ac535c146e4f9b6026ed57b7d | 75,973 |
def complete_e(words, postags, child_dict_list, word_index):
"""
完善识别的部分实体
"""
child_dict = child_dict_list[word_index]
prefix = ''
if child_dict.has_key('ATT'):
for i in range(len(child_dict['ATT'])):
prefix += complete_e(words, postags, child_dict_list, child_dict['ATT'][i]... | bc87673e3c045a4a102587ec5243dc563d58338b | 75,974 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.