content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Tell the crew what you have spotted from the crowsnest',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('word', metavar='word', help='A word')
... | 7c1650cf4c27330dce5c15bfadee8464c1a182fa | 58,401 |
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 |
import sys
import re
def parse_args():
"""
Parse arguments.
"""
# flags
param={
"help":False,
"version":False,
"retry":3,
"urls":[],
"only-target":False,
"errout":sys.stderr,
"out":sys.stdout,
"level":0,
}
args = sys.... | 39d23f664b319caba417e3ad932ad6c7235456d9 | 58,409 |
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 |
import hashlib
import sys
import os
def import_module(path, module_name=None):
"""
Import module from path.
:param path: full path to module to import
:param module_name: name to map module in sys.modules
:returns: imported module
Based on code from the following:
:source: http://stacko... | a0b2be49149e0b49e45d297ae91a3d53d4bc3558 | 58,421 |
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 |
from typing import List
import subprocess
def _container_names_by_prefix(prefix: str) -> List[str]:
"""Return a list of all containers (running or not) whose names begin
with `prefix`.
Provide a `docker-compose` project name as a prefix to retrieve
containers associated with that project. (We don't u... | 21794b0be7476444f867d2a6aeba18d47f916ba7 | 58,423 |
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 |
import sys
def createkSpaceMask(im_size, num_half_lines):
""" Compute mask of radial lines for given image size
:param im_size: image size
:param num_half_lines: number of half radial lines
:return: sampling mask
"""
if im_size[0] < 32 or im_size[1] < 32:
sys.exit("side < 32")
if... | 7716c91732c8acf58ec1e4f27ab8db4d82ebfbf5 | 58,433 |
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 |
import logging
def get_tags_list(repo, start, end, last_release):
"""
Get a list of tags from the repo and return the require range.
Args:
repo(:class:`~git.repo.base.Repo`): Git repository instance
start(str): Start point of tags
end(str): End point of tags
last_release(s... | c9943dd68648036594de4cc3658405e6310f2b79 | 58,435 |
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 |
import argparse
def cli_unset_account(args: argparse.Namespace) -> CliFunctionReturnType:
"""
CLI adapter to unset the default account to be used.
:param args: arguments parsed by the CLI parser
:returns: the resto client parameters and the resto server possibly built by this command.
"""
res... | 416a7ba590e60c43828a8a1c6ce1339a3b20fd6b | 58,448 |
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 |
def normalize_image_min_max(image, min_image, max_image):
"""normalizes an image (from [min_image;max_image] to [0;1])
Args:
image (numpy.ndarray): input image
min_image (float): input image manual min value (all values below will be set to 0)
max_image (float): input image manu... | d314ef09feed7342b5229ce95c8815b3d4da7a6d | 58,478 |
def setup_es(endpoint, dataset, production,
drop_and_recreate=False, increment_version=False):
"""Retrieve the ES connection, ES config and setup the index
if required.
Args:
endpoint (str): Name of the AWS ES endpoint.
dataset (str): Name of the dataset for the ES mapping.
... | cc8a2731c3d09dfcf64454b7d7c65adb119494bf | 58,479 |
import numbers
import math
def _sd_of_runs(stats, mean, key='runs'):
"""Obtain the standard deviation of stats.
Args:
stats: dict; A set of stats, structured as above.
mean: dict; Mean for each key in stats.
key: str; Optional key to determine where list of runs is found in stats
... | 3736fa81b782e2ef45fe1acc7a300047f215ce1d | 58,480 |
from typing import Optional
import re
def get_biolink_element(name) -> Optional[Element]:
"""
Get Biolink element for a given name, where name can be a class, slot, or relation.
Parameters
----------
name: str
The name
Returns
-------
Optional[biolinkml.meta.Element]
... | c5cfe635dee723590d762e41f37ef22ac4221a4d | 58,481 |
def make_path(index, bits):
"""
Given a size of a node to add get the binary path to reach it.
"""
mask = 2**np.arange(bits-1, -1, -1)
x = np.bitwise_and(np.array(index+1).ravel(), mask) != 0
def path(c, a):
x = a + 2 * c
x = np.minimum(x, index+1)
return x, x
_, x =... | 6e0cb999eb52fe5af708af43e85d0977bf3a94c7 | 58,482 |
import stat
def _get_type_by_stat(st_mode):
"""Match special filesystem objects to Mimetypes."""
if stat.S_ISDIR(st_mode): return inode_dir
elif stat.S_ISCHR(st_mode): return inode_char
elif stat.S_ISBLK(st_mode): return inode_block
elif stat.S_ISFIFO(st_mode): return inode_fifo
elif stat.S_IS... | 7e202a31013b32098d9929052fba2ef04e65af38 | 58,483 |
def scatter_nd(data, indices, shape):
"""Scatter elements from a n-dimension array.
Given data with shape (Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1}), indices with shape
(M, Y_0, ..., Y_{K-1}), and output with shape (X_0, X_1, ..., X_{N-1}), scatter_nd computes
.. code-block::
output[indices[0, y_... | 4a62f1ecffcfa29347443f03062d3c904aa10882 | 58,484 |
def sm_to_pandas(sm):
"""
Convert a score matrix that is the result of sciunit TestSuite
to a regular pandas dataframe.
"""
n_rows, n_cols = sm.shape
arr = np.empty(shape=(n_rows, n_cols), dtype=np.float64)
for i in range(n_rows):
for j in range(n_cols):
arr[i, j] = sm.ia... | 2143cf69d00175fbd008f54b7572fb8d7f7c1ca4 | 58,485 |
def is_in_group(user, group_name):
"""
Check if a user in a group named ``group_name``.
:param user User:
The auth.User object
:param group_name str:
The name of the group
:returns: bool
"""
return user.groups.filter(name__exact=group_name).exists() | 25e51e483b0c18c03f8e897725f07e9e63cc160a | 58,486 |
import csv
def read_pairs_from_csv(filename, skip_first=False):
"""Read numbers from file in format ROMAN;DECIMAL.
This will return a list of (roman_numeral: string, decimal: int) tuples.
The Roman numerals will have square brackets removed.
"""
with open(filename) as csvfile:
if skip_fir... | f0a7e80a8860f0b26d78cceffd454c4b5ed64235 | 58,487 |
from datetime import datetime
def create(task):
"""
This function creates a new task in the tasks structure
based on the passed in task data
:param task: task to create in tasks structure
:return: 201 on success, 406 on task exists
"""
title = task.get("title")
duedate = task.... | 575a027be2892e649de250fc47283ea186cd78d4 | 58,488 |
def MakeReverseCompoMapping(font):
"""Return a dict that maps glyph names to lists containing tuples
of the form:
(clientGlyphName, componentIndex)
"""
font = unwrapFont(font)
reverseCompoMapping = {}
for g in font.glyphs:
for i, c in zip(range(len(g.components)), g.components):
base = font[c.index].name... | 416466c4a0f9d1e8e13bb883e275e5a69b174d86 | 58,489 |
import os
def join_file_path(*args):
"""
Preprocesses the given values and runs them through os.path.join.
"""
args = list(args)
if args[0] == '':
args[0] = '/'
for i in range(1, len(args)): # First value can start with /
args[i] = args[i].strip('/')
retur... | 71e63993ef9a40ced16dafec75442c95229f4537 | 58,490 |
def get_anno_bbox(img_id, scale_factor_row, scale_factor_col):
"""
根据xml文件获取标注的整体bbox
"""
xml_fname = id_to_xml(img_id)
tree = ET.parse(xml_fname)
root = tree.getroot()
annotations = root[0]
minx, miny, maxx, maxy = 1e10, 1e10, 0, 0
for each_annotation in annotations:
for eac... | 26105abb70db6ae2722ccddcdbd8aebef700308f | 58,491 |
def label_colormap(n_label=256, value=None):
"""Label colormap.
Parameters
----------
n_labels: int
Number of labels (default: 256).
value: float or int
Value scale or value of label color in HSV space.
Returns
-------
cmap: numpy.ndarray, (N, 3), numpy.uint8
La... | d16c149e294fdbb7e14895061cf1ad7148b51e76 | 58,492 |
def create_group_transition_probs(states, assort_by, params, model_name):
"""Create a transition matrix for groups.
Args:
states (pandas.DataFrame): The states.
assort_by (list): List of variables that influence matching probabilities.
params (pandas.DataFrame): The parameters.
... | ff288bcdeb0d928c6f79127987af115f86773868 | 58,493 |
def _cached_to(attr_name):
"""
Оборачивает простые методы (без аргументов) и property getters,
с целью закэшировать первый полученный результат
"""
def wrapper(fn):
@wraps(fn)
def inner(self):
if hasattr(self, attr_name):
result = getattr(self, attr_name)
... | 098d72ad164f6794492747f0dbefa752f0c92028 | 58,494 |
def pickArgs(local_state, global_state, node_name, argument_specs, operation,predecessors):
"""
:param local_state:
:param global_state:
:param argument_specs:
:param operation:
:param predecessors:
:return:
@type operation : Operation
@type predecessors: List[str]
"""
startT... | 6b9f6f06ae6fd9489be72e5cbf57bfad3bc830b3 | 58,495 |
def imshow(image, ax=None, title=None, normalize=True):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
image = image.numpy().transpose((1, 2, 0))
if normalize:
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * im... | 35fe7c6e945c978a3e7082aad7e36b87d6dc9ac6 | 58,496 |
import datasets
import os
import importlib
def dataset(train_transforms, val_transforms, test_transforms):
"""get dataset for classification"""
if FLAGS.dataset == 'imagenet1k':
if not FLAGS.test_only:
train_set = datasets.ImageFolder(
os.path.join(FLAGS.dataset_dir, 'train... | 4edb4159231e8bf991333632463e3395c09b86db | 58,497 |
def calc_bic(eprofile, bi2014):
"""
Calculates the Bayesian Information Criterion
See: https://www.immagic.com/eLibrary/ARCHIVES/GENERAL/WIKIPEDI/W120607B.pdf
Parameters
----------
eprofile
bi2014
Returns
-------
"""
err_var = crr_error_variance(eprofile, bi2014.crr_m7p5)... | 0827bc54a235f157fa6ceb5ba6db56158993d62e | 58,498 |
def _derive_entity_label_matrix(train_full_results, entities):
"""
Derive entity feature matrix for chi2 anaylsis using entity annotations from message api
:param train_full_results: pandas data frame outputed by inference
:param entities: list of entities that is defined in the workspace
:return en... | ce806a97ce83d50226b1a68b09e986c0225ec955 | 58,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.