content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _check_union(value, expected_type, path, context):
"""Checks `value` to a value with any of the types in `expected_type`."""
for type_option in get_generic_type_args(expected_type):
try:
return _convert_value(value, type_option, path, context, convert=False)
except TypeError:
... | 3bec745ccb74761f3acd1b59d82be74812de1a22 | 58,367 |
from OpenGL.arrays import vbo
def ca(ntracers):
"""Initialize position, color and velocity arrays we also make Vertex
Buffer Objects for the position and color arrays"""
pos, col, time, props = ca_np(ntracers)
#print timings
#create the Vertex Buffer Objects
pos_vbo = vbo.VBO(data=pos, u... | 16c3f156045d2e2884ce26f0b2bc52687bfbe948 | 58,368 |
def expected_ini_dict() -> DictType:
"""Get the expected dictionary - content of the fixture file."""
return {
"databases.postgres": {
"user": "admin",
"password": "admin",
"host": "localhost",
"port": "5432",
"schema": "public",
},
... | 8a34601c7aa2e40bd4fb2304b10717755a2cce7b | 58,369 |
from typing import Tuple
import logging
async def mark_next_person(queue_array: list) -> Tuple[list, int]:
"""Mark next person in the queue (transfers current_turn to them).
Parameters
----------
queue_array : list
This array represents the queue
Returns
-------
Tuple[list, int]
... | e792dbf2ac10f44bda53a6429ba43180bdefd144 | 58,370 |
def svn_repos_parse_fns3_invoke_new_node_record(*args):
"""svn_repos_parse_fns3_invoke_new_node_record(svn_repos_parse_fns3_t _obj, apr_hash_t headers, void * revision_baton, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_parse_fns3_invoke_new_node_record(*args) | 40df4339631077ce74127b10b959f84e5bf36568 | 58,372 |
def stop_algorithm():
"""
View for stopping the algorithm. If the algorithm is already
stopped an exception will be thrown. Otherwise all workers
will be stopped.
"""
if not current_app.algorithm.running:
raise ApiException("Algorithm is already stopped")
current_app.algorithm.stop... | c60449b78e45bf3bbd76fd1957d0de7804950f89 | 58,373 |
def patch_cluster_config(cluster_id, user=None, session=None, **kwargs):
"""patch cluster config."""
cluster = _get_cluster(cluster_id, session=session)
return _update_cluster_config(
cluster, session=session, user=user, **kwargs
) | f83ef5f4b10442608cefc222032d3b207bad588a | 58,375 |
def need_new_decimal_value(old, new, delta=0.001):
""" Определяет приблизительным сравнением, необходимо ли записывать новое значение в базу."""
if new is None:
return False
elif old is None:
return True
old = float(old)
new = float(new)
delta = float(delta)
try:
if... | 0bf496c19555a6f8a878acb57322f266fb470f24 | 58,376 |
def classify():
""" Sample test Route to Neural Net """
image = request.files['image']
label, prob = classify_image(image)
return f"{label} - {prob:.2f}" | 907dbfe4149362da68da764bb44ef2ec8215185d | 58,377 |
def kegg_get(dbentries, option=None):
"""KEGG get - Data retrieval.
dbentries - Identifiers (single string, or list of strings), see below.
option - One of "aaseq", "ntseq", "mol", "kcf", "image", "kgml" (string)
The input is limited up to 10 entries.
The input is limited to one pathway entry with... | 4051c59831fc5e29e747bd0c0d20dcc28156d565 | 58,378 |
def generate_tutorial_data():
"""
Generates tutorial data.
Returns
-------
datasets : dict
Dictionary that contains the tutorial datasets.
Dictionary keys are one of circles, linearly_separable, and moons.
Dictionary values are tuples (X, y) where:
X : array-like of... | 5ae5745a87b9a9f8270d400e64200ee6325e25e9 | 58,379 |
from typing import Union
from typing import Optional
def infer_schema(data: Union[pd.DataFrame, pd.Series]) -> Optional[ProcSchema]:
"""
Infer the correct schema to use for this data set.
Parameters
----------
data : Union[pd.DataFrame, pd.Series]
Data set to test
Returns
-------... | b30028c354694c15e94dd55ff12ffbf7cc62585f | 58,380 |
def post_delete(request):
"""
View post delete page.
Param post id.
Return post list page.
"""
post_id = request.GET["post_id"]
delete_post = get_object_or_404(Post, pk=post_id)
delete_post.deleted_user_id = request.user.id
delete_post.deleted_at = timezone.now()
delete_post.save... | eb8619b811f56a0fc5a412f11b53389d03fe09e2 | 58,381 |
def set_outerHTML(new_value, traverser):
"""Tests that values being assigned to outerHTML are not dangerous."""
return _set_HTML_property("outerHTML", new_value, traverser) | ba9715989d3d8dd610331155042693173ad461ef | 58,382 |
def check_property_definitions_exist_in_scope_single(
api_factory: lusid.utilities.ApiClientFactory, property_key: str
) -> (bool, str):
"""
This function takes a list of property keys and looks to see which property definitions already exist inside LUSID
Parameters
----------
api_factory : lus... | 785022aac8ff21223d495da4c34f2d5a9edced78 | 58,384 |
def xnnpack_optional_gemmlowp_copts():
"""Compiler flags to optionally enable Gemmlowp benchmarks."""
return [] | 1f5648d61235343ebc0e3bd601a004b81e0fb65b | 58,385 |
def commitment_pattern_view(request, commitmentid):
""" Show a single commitment pattern, along with instances based on startDate and endDate url parameters. """
startDate, endDate = get_dates(request)
commitment = get_object_or_404(VolunteerCommitment, id=commitmentid)
is_my_commitment = True if commi... | f535b4db5e2cb494843b4dc3c22215559aee9468 | 58,387 |
def custom_regularizer_to_zero(x):
"""
Regularizer for custom layers that enforces tensor values to go towards 0 (the same as L2 regularization).
:param x: tensor of weights, which we want to regularize
:return: value of the loss for the custom layer
"""
return 0.0001 * tensorflow.reduce_sum(te... | 1455bb5c90d9d92cdc6eba647a80e0374998c4fd | 58,388 |
def vector_attention(x, encode_dim, feature_dim, attention_dim, sequence_length=None,
mask_zero=False, maxlen=None, epsilon=1e-8, seed=0,
scope_name="attention", reuse=False):
"""
:param x: [batchsize, s, feature_dim]
:param encode_dim: dim of encoder output
:pa... | 6cd1a51c955bf5cd4e7391239f9856def1ab5e51 | 58,389 |
def coerce_column_to_dolt(column: Column, type_mapping: dict):
"""
Defines how we map MySQL types to Dolt types, and removes unsupported column level constraints. Eventually this
function should be trivial since we aim to faithfully support MySQL.
:param column:
:param type_mapping:
:return:
... | c1821c7a97ed7a69f12afe297da70c54ee1a02b7 | 58,390 |
def _load_pdf_content(pdf: PdfFileReader) -> str:
"""
#################################
## PDF Load content ##
#################################
:param pdf: PDFFileReader object that has loaded the PDF path
:return: the raw text from the PDF
"""
# Discerning the number of... | 3b88f8e029e31063c3d7a21f43aa358cbe65b063 | 58,391 |
import re
from datetime import datetime
def match_to_datetime(match: re.Match) -> datetime | date:
"""Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
Raises ValueError if the match does not correspond to a valid date
or datetime.
"""
(
year_str,
month_str,... | 1222d2b975420605ec91bc03db516e9bff97b0d1 | 58,392 |
def extend_knots_vector(order, interval, internal_knots, closed=False, multiplicities=None):
"""Produces an extended knots vector for BSpline functions given a simple one.
This function extend the given knots partition adding auxiliary knots
on the left and on the right of the given ones in order to be th... | 7d29efedb07c4f72c4ba0ebec17ffa0fa8ea307a | 58,393 |
def load_font(font_name):
"""Loads the given font into a font object
:rtype: PIL.ImageFont.
"""
return create_font(font_name, 10) | ae99115fcae34b310577586aeb39b5f8b657aace | 58,394 |
def parse_haplotypes_from_fasta(reads_location):
"""
# ========================================================================
PARSE HAPLOTYPES FROM READS
PURPOSE
-------
Builds a list of Haplotype objects from aligned FASTA reads.
INPUT
-----
[FILE LOCATION] [reads_location]... | 0f8b7dae3a6396d733b9dc96b4c1f192a1be3341 | 58,395 |
def costs_matrix(a, b, costs):
"""
a = 'xyz'
b = 'ayzb'
m = / a y z b
0 1 2 3 4
x 1 2 3 4 5
y 2 3 2 3 4
z 3 4 3 2 3
m[row][col] -> m[2][4] == 6
"""
height = len(a) + 1
width = len(b) + 1
m = [[0] * width for _ in range(height)]
for row in r... | f2845efbe55a12806d3d9b464cbe2c0f8efd8c56 | 58,396 |
def _get(key):
"""Looks up the given key in the config singleton.
"""
config = _load()
if key in config:
return config[key]
return None | 5aac26e98f95d53c7348e27f6fabb5780d73268c | 58,397 |
from typing import Optional
from typing import Callable
def warn_if_incorrect_typing(
func: Optional[Callable] = None, join: bool = True
) -> Callable:
"""
Applies :func:`check_correct_typing` with warning as output.
:param func: the function
:param join: if True, will join all errors and raise t... | 35509721d568b8aaf6f0fa33e91cd7b7a3dbb527 | 58,398 |
import time
def get_process_id(id):
"""
get_process_id: generate a string of dmYHMS
:param id: process_id
:return: unique name of string and dateyeartime
"""
return id + "-" + str(time.strftime("%d%m%Y%H%M%S")) | 22f2c88dc14b89a54651f58b03e16e167fbd640d | 58,399 |
import random
def gen_salt(len):
"""
Generate random salt of given length
>>> len(gen_salt(10))==10
True
"""
return "".join([random.choice(SALT_DICT) for _ in range(len)]) | 640b91cf961f52efe9e3ce634bbef5d6db4f0758 | 58,400 |
async def update_file(file_id: str, data: File) -> File:
"""
Given a File ID and data, update the File in metadata store.
Args:
file_id: The File ID
data: The File object
Returns:
The updated File object
"""
db_connect = DBConnect()
collection = await db_connect.ge... | f55fb21043e9a5518895d734aeaeb0b0205a6fd1 | 58,402 |
def book_page_for_json(book_page):
"""Return the book_page formated as json suitable for jquery-file-upload.
Args:
book_page: BookPage instance
Returns:
dict, containing book_page data suitable for jquery-file-upload
{
"name": "picture1.jpg",
"si... | 965759f6c216bcd43c6ab81f40759948fb63ea6f | 58,403 |
from typing import List
def computeHV2D(front: np.ndarray, ref: List[float]):
"""
Compute the Hypervolume for the pareto front (only implement it for 2D)
:param front: (n_points, m_cost_values) array for which to compute the volume
:param ref: coordinates of the reference point
:returns: Hypervol... | e6b9618d479a6a41b840056c79411c47eeb5d9cc | 58,404 |
def go_to_semester_page(pageinfo):
"""Use the menu to get to the semester overview page"""
# don't use the link id because it looks automatically generated
# let's hope they don't change the layout
relurl = pageinfo.page.xpath('//div[@id = "pageTopNavi"]//a/@href')[1]
return PageInfo.copy_relurl(pag... | add500cdb3f4656b1a7d63865292f8853296ae86 | 58,405 |
def save_from_server(request, pk):
"""Save a portforwarding entry from the server view"""
server_from = get_object_or_404(Server, pk=request.POST.get('server_from'), is_vm=False)
server_to = get_object_or_404(Server, pk=request.POST.get('server_to'), is_vm=True)
try:
port_to = int(request.POS... | 285517f63ff356821074fb4f453585e803484344 | 58,406 |
def parse_spyder_dependencies():
"""
Parse Spyder dependencies and return a dict of deps and versions.
"""
deps = {}
for dep in DESCRIPTIONS:
if dep.get('kind', None) == OPTIONAL:
continue
ver = dep['required_version']
if ver:
if ';' in ver:
... | 4b166f7dc0c66a15b6208a794f1738b572c14487 | 58,407 |
def distribute_array(MPI, comm, data):
"""
Distribute array "data" equally between ranks and return the laod
for each rank individually.
"""
rank = comm.Get_rank()
size = comm.Get_size()
LoadRank = np.ones(shape=(size,), dtype=int)*int(data.size/size)
remainder = int(data.size%... | c5b983027b222c551d4da15334351658e92ad043 | 58,408 |
def add_contest():
"""
Adds or edits a contest
Note:
must be called from within a request context
Returns:
a redirect to the contest view page
"""
name = request.form.get("name")
activate_date = request.form.get("activate_date")
activate_time = request.form.get("activat... | 3295b7bf987df37855fbeb594aa00caaa8eb94fa | 58,410 |
def reflect(filename):
"""
:param filename: string
:return: SimpleImage
"""
img = SimpleImage(filename)
new_img = SimpleImage.blank(img.width, img.height * 2)
for y in range(img.height):
for x in range(img.width):
pixel = img.get_pixel(x,y)
upper_img = new_im... | 86b2e80e8d03605c150fdb8e25b8b6329947e69e | 58,411 |
def calculateFft(molecule, data, offset=100):
"""
Calculate the FFT for a molecule in the simulation output.
The calculation does not include amplitudes at a frequency of 0.
Parameters
----------
molecule: str
data: NamedArray/DataFrame
offset: int
Initial data that are not ... | b482ddbd12c3811bc742149a3e38323b0162a1fe | 58,412 |
def find_best_question_match(doc, question, with_score=False):
"""
For each document, find the paragraph that matches best to the question.
Args:
doc: The document object.
question: The question tokens.
with_score: If True then the match score will be returned,
otherwise ... | faf84ce9780b4e5edea6671706106be0c6bfcc35 | 58,413 |
def total_time(ui):
"""
Calculate the experiment time of each file in the experiment queue and append them to a list.
Parameters
-------
ui: the Ui_Experiment object
Instance is created in the main.py
Returns
-------
time: list which contains the experiment time of each file in... | b8230160508a50cc128e2fbb9d85f426488fcfb6 | 58,414 |
def _get_outlier_bound(series: pd.Series) -> tuple:
""" Computes the outlier bounds of a series of observations. """
# Calculate statistics
quantile_25 = series.quantile(0.25)
quantile_75 = series.quantile(0.75)
iqr = quantile_75 - quantile_25
# Calculate lower and upper bounds
lower_boun... | 421a2233bbbf1feccd7098208a6b446f783522c7 | 58,415 |
def do_markdownlaceholder(parser, token):
"""
Method that parse the markdownplaceholder template tag.
"""
name, params = parse_placeholder(parser, token)
return MarkdownPlaceholderNode(name, **params) | 7ff467e0389c6ebf2cecdfbed73980171fd5498a | 58,416 |
import requests
import traceback
def get_cluster_data(api_endpoint, data_required, only_host='all', endpoint_params={}):
"""
Gets data from the /api of REMOTE_SKYLINE_INSTANCES. This allows the user
to query a single Skyline webapp node in a cluster and the Skyline instance
will respond with the conc... | ecfac2319c7e1887457ed0796503c4c55eb8ab21 | 58,417 |
def my_model_fn_linear_conv1d(features, batch_size, fc_filters, tconv_dims, tconv_filters):
"""
My customized model function
:param features: input features
:param output_size: dimension of output data
:return:
"""
fc = features
for cnt, filters in enumerate(fc_filters):
fc = lin... | 2307c5f1d5cc02383c2afe1336788f33db94bc2b | 58,418 |
import logging
def env_data_logic(**kwargs):
"""
环境信息逻辑判断及落地
:param kwargs: dict
:return: ok or tips
"""
id = kwargs.get('id', None)
user_account = kwargs.get('user_account')
if id:
try:
EnvInfo.objects.delete_env(id,user_account)
except ObjectDoesNotExist:
... | 2d7964caf5cd077bd026107c02570d7edbcb29bc | 58,419 |
def inceptionv3(**kwargs):
"""
InceptionV3 model from 'Rethinking the Inception Architecture for Computer Vision,'
https://arxiv.org/abs/1512.00567.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.tens... | 2e115c129db1a9a8d002869ef49806fa8e02017c | 58,420 |
def binaryoperation(OPCODE, operation):
"""NOT_RPYTHON"""
def BINARY_OP(self, _):
w_2 = self.popvalue()
w_1 = self.popvalue()
w_result = operation(w_1, w_2).eval(self)
self.pushvalue(w_result)
BINARY_OP.func_name = OPCODE
return BINARY_OP | cec7ddbf7cc81c830574a3e79d40435ba08ed36a | 58,422 |
def home(request):
"""Home page view."""
context = {
"posts": Post.objects.all(),
}
return render(request, "blog/home.html", context) | 609b746d7083c2517b2b9f7758b19aa56e278d24 | 58,424 |
from pathlib import Path
def get_delimiter_field_name(field):
"""
function to return delimiter field name
"""
delimiter_name = ""
ipp_attr_group_tags = load_json_file(str(Path("protocols/ipp/ipp_data/ipp_attribute_group_tags.json")))
for key, value in ipp_attr_group_tags.items():
if in... | 08a39463bda00368c6125145f57604f5e252c784 | 58,425 |
import decimal
from datetime import datetime
def json_default(obj):
"""Serializes decimal and date values, can be used for json encoder."""
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, datetime.date):
return str(obj)
raise TypeError | 06debdd020d8d34cf6736f1f2bde6014b53c3250 | 58,426 |
def get_extras_require():
"""Add conditional dependencies for Windows (when creating wheel distributions)."""
extras_require = dict(cron='capturer>=2.4')
if have_environment_marker_support():
expression = ':sys_platform == "win32"'
extras_require[expression] = 'colorama'
return extras_re... | abe65209b843125ed331569f66a069187c36f7a9 | 58,427 |
def generate_cylinder_mask(original_img, circle_center0, radius0, circle_center1, radius1):
"""
generate the cylinder mask of the test tube given the coordinates of the bottom and top circle
coordinates and radii.
x is the depth dimenstion
"""
x0, y0, z0 = circle_center0 # larger x
x1, ... | 46dcc283dd537a59b946ba4ed7b8f788e3775000 | 58,428 |
from typing import Dict
from typing import Any
def map_key(dictionary: Dict, search: Any) -> Any:
"""Find and return they key for given search value."""
for key, value in dictionary.items():
if value == search:
return key
return None | c9e200bb352b68c7468ae0511f11f7eff5e46b52 | 58,429 |
def get_requirements(filename):
"""
Get requirements file content by filename.
:param filename: Name of requirements file.
:return: Content of requirements file.
"""
return open("requirements/" + filename).read().splitlines() | 3dab39352bb69798e076a9d97077902580f50640 | 58,430 |
import uuid
def session(loop, test_client, request, main_router):
"""
Create testing session. Tests using this fixture are expected
to have @pytest.mark.parametrize('root', [value]) decorator set.
If not set root will be defaulted to None
"""
root = None
try:
root = request.getfunc... | 3f77696644b9a8c437477efe4a9ac982ab94878a | 58,431 |
def discrete_gaussian_mean_stdd(
input,
sigma = 1.0,
errtol=0.01
):
"""
Discrete-Gaussian weighted mean and weighted standard-deviation
image calculation.
:type input: :obj:`mango.Dds`
:param input: Image for Discrete-Gaussian weighted mean and standard-deviation calculation.
:t... | 404cbfca7e976e506f81feab0e1a61f97ce5a8f5 | 58,432 |
def get_subnetwork(name=None, project=None, region=None):
"""
Get a subnetwork within GCE from its name and region.
"""
__args__ = dict()
__args__['name'] = name
__args__['project'] = project
__args__['region'] = region
__ret__ = pulumi.runtime.invoke('gcp:compute/getSubnetwork:getSubne... | b8f636004ccb73ac353421120df7f31d32537271 | 58,434 |
def convert_to_ndarray(entity):
"""Convert the object `entity` to a numpy ndarray of numerical dtype. This is needed in the routines for writing
content of DataStores and SpectrumData to disk.
Parameters
----------
entity: array_like
"""
if isinstance(entity, np.ndarray) and entity.dtype.ki... | d56c58f8788b312d1c18dbc5a54e5ae37afbcf4c | 58,436 |
def committee_page(c_id, cycle=None):
"""Fetch and render data for committee detail page.
:param int cycle: Optional cycle for financials.
"""
committee, candidates, cycle = api_caller.load_with_nested('committee', c_id, 'candidates', cycle)
return views.render_committee(committee, candidates, cycl... | 5d68718c50aade478447c4b49067f834360d0867 | 58,437 |
def TranslateTimesSimple( theaterTime ):
"""Given a tuple of(theaterName, movie showtimes) in German, returns
a string with the movie showtimes in English.
"""
showtimes = theaterTime[1]
# strip off extra stuff (some lines have extra spaces and \n)
showtimesClean = showtimes.splitlines()[0]
# fix for Wekstattki... | 6eec34793692f24bc32d7e0ffc1477edf783f1ed | 58,438 |
def is_operator(token):
"""Checks if token is an operator '-+/*'."""
return token in '-+/*' | 24b57d2a299df263c900cc94e2e18a9fc7d026b1 | 58,439 |
def flatten_array(array):
"""Flaten nested array of integer numbers. Example
flatten_array([[1,2,[3]],4]) -> [1, 2, 3, 4]
Args:
array: A nested/flat array of integer numbers or just an integer number
Returns:
Flattened array of integer numbers
Raises:
... | f6ce99f26b08c8e51d20171b9aa2c65cdbbed501 | 58,440 |
import re
def parse_url(url):
"""
parses url format is:
language/page~pagenum/~post
example:
en/my-page-with-something-interresting~5/~post-on-page-5
@param url: string
@return dict
"""
urlpattern = re.compile(
r"""
^ ... | bbcd53b08e63a35bea2a813edfe4f71fc8dfa21f | 58,441 |
def get_data(phase, amplitude, fcn):
"""Add your code here to generate and return data to be plotted.
For best results, it's easiest to import data into a Pandas dataframe and
then convert the dataframe into a Bokeh ColumnDataSource.
In this example, get_data() generates x and y values for a trig function.
... | a435a9cb549957ec45d2d0bd31d67f88a96af26b | 58,442 |
from typing import Dict
from typing import cast
from typing import Union
def build_goods_description(
good_id_to_quantities: Dict[str, int], currency_id: str, is_supply: bool
) -> Description:
"""
Get the service description (good quantities supplied or demanded and their price).
:param good_id_to_qu... | fb9cbf93175bc885d672fb84f1ce399559452647 | 58,443 |
def filter_options(section):
""" dictionary of filter specific options"""
return feed_options(section) | e104bb0c2dadf69ebfc26730ee97657280a1e766 | 58,444 |
import itertools
def duel(state, agent_1, agent_2, max_game_length=1e99):
"""Plays two agants against each other"""
history = []
agents = itertools.cycle([agent_1, agent_2])
move_number = 0
while not state.game_over and move_number < max_game_length:
actor = next(agents)
actor.pe... | 871d2e0ee036878c10c0acb6fc51349a0edcd4da | 58,445 |
def show_box(box): # pragma: no cover
"""Display a dialog."""
return _button_name_from_enum(box.exec_()) | 5c20684e3b0730c3ac06790455cc83419eb1fa6e | 58,446 |
import re
def sorted_nicely(l):
""" Sorts iterable in the way that is expected.
Parameters
----------
l : list
The iterable to be sorted.
Returns
-------
sortedList : list
The sorted iterable.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for ... | 5ae3db1c55915d3092362b80395c60cdda8aa9d0 | 58,447 |
def get_mean_roce(true_path,
pred_paths,
target,
split,
fpr_vals):
"""
Get mean ROCE scores from various different versions of a model
(e.g. different seeds of a ChemProp model).
Args:
true_path (str): path to real values
... | dfa25538ae136fdb00a827866f7d6b6a1b931c3b | 58,449 |
from typing import Dict
def get_subset(my_set: amplpy.set.Set) -> Dict:
"""
Function to extract the subsets of set containing sets from the AMPL() object
Parameters
----------
my_set : amplpy.set.Set
2-dimensional set to extract
Returns
-------
d : Dict
dictionary cont... | 35c6fba23bf9a9c67ee37e341e3c1f484ef363ab | 58,450 |
def add_date_end(record: dict):
"""
Function to make ``date_end`` ``date_start`` if ``measure_stage`` is "Lift"
Parameters
----------
record : dict
Input record.
Returns
-------
type
Record with date_end changed conditionally, or original record.
"""
if record... | 67f6ae063aabdf7a7d456ed0ce9660a75b37b6c2 | 58,451 |
def pip_package(package: str, local_pip: bool, distro: Distro) -> str:
"""
Helper function to construct installing core python packages
:param package: the python package
:param local_pip: if True, install the package using pip and Pypi,
else install using the Linux distribution package tools.
... | 1f04453b43121442a6e34de416a950cc57980962 | 58,452 |
def evaluate(string):
"""Evaluate color."""
colors = []
try:
color = string.strip()
second = None
method = None
# Try to capture the color or the two colors diff
first, method, more = parse_color(color)
if first and more is not None:
if more is ... | 02e64b8b4bf89ce9ba0b6552768a387c42858774 | 58,453 |
from bs4 import BeautifulSoup
def _get_soup(pagerequest):
# print(pagerequest)
# print("\n\n")
"""Return the BeautifulSoup for a page on scholar.google.com"""
html = _get_page(pagerequest)
html = html.replace(u'\xa0', u' ')
return BeautifulSoup(html, 'html.parser') | 53783f782620323e4ebedb656bf26ae7387c66df | 58,454 |
def get_random_train_test_split(posts, test_size=0.3, random_state=40):
"""
DataFrame을 훈련/테스트 세트로 나눕니다.
DataFrame이 질문마다 하나의 행을 가진다고 가정합니다.
:param posts: 모든 포스트와 레이블
:param test_size: 테스트 세트로 할당할 비율
:param random_state: 랜덤 시드
"""
return train_test_split(
posts, test_size=test_size... | bf370b2bb7248d3140a08eac1b3522052a1e9eae | 58,455 |
def check_revs_on_date(date):
"""
Returns true if the driver already has a reservation on the given date which means they can't drive a ride too
"""
revsOnDate=[]
db.session.execute('''PREPARE revsOnDate (varchar, date) AS SELECT * FROM Reserve rev WHERE rev.rider_netid = $1\
AND EXISTS ... | 9c8146d7b6364760185541b90b0356934bf22e4b | 58,456 |
def texto(str, fonte, cor, largura=tela.get_width()):
"""
Cria uma imagem com base em um texto.
:param str: String -- o texto.
:param fonte: Fonte -- a fonte (classe Fonte) do texto.
:param cor: Cor -- a cor (classe Cor) do texto.
:param largura: Int -- a largura na qual o texto deve estar conti... | 67d6d442550c4c86858111466b546f0eee95aaa4 | 58,457 |
import json
import io
def icellplot(download=None):
"""
renders the plot on the fly.
https://gist.github.com/illume/1f19a2cf9f26425b1761b63d9506331f
"""
apps=current_user.user_apps
plot_arguments=None
reset_info=check_session_app(session,"icellplot",apps)
submissions, apps=s... | 75ca3c126c13b2cf5a10ae606040c0beb928030e | 58,458 |
import warnings
def get_pv_map(data, header, sum_over_axis=1, slice_z=slice(None, None),
vel_unit=u.km/u.s):
"""Produce a position-velocity map.
Parameters
----------
data : numpy.ndarray
Data of the FITS array.
header : astropy.io.fits.Header
Header of the FITS arr... | 79ab1b7c8391ac760c8db2049522ead2f7ba176c | 58,459 |
def non_homogeneous_term(x: Matrix, t: Scalar) -> Matrix:
"""
The non-homogeneous term in the investigated PDE. Since out PDE is homogeneous, this will be a constant zero.
:param x: The sampled space coordinates vector.
:param t: A specific sampled time value.
:return: A scalar integer zero.
"""... | 1841588a653b139c8110a09c361bc613346a9735 | 58,460 |
def get_scoring_engine_list():
"""Returns a list of Scoring Engine instances.
The main use case for this method is discoverability, so the Scoring
Engine list is always reloaded before returning any results.
Frequent calling of this method might have a negative performance impact.
:return: A list... | 295800d98ee5b60f12d4790fec88609ec0759da9 | 58,461 |
def multy(b: int) -> int:
"""2**b via naive recursion.
>>> multy(17)-1
131071
"""
if b == 0:
return 1
return 2*multy(b-1) | 272cd138de2209093c0a32e1c7b2f1c08d0dc2be | 58,462 |
def safe_mape(actual_y, prediction_y):
"""
Calculate mean absolute percentage error
Args:
actual_y - numpy array containing targets with shape (n_samples, n_targets)
prediction_y - numpy array containing predictions with shape (n_samples, n_targets)
"""
# Ensure data shape is correc... | 28b12724bc1f15b82fd3e84bb77305ae17771e88 | 58,463 |
def token_network_registry_contract(
deploy_tester_contract, token_network_registry_constructor_args
):
"""Deployed TokenNetworkRegistry contract"""
return deploy_tester_contract(
CONTRACT_TOKEN_NETWORK_REGISTRY, token_network_registry_constructor_args
) | de18e3115cd1c0e6b8804223bd5689ba863d5239 | 58,464 |
def oauth_resp_remote_error_handler(f):
"""Decorator to handle exceptions."""
@wraps(f)
def inner(resp, remote, *args, **kwargs):
# OAuthErrors should not happen, so they are not caught here. Hence
# they will result in a 500 Internal Server Error which is what we
# are interested in... | 8a0213fe10d30b27c27fbb2fb2455c2d9fc9576b | 58,465 |
def get_loader(dataset, data_dir='./data/Figaro1k', train=True, batch_size=64, shuffle=True,
joint_transforms=None, image_transforms=None, mask_transforms=None, num_workers=0, gray_image=False):
"""
Args:
dataset (string): name of dataset to use
data_dir (string): directory to dataset
... | eeebad7c2857ae355e10648484ac957889c8a542 | 58,466 |
def CalculateNumStereocenters(mol):
"""
the number of stereo centers
--->nStereo
:param mol: molecular
:type mol: rdkit.Chem.rdchem.Mol
:return: the number of stereo centers
:rtype: int
"""
return Chem.CalcNumAtomStereoCenters(mol) | 4fc687364948dc4bb37bcef5ef6b8e5639db9799 | 58,467 |
import re
def find_process_config_str(process_name, process_configs):
"""
Searches for process config matching process name. If process name matches subprocess of mother process it adds a
new process config to process_configs. If a MC campaign is parsed and it is a subprocess and no mother process with
... | cd36aa231ab2bad83b136500754fdad7ee4317bf | 58,468 |
import html
def generate_graph_container_with_map(language, graph_type):
"""Creates and returns the HTML code for the graph container
of the dashboard.
Parameters
----------
language : str
The language to be used (e.g., 'ES' or 'EN')
graph_type : str
The type of graph to be ge... | ed0b4c164091235301e8dd5cdbe81497b8ee9db8 | 58,469 |
def prop_labeled(json_file_path, audio_file_path):
""" Compute proportion of the ratio of labels duration compared to total duration of audio
Parameters
----------
json_file_path : str
Path of json file.
audio_file_path : str
Path of audio file.
Retu... | b2d88c9ca919b416c579b6d8100a526e23a6c295 | 58,470 |
def linear_regression(x=None, y=None):
"""Plot the linear regression between two signals and get the equation coefficients.
The linear regression uses the least squares method.
Parameters
----------
x : array
First input signal.
y : array
Second input signal.
Returns
-... | a7800b2792ae53c7f60c070380b8771951078de1 | 58,471 |
def test(function):
"""
Marks a function as a test:
@test
def ensure_that_something_is_valid (...):
...
"""
setattr(function, TEST_ATTRIBUTE, True)
return function | 04969660edc8f196a033a6272bb866c1eac46421 | 58,472 |
from datetime import datetime
def put_order(params):
"""
商品情報一覧の取得
Parameters
----------
params : dict
APIGatewayのGETパラメータ
Returns
-------
paymentId:str
paymentId(create_payment_infoのreturn値)
"""
now = datetime.datetime.now(
gettz('Asia/Tokyo')).strfti... | 8585b6ae4f01895229582c07c5170006337330a7 | 58,473 |
def get_ens(sets):
"""
Puts all entities appeared in interpretation sets in one set.
:param sets: [{en1, en2, ...}, {en3, ..}, ...]
:return: set {en1, en2, en3, ...}
"""
ens = set()
for en_set in sets:
for en in en_set:
ens.add(en)
return ens | 7f5b59d6f5786ee9506bda72a4ee3f8cdf787c33 | 58,474 |
def get(lens, *args, **kargs) :
"""
Extracts a python structure from some string structure using the given
lens.
Example: get(some_lens, "a=1,c=4") -> {"a":1, "c":4}
"""
lens = Lens._coerce_to_lens(lens)
# Wrap in AutoGroup, so outer container may be ommitted for convenience
# (usually of testing lens ... | 5bf9b6ec3fa16dd94a5fb33d5e2c8ff1d6b8fd84 | 58,475 |
import uuid
def create_new_gift(ctx, creator, gift_type, annotation, campaign_name=None):
"""
Create a new gift for the given creator user.
"""
assert gift_type in gift_types.ALL, "Unknown gift_type when attempting to create %s" % gift_type
params = {}
# Use a random version 4 UUID for gifts ... | 6fecde1fa43a19c560b1430e05c6c5d3365887b5 | 58,476 |
def make_iw_env(environment_data,
seed=None,
total_wells=3,
depth=6,
well_penalty=True,
alive_penalty=False,
start_pos_type=0,
random_type=0):
"""Builds and returns a Distributional Shift game."""
env_kwa... | 2d9bdaf9b5d8f27e854709890a9e343d3bc6b3c6 | 58,477 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.