content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_(ctx):
"""List all news notifications"""
for c in get_metadata(Notification):
click.echo('{} {}'.format(c.published_date, c.title_en)) | 5,287,500 |
def test_load():
"""Tests keyword loading into dict
"""
from aflow.keywords import load
kws_from_module = K.__dict__
loaded_kws = dict()
load(loaded_kws)
for kw, obj in loaded_kws.items():
assert kw in kws_from_module
assert obj is kws_from_module[kw] | 5,287,501 |
def authorization(auth, preserve_user=None, white_list=None):
"""
MW для авторизации.
:param auth: сервис авторизации
:param white_list: Список контроллеров без проверки
:return: вызов следующей по списку MW
"""
bypass = set(white_list or []).__contains__
def wrapper(nxt, controller, a... | 5,287,502 |
def format_call(__fn, *args, **kw_args):
"""
Formats a function call, with arguments, as a string.
>>> format_call(open, "data.csv", mode="r")
"open('data.csv', mode='r')"
@param __fn
The function to call, or its name.
@rtype
`str`
"""
try:
name = __fn.__name__... | 5,287,503 |
def rgb_to_yuv(image: Tensor) -> Tensor:
"""Convert an RGB image to YUV. Image data is assumed to be in the
range of [0.0, 1.0].
Args:
image (Tensor[B, 3, H, W]):
RGB Image to be converted to YUV.
Returns:
yuv (Tensor[B, 3, H, W]):
YUV version of the image.
... | 5,287,504 |
def _get_preprocessor_settings(variables, profile, config_user):
"""Get preprocessor settings for a set of datasets."""
all_settings = {}
profile = copy.deepcopy(profile)
_update_multi_model_statistics(variables, profile,
config_user['preproc_dir'])
for variable i... | 5,287,505 |
def _melProc_to_pyModule(t, procedure):
"""
determine if this procedure has been or will be converted into python, and if so, what module it belongs to
"""
pass | 5,287,506 |
def method(obj, method, **kwargs):
"""
Call an object method. {% method object method **kwargs %}
"""
try:
return getattr(obj, method)(**kwargs)
except Exception as exception:
raise TemplateSyntaxError(
'Error calling object method; {}'.format(exception)
) | 5,287,507 |
def make_layout() -> Layout:
"""Define the layout."""
layout = Layout(name="root")
layout.split(
Layout(name="header", size=3),
Layout(name="main", ratio=1),
Layout(name="footer", size=7),
)
layout["main"].split_row(
Layout(name="side"),
Layout(name="body", r... | 5,287,508 |
def _get_precursor_mz_splits(precursor_mzs: np.ndarray,
precursor_tol_mass: float,
precursor_tol_mode: str,
batch_size: int) -> nb.typed.List:
"""
Find contiguous blocks of precursor m/z's, relative to the precursor m/z
t... | 5,287,509 |
def generate_fieldnames(value, prefix=''):
"""
"""
fieldnames = []
if isinstance(value, dict):
prefix = prefix + '.' if prefix != '' else ''
for key in sorted(value.keys()):
subnames = generate_fieldnames(value[key], prefix='{}{}'.format(prefix, key))
fieldnames.e... | 5,287,510 |
def treebank_to_short_name(treebank):
""" Convert treebank name to short code. """
if treebank in treebank_special_cases:
return treebank_special_cases.get(treebank)
if treebank.startswith('UD_'):
treebank = treebank[3:]
splits = treebank.split('-')
assert len(splits) == 2, "Unable ... | 5,287,511 |
def solve_chroma_sub(upper_rgb, lower_rgb, xyz_t, l, h, l_val, h_val, c):
"""
与えられた条件下での Chroma の限界値を算出する。
"""
upper_rgb = [
upper_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)]
lower_rgb = [
lower_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)]
xyz_t = [
... | 5,287,512 |
def get_data_dir(file=''):
"""Return the full path to the directory used to store the API data
"""
data_dir = os.getenv('TRAPI_DATA_DIR')
if not data_dir:
# Output data folder in current dir if not provided via environment variable
data_dir = os.getcwd() + '/output/'
else:
if... | 5,287,513 |
def ProcrustesCompare(mat1,mat2):
"""
Compares similarity of two matrices according to weighted R^2 among their individual components.
R^2 of inidividual components weighted by their magnitude to generate composite score.
Matrcies aligned prior to comparison using orthogonal procrustes (rotation only).
... | 5,287,514 |
def _get_value_pos(line, delim):
"""
Finds the first non-whitespace character after the delimiter
Parameters:
line: (string) Input string
delim: (string) The data delimiter
"""
fields = line.split(delim, 1)
if not len(fields) == 2:
raise Exception(f"Expected a '{delim}' ... | 5,287,515 |
def norm(data):
"""Normaliza una serie de datos"""
return (data - data.min(axis=0))/(data.max(axis=0)-data.min(axis=0)) | 5,287,516 |
def area(ds, Nmax=None, label_name='labels', cell_dim_name='CellID', dims='STCZYX'):
"""
Compute the area of each labelled region in each frame.
"""
if isinstance(dims, str):
S, T, C, Z, Y, X = list(dims)
elif isinstance(dims, list):
S, T, C, Z, Y, X = dims
def padded_area(int... | 5,287,517 |
def create_default_compiler_error_handler(
experiment_handle: 'ExperimentHandle',
project: Project,
report_type: tp.Type[BaseReport],
output_folder: tp.Optional[Path] = None,
binary: tp.Optional[ProjectBinaryWrapper] = None
) -> PEErrorHandler:
"""
Create a default PEErrorHandler for compile... | 5,287,518 |
def format_size(size):
"""格式化大小
>>> format_size(10240)
'10.00K'
>>> format_size(1429365116108)
'1.3T'
>>> format_size(1429365116108000)
'1.3P'
"""
if size < 1024:
return '%sB' % size
elif size < 1024 **2:
return '%.2fK' % (float(size) / 1024)
elif size < 1024... | 5,287,519 |
def _new(args: argparse.Namespace) -> int:
"""
Begin a new hive! Create initial scafolding for the project, nodes,
etc.
:param args: The namespace that we're given with our settings
:return: int
"""
if args.dir:
os.chdir(args.dir)
config = _get_startup_config()
log.start(ar... | 5,287,520 |
def vectorize(tokens_list, feature_fns, min_freq, vocab=None):
"""
Given the tokens for a set of documents, create a sparse
feature matrix, where each row represents a document, and
each column represents a feature.
Params:
tokens_list...a list of lists; each sublist is an
... | 5,287,521 |
def convert_category_to_continuous(df: pd.DataFrame):
"""Convert category to continuous value started from the
trial. 5 sec and 9 sec is flushing time.
See "makeDataFrame" in basicChara for reference code.
Args:
df: cleaned dataframe. Ex., pL.merged_structured_df.
"""
df = df.cop... | 5,287,522 |
def validate_header_image(wide_image: object):
"""Validates image of the header"""
if not utils.image_size_match(wide_image, width=1920, height=720):
raise ValidationError('The image must be 1920x720') | 5,287,523 |
def closest_contour_center(depth_image, contours):
"""
Takes a depth_image and list of contours.
Finds the center of each contour, then finds which center is closest.
Returns the coordinates for that center in y, x format.
"""
depth_image = cv.GaussianBlur(depth_image, (3, 3), 0)
contour_centers = []
for con... | 5,287,524 |
def get_download_url_for_platform(url_templates, platform_info_dict):
"""
Compare the dict returned by get_platform_info() with the values specified in the url_template element. Return
true if and only if all defined attributes match the corresponding dict entries. If an entry is not
defined in the url_... | 5,287,525 |
def determine_boundaries(df: pd.DataFrame, bucket_mapping: BucketMapping) -> Union[List, Dict]:
"""
Determine mapping boundaries.
Given a dataframe with pre_bucket and bucket column, determine the boundaries
that can be passed to the bucket_mapping.
```python
import pandas as pd
from skore... | 5,287,526 |
def load(filepath):
"""
Load in metadata from filepath.
Args:
filepath (string/path): path to file.
Returns:
pd.DataFrame: dataframe containing metadata.
"""
tracks = pd.read_csv(filepath, index_col=0, header=[0])
# Format the data.
# Remove "tabs" from strings etc.
... | 5,287,527 |
def compute(
applied_voltages, resistances, r_i=None,
r_i_word_line=None, r_i_bit_line=None, **kwargs):
"""Computes branch currents and node voltages of a crossbar.
Parameters
----------
applied_voltages : array_like
Applied voltages. Voltages must be supplied in an array of sha... | 5,287,528 |
def cli(filename, csfd, open):
"""Finds titulky.com subtitles for given file."""
if csfd:
csfd_link = parse_csfd(csfd)
film = {'url': csfd_link, 'name': get_film_name(csfd_link)}
else:
film = None
if filename:
urls = automatic_mode(filename, film=film)
else:
... | 5,287,529 |
def TypeNameToLogModel(type_name):
"""Return log model associated with type_name."""
if type_name == BitLockerVolume.ESCROW_TYPE_NAME:
return BitLockerAccessLog
elif type_name == DuplicityKeyPair.ESCROW_TYPE_NAME:
return DuplicityAccessLog
elif type_name == FileVaultVolume.ESCROW_TYPE_NAME:
return F... | 5,287,530 |
def save_obj(fname, vertices, faces):
"""Save to Wavefront .OBJ.
Args:
fname (str): filename
vertices (torch.Tensor): [N_vertices, 3]
vertices (torch.Tensor): [N_faces, 3]
"""
assert fname.endswith('.obj'), 'Filename must end with .obj'
with open(fname, 'w') as f:
... | 5,287,531 |
def grad_logdet(inv_metric: np.ndarray, jac_metric: np.ndarray, num_dims: int) -> np.ndarray:
"""Computes the gradient of the log-determinant of the Riemannian metric.
Args:
inv_metric: The inverse of the Riemannian metric.
jac_metric: The Jacobian of the metric tensor.
num_dims: The nu... | 5,287,532 |
def create_api_access_audit_log(
username: str,
success: bool,
path: str) -> None:
""" Create an audit log. """
with app.db.database.get_write_session_scope() as session:
now = get_utc_now()
audit_log = APIAccessAudit(create_user=username, path=path, success=success,
... | 5,287,533 |
def escrever_senhas_nascimento(nome_arquivo, data_nascimento):
"""Escreve como senha somente a data de nascimento.
Arguments:
nome_arquivo {str} -- Nome do arquivo onde será escrito
data_nascimento {str} -- A data de nascimento
"""
arquivo = open(nome_arquivo + '.txt', 'at')
... | 5,287,534 |
async def task_runner(inventory, sleep, task, should_run):
"""
Runs a task in an event loop
:param inventory: Inventory
:param sleep: how long to wait between loop iterations
:param task: coroutine to run
:param should_run: function for should this task continue to run
"""
# pylint: disa... | 5,287,535 |
def get_code():
""" return code from codes.txt and """
codes = []
with open(codes_file, "r") as cf:
for num, line in enumerate(cf.readlines()):
if num == 1:
if line.startswith("Need"):
raise Exception(line)
codes.append(line)
code = cod... | 5,287,536 |
def get_unicode_category(prop):
"""
Retrieve the unicode category from the table
"""
p1, p2 = (prop[0], prop[1]) if len(prop) > 1 else (prop[0], None)
return ''.join([x for x in _unicode_properties[p1].values()]) if p2 is None else _unicode_properties[p1][p2] | 5,287,537 |
def pink_noise(nstep_out, pow_spec=None, f=None, fmin=None, alpha=-1, **kwargs):
""" Generate random pink noise
Parameters
==========
nstep_out : int
Desired size of the output noise array. If smaller than `pow_spec`
then it just truncates the results to the appropriate size.
If... | 5,287,538 |
def plotEigenfrequenciesPlate( GraphInstance ):
"""
The function prints and updates the values of the eigen frequencies using the
Message instance which is a part of an instance of GraphObject class
:param GraphInstance: an instance of GraphObject class
:return:
"""
Text = "</p>The first fo... | 5,287,539 |
def get_username() -> str:
"""
Returns username lowercase
>>> username = get_username()
>>> assert len(username) > 1
"""
_username = getpass.getuser().lower()
return _username | 5,287,540 |
def fetch_ALL_standings():
"""
This returns the complete set of all the standings in the league, namely IGnobels and general/points. It is used
by other functions
"""
dic_stand = {
'Caduti': 'infortunati',
'Cartellino Facile': 'cartellini',
'Porta Violata': 'goal_subit... | 5,287,541 |
def extract_id(source):
"""
Attempts to extract an ID from the argument, first by looking for an
attribute and then by using dictionary access. If both fail, the argument
is returned.
"""
try:
return source.id
except AttributeError:
pass
try:
return source["id"]
... | 5,287,542 |
def pytest_report_header(config):
"""Add header information for pytest execution."""
return [
"LAMMPS Executable: {}".format(
shutil.which(config.getoption("lammps_exec") or "lammps")
),
"LAMMPS Work Directory: {}".format(
config.getoption("lammps_workdir") or "<T... | 5,287,543 |
def transform_score(data, score_card):
"""
特征映射回分值
Args:
data: 特征表
score_card: 评分卡
Returns:
返回转化后的得分
"""
base_score = score_card[score_card['Bins'] == '-']['Score'].values[0]
data['Score'] = base_score
for i in range(len(data)):
score_i = base_score
... | 5,287,544 |
def download_csv(
raw_csv_folder: str,
search_terms: list,
start_date: str,
end_date: str
):
"""Download csv files of historical price data for specified financial assets from yahoo finance
- xpaths are based on yahoo finance website
Args:
raw_csv_folder (str): absolute file path to... | 5,287,545 |
def load_query(asset):
"""Helper to load test asset and parse as Query, returning."""
yaml_query1 = load_test_asset(asset)
parser1 = mql.QueryParser()
return parser1.parse_ystr_query(yaml_query1) | 5,287,546 |
def crop_transcript(json_infile, json_outfile, crop_time, goal_time, printout=False):
"""
Check if everything is fine with the json transcript file
Args:
json_file: file with speech transcript
printout: weather we need to print for debugging
Returns:
nothing, can raise errors
... | 5,287,547 |
def test_list_datasets_outside_a_renku_project(directory_tree):
"""Test listing datasets in a non-renku directory."""
os.chdir(directory_tree)
assert [] == Dataset.list() | 5,287,548 |
def FKinBody(M, Blist, thetalist):
"""Computes forward kinematics in the body frame for an open chain robot
:param M: The home configuration (position and orientation) of the end-
effector
:param Blist: The joint screw axes in the end-effector frame when the
manipulator is at... | 5,287,549 |
def list_spot_pricing(ctx, regions_, instance_types_):
"""List pricing on spot instances
Examples:
rxtb ec2 list-spot-pricing --region eu-west-1 --instance-type m5.xlarge
rxtb ec2 list-spot-pricing --region eu-west-1 --region eu-west-2 --instance-type m5.xlarge
"""
# get all regions
r... | 5,287,550 |
def l2_regularization(cg, rate=0.01):
"""compute L2 regularization decay.
Parameters
----------
cg : ComputationGraph
computation graph for a network
rate : float
L2 regularization rate
Returns
-------
L2_cost : expression
L2 cost for a network
"""
W = V... | 5,287,551 |
def convertcsv(inputfile, outputfile, templatefile, charset=None,
columnorder=None):
"""reads in inputfile using csvl10n, converts using csv2tbx, writes to
outputfile"""
inputstore = csvl10n.csvfile(inputfile, fieldnames=columnorder)
convertor = csv2tbx(charset=charset)
outputstore = ... | 5,287,552 |
def supported_disabled(responses, derived):
""" Return the parsed array of supporting_disabled """
try:
return json.loads(responses.get('supporting_disabled', '[]'))
except ValueError:
return [] | 5,287,553 |
def insert_task_id(app_ctx, task_id):
"""
Add a task id to the application context.
:type app_ctx: :class:`vmware.vapi.core.ApplicationContext`
:param app_ctx: Application Context
:type task_id: :class:`str`
:param task_id: Task Id
"""
if app_ctx is not None:
app_ctx[TASK_ID] = ... | 5,287,554 |
def shape_sanity_check(image: np.ndarray, ddf: np.ndarray):
"""
Verify image and ddf shapes are consistent and correct.
:param image: a numpy array of shape (m_dim1, m_dim2, m_dim3)
or (m_dim1, m_dim2, m_dim3, ch)
:param ddf: a numpy array of shape (f_dim1, f_dim2, f_dim3, 3)
"""
if len... | 5,287,555 |
def mathreco():
"""API function
All model-specific logic to be defined in the get_model_api()
function
"""
input_data = request.json
app.logger.debug("api_input: " + str(input_data))
output_data = model_api(input_data)
app.logger.debug("api_output: " + str(output_data))
response = j... | 5,287,556 |
def test_get_obj_size():
"""Test get byte size of an object."""
assert utils.get_obj_size([]) > 0
assert utils.get_obj_size("") > 0
assert utils.get_obj_size({}) > 0 | 5,287,557 |
def test_lshift(cdll_data):
"""Test lshift method of CDLL class"""
assert cdll_data.head.value == 0
assert cdll_data.tail.value == 9
cdll_data << 1
assert cdll_data.head.value == 9
assert cdll_data.tail.value == 8 | 5,287,558 |
def test_wpas_ap_async_fail(dev):
"""wpa_supplicant AP mode - Async failure"""
id = dev[0].add_network()
dev[0].set("country", "FI")
try:
dev[0].set_network(id, "mode", "2")
dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
dev[0].set_network(id, "key_mgmt", "NONE")
d... | 5,287,559 |
def link_all(src: Path, dest: Path):
"""
Link all your dot files from source to dest
:param src: the source path
:param dest: the dest path
"""
__link_all(src, dest)
print('Done!') | 5,287,560 |
def metrics_binary(ytest, predict_y_score):
"""Evaluation metrics for binary classification (including auc, ap, f1)"""
predict_y_label = np.array(predict_y_score >= 0.5).astype(np.int)
pos_num = np.sum(predict_y_label)
frac = np.sum(predict_y_label) * 100 / len(ytest)
try:
auc = metrics.roc_... | 5,287,561 |
def prepare_custom_bucket(**kwargs):
"""Creates and uploads objects to a bucket in preparation for load generation"""
bucket_name = load_generator_custom.prepare_custom_bucket(**kwargs)
print('OK')
print('bucket_name={}'.format(bucket_name)) | 5,287,562 |
def main():
"""Main method that prints netconf capabilities of remote device."""
with manager.connect(host=HOST, port=PORT, username=USER, password=PASS,
hostkey_verify=False, device_params={'name': 'default'},
look_for_keys=False, allow_agent=False) as m:
... | 5,287,563 |
def kill_cloudverifier():
"""Kill the cloud verifier"""
global cv_process
if cv_process is None:
return
os.killpg(os.getpgid(cv_process.pid), signal.SIGINT)
cv_process.wait()
cv_process = None | 5,287,564 |
def zeros_like(x: Union[ivy.Array, ivy.NativeArray], dtype: ivy.Dtype = None, dev: ivy.Device = None,
) -> Union[ivy.Array, ivy.NativeArray]:
"""
Returns an array of zeros with the same shape and type as x, unless dtype provided which overrides.
:param x: The shape and data-type of x define ... | 5,287,565 |
def preprocess_tweets(infile: str, outfile: str) -> None:
"""Remove redundant and non-objective posts."""
logger = logging.getLogger("preprocessor")
# Number of Tweets read
counter: int = 0
# List of all Tweets
tweets: List[Tweet] = []
# Begin reading
with open(infile, "r") as csv_fil... | 5,287,566 |
def get_data_ts(type, mask_disc=False, filter_missing_vft=False):
"""
get data as tme series i.e no input output
:param type:
:param use_deltat:
:return:
"""
pickle = True
if (type == 'train'):
data = np.load('../oct_forecasting/temp/lstmdata_train.npz', allow_pickle=pickle)
... | 5,287,567 |
def test_submodule_clone(repo_with_submodule):
"""Test git clone containing a git submodule."""
upstream, expected_sha1_upstream, expected_sha1_submod = repo_with_submodule
with TemporaryDirectory() as clone_dir:
submod_dir = os.path.join(clone_dir, "submod") # set by fixture
spec = {"repo... | 5,287,568 |
def get_lwt_topic(mqtt: dict) -> dict:
"""Return last will topic."""
if not mqtt["last_will_topic"]:
mqtt["last_will_topic"] = f"{mqtt['client_id']}/lwt"
return mqtt | 5,287,569 |
def list_count(choice, dataset_id, start_timestamp, end_timestamp, dataset_type='result_table', frequency='1d'):
"""
查询生命周期指标的数据趋势
:param choice:
:param dataset_id:
:param start_timestamp:
:param end_timestamp:
:param dataset_type:
:param frequency:
:return:
"""
# 生成influxdb需... | 5,287,570 |
def debounce(wait: int):
"""Debounce main method."""
def decorator(fn: Callable):
def debounced(*args: Any, **kwargs: Any):
def call_it() -> None:
fn(*args, **kwargs)
try:
debounced.timer.cancel()
except (AttributeError):
... | 5,287,571 |
def test_prepare_cube_for_merging():
"""Test preprocessing cubes before merging."""
label = 'abcde'
aux_coord = iris.coords.AuxCoord(label,
var_name='cube_label',
long_name='cube_label')
cube_in = CUBE_1.copy()
cube_in.coord(D... | 5,287,572 |
def aos_delete(session, endpoint, aos_id):
"""
DELETE request aginst aos RestApi
:param session: dict
:param endpoint: string
:param aos_id: string
:return: dict
"""
aos_url = "https://{}/api/{}/{}".format(session['server'],
endpoint,
... | 5,287,573 |
def value_to_key_strokes(value):
"""Convert value to a list of key strokes
>>> value_to_key_strokes(123)
['123']
>>> value_to_key_strokes('123')
['123']
>>> value_to_key_strokes([1, 2, 3])
['123']
>>> value_to_key_strokes(['1', '2', '3'])
['123']
Args:
value(int|str|list... | 5,287,574 |
def legacy_data_config_to_new_data_config(
ds_section: DictConfig, legacy_dataset_section: DictConfig, train: bool
) -> DictConfig:
"""
Transform old style dataset to new format dataset.
Args:
ds_section: a ds section (``train_ds``, or ``validation_ds``, or ``test_ds``) from old style config. Su... | 5,287,575 |
def app():
"""Create and configure a new app instance for each test."""
# create the app with common test config
_app = create_app({
'TESTING': True,
'DEBUG': True,
})
# create the database and load test data
with _app.app_context():
init_db()
yield _app | 5,287,576 |
def _calculate_gain(nonlinearity, param=None):
"""
Calculate gain.
Args:
nonlinearity (str): nonlinearity function.
param (str): used to calculate negative_slope.
Returns:
number.
"""
linear_fns = ['linear', 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transp... | 5,287,577 |
def verifyDirectory(path, create, quiet):
"""
ERROR CHECK: verify directory exists
:param path: str, path to save the file
:param create: bool, whether to create missing dir
:param quiet: bool, whether to quietly return T/F
:return: exists, bool, indicates existence of directory
"""
exists = True
if not os.p... | 5,287,578 |
def test_equality_pass() -> None:
"""It declares two pass Move objects with same fields as equal."""
assert Move.pass_turn() == Move.pass_turn() | 5,287,579 |
def listify(array, valuename, colnames):
"""
converts a multidimensional numpy array into a pandas dataframe with colnames[0] referring to dimension 0, etc
and valuecolumn containing the array values
"""
multiindex = pd.MultiIndex.from_product([range(i) for i in array.shape])
colmapping = {"level_" + ... | 5,287,580 |
def Lp(params, p=2):
"""
Given a list of parameters, compute the p-th power of its Lp norm.
:type params: list
:param params: Parameters to take the Lp norm of.
:type p: int
:param p: p of the Lp norm. Defaults to 2.
:return: (Lp norm)^p
"""
# Compute Lp^p
lpn = sum(map(T.sum... | 5,287,581 |
def unpack_student_answer_1_5(questions_info, valid_question_ids,
assessment_weights, group_to_questions,
unit_responses, timestamp):
"""Unpack JSON from event; convert to QuestionAnswerInfo objects.
The JSON for events is unusually shaped; function r... | 5,287,582 |
def handle_command(slack_api, command, channel):
"""
Recieves commands directed for the bot, if they are valid perform action
else resends clarification
"""
EXAMPLE_COMMAND = 'do'
if command.lower().startswith(EXAMPLE_COMMAND) or command.lower().startswith('what'):
slack_api.rtm_send_message(channel, 'Yes, cod... | 5,287,583 |
def handle_all_coordinates():
"""
Kezeli az ossz koordinata lekereset.
:return:
"""
response = make_response(json.dumps(coordinates))
response.headers["Content-Type"] = "application/json"
return response | 5,287,584 |
def loadXML(path):
"""
returns a 'xml.etree.ElementTree.ElementTree' object read from a xml file
or object-type.
"""
return et.parse(path) | 5,287,585 |
def test_publish_release_from_state(db, admin_client, mocker, state, allowed):
"""
Test that a release may only be published from the staged state.
"""
mock_rq = mocker.patch("coordinator.graphql.releases.django_rq")
release = ReleaseFactory(state=state)
variables = {"release": to_global_id("Re... | 5,287,586 |
def _label(img: np.ndarray) -> np.ndarray:
""" Applies labeling to given binary image returning array in which each group of pixels has the same value. """
return measure.label(img) | 5,287,587 |
def execute_remote_ssh_commands(hostname, username, password, commands, verbose=True):
""" Execute a remote command line.
hostname (str): This is the IP or domain name of ssh server.
username (str): This value is the username use to login to ssh server.
password (str): This value... | 5,287,588 |
def consolidate_rows(df: pd.DataFrame) -> pd.DataFrame:
"""
Group rows by all columns except "origin" to remove redundancies
created by entity recognition from multiple sources/ontologies
:param df: Input DataFrame
:type df: pd.DataFrame
:return: Consolidated DataFrame
:rtype: pd.DataFrame
... | 5,287,589 |
def write(filename, gen):
"""Write all lines from the generator into a file"""
f = open(str(filename), 'w')
for line in gen:
f.write(line) | 5,287,590 |
def main():
"""Make a jazz noise here"""
args = get_args()
annot_fp = args.annotations
out_fp = args.outfile
blast_fp = args.positional
#print('output_arg = "{}"'.format(out_fp))
#print('annotation_arg = "{}"'.format(annot_fp))
#print('blast_fp = "{}"'.format(blast_fp))
if not os.p... | 5,287,591 |
def test_test():
""" """
import pinot
import copy
layer = pinot.representation.dgl_legacy.gn()
net_representation = pinot.representation.Sequential(
layer, [32, "tanh", 32, "tanh", 32, "tanh"]
)
net = pinot.Net(net_representation)
train = pinot.Train(
net=net,
d... | 5,287,592 |
def get_locale():
"""Return the default locale string."""
return ('es_ES' if getdefaultlocale()[0] == 'es_CU' else
getdefaultlocale()[0])
# return 'es_ES' | 5,287,593 |
def process_fare(df):
"""
Converts the Fare column into pre-defined bins.
:param df: Dataframe
:return: Dataframe with Fare column having pre-defined bins
"""
cut_points = [-1, 12, 50, 100, 1000]
label_names = ["0-12", "12-50", "50-100", "100+"]
df["Fare_categories"] = pd.cut(df["Fare"]... | 5,287,594 |
def disable_account_ajax(request):
"""
Ajax call to change user standing. Endpoint of the form
in manage_user_standing.html
"""
if not request.user.is_staff:
raise Http404
username = request.POST.get('username')
context = {}
if username is None or username.strip() == '':
... | 5,287,595 |
def spacja(sciezka):
""" escaping space and special char in pathname """
sciezka = os.path.normpath(sciezka)
if platform.system() == "Windows":
czy_spacja = re.search(" ", sciezka)
if czy_spacja is not None:
sciezka = '"' + sciezka + '"'
else:
path = os.path.splitext... | 5,287,596 |
def ghg_parse(dataframe_list, args):
"""
Parse the given EPA GHGI data and return multiple dataframes, one per-year per-table.
:param dataframe_list:
:param args:
:return:
"""
cleaned_list = []
for df in dataframe_list:
special_format = False
source_name = df["SourceName"... | 5,287,597 |
def execute_all(
executables: list[Executable],
target: test_target.TestTarget,
repeat: int,
):
"""Executes all tests in the `executables` list in parallel."""
executables = [e for e in executables if should_run_executable(e, target.arch)]
if repeat > 1:
executables = executables * repea... | 5,287,598 |
def create_collection(href, cls):
"""
This collection type inserts a ``create`` method into the collection.
This will proxy to the sub elements create method while restricting
access to other attributes that wouldn't be initialized yet.
.. py:method:: create(...)
Create method is inser... | 5,287,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.