content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def data_static(filename):
"""
Get files
:param filename:
:return:
"""
_p, _f = os.path.split(filename)
# print(_p, _f)
return flask.send_from_directory(os.path.join(config['path']['path_data'], _p), _f) | 1b603a8adb7bc384985cd0571d8ed2323ae32a73 | 17,100 |
def target(x, seed, instance):
"""A target function for dummy testing of TA
perform x^2 for easy result calculations in checks.
"""
# Return x[i] (with brackets) so we pass the value, not the
# np array element
return x[0] ** 2, {'key': seed, 'instance': instance} | 131560778f51ebd250a3077833859f7e5addeb6e | 17,101 |
def generate(fspec, count, _fuel=None):
"""Generate <count> number of random passwords/passphrases.
The passphrases are formated according to <fspec>.
Returned value is (list, json_data),
where list is a <count>-element sequence of
pair of (password, reading hint for password).
json_da... | aad44a80a648d192c696ebdd44ceefadd21d88cd | 17,102 |
def convert_to_valid_einsum_chars(einsum_str):
"""Convert the str ``einsum_str`` to contain only the alphabetic characters
valid for numpy einsum.
"""
# partition into valid and invalid sets
valid, invalid = set(), set()
for x in einsum_str:
(valid if is_valid_einsum_char(x) else invalid... | 2cdd67bc967a12bd3dcb80f323f093cd9eff7213 | 17,103 |
def prop_GAC(csp, newVar=None):
"""
Do GAC propagation. If newVar is None we do initial GAC enforce
processing all constraints. Otherwise we do GAC enforce with
constraints containing newVar on GAC Queue
"""
constraints = csp.get_cons_with_var(newVar) if newVar else csp.get_all_cons()
pruned... | a1c576cfd9920a51eb9b9884bd49b4e8f4194d02 | 17,104 |
import io
import shutil
import os
def clone( # pylint: disable=R0913,R0912,R0914
source, target, branch="main", depth=None, delete_git_dir=False,
username=None, password=None, key_filename=None, key_data=None,
track_branch_upstream=True,
):
""" Clone repository """
# Prepare auth args... | 6fe55e808bfe2758e82859772d3d2e063d9c5add | 17,105 |
def submit_only_kwargs(kwargs):
"""Strip out kwargs that are not used in submit"""
kwargs = kwargs.copy()
for key in ['patience', 'min_freq', 'max_freq', 'validation',
"max_epochs", "epoch_boost", "train_size", "valid_size"]:
_ = kwargs.pop(key, None)
return kwargs | e93a4b8921c5b80bb487caa6057c1ff7c1701305 | 17,106 |
def make_simple_boundary(outline_edge_group: UniqueEdgeList, all_edges: UniqueEdgeList):
"""
Step 3 recursive
:param outline_edge_group: A list of edges, grouped by connectivity between edges.
:param all_edges:
:return: ???
"""
while len(all_edges.edge_list) > 0:
current_edge = all_e... | fd3dfd40302d2f01126032c9420fd7b990d30cc6 | 17,107 |
import os
def convert_rscape_svg_to_one_line(rscape_svg, destination):
"""
Convert R-scape SVG into SVG with 1 line per element.
"""
output = os.path.join(destination, 'rscape-one-line.svg')
cmd = (r"perl -0777 -pe 's/\n +fill/ fill/g' {rscape_svg} | "
r"perl -0777 -pe 's/\n d=/ d=/g' |... | 7f561dcd1b9c6e540bb96fab363781dad73db566 | 17,108 |
import subprocess
import tempfile
import scipy
def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs):
"""
Download Digitized Sky Survey images
https://archive.stsci.edu/cgi-bin/dss_form
https://archive.stsci.edu/cgi-bin/dss_search
Image is in celestial orientation (RA increases to the right)... | 338b0a5e4b54656f7fc763e0af55a1877b514712 | 17,109 |
async def async_attach_trigger(
hass: HomeAssistant,
config: ConfigType,
action: AutomationActionType,
automation_info: dict,
) -> CALLBACK_TYPE:
"""Attach a trigger."""
job = HassJob(action)
if config[CONF_TYPE] == "turn_on":
entity_id = config[CONF_ENTITY_ID]
@callback
... | 5cf362c7dc0b82f562164141ccf76f30dd1a0169 | 17,110 |
import pathlib
def imread(image_path, as_uint8=True):
"""Read an image as numpy array.
Args:
image_path (str or pathlib.Path):
File path (including extension) to read image.
as_uint8 (bool):
Read an image in uint8 format.
Returns:
:class:`numpy.ndarray`:
... | 30050f63e43d862cf512994f0e9d21c187b1ac0a | 17,111 |
def pk(obj):
"""
A helper that gets the primary key of a model instance if one is passed in.
If not, this returns the parameter itself.
This allows functions to have parameters that accept either a primary key
or model instance. For example:
``` python
def get_translations(target_locale):
... | 431f518fe6d53e979543e4588a1d7389d7100d69 | 17,112 |
import requests
import json
def get_dataset(id):
"""Query for existence of dataset by ID."""
uu = UrlUtils()
es_url = uu.rest_url
#es_index = "{}_{}_s1-ifg".format(uu.grq_index_prefix, version)
es_index = "grq"
# query
query = {
"query": {
"wildcard": {
"_id": id
... | cfb31da0e23b7e197af1919fa34fa3f2d4fa1dfe | 17,113 |
def bags_with_gold( parents_of, _ ):
"""
Starting from leaf = 'gold', find recursively its parents upto the root and add them to a set
Number of bags that could contain gold = length of the set
"""
contains_gold = set()
def find_roots( bag ):
for outer_bag in parents_of[ bag ]:
... | 3fd2b1c260d41867a5787a14f0c50a9b5d1a2f08 | 17,114 |
def process_file(file_path):
"""
This function processes the submitted file
:return: A dictionary of errors found in the file. If there are no errors,
then only the error report headers will in the results.
"""
enc = detect_bom_encoding(file_path)
if enc is None:
with open(file_path... | 29b25b9a1ac950b2b0d051a6748ebc78b31bad10 | 17,115 |
import requests
def get_request_body(text, api_key, *args):
"""
send a request and return the response body parsed as dictionary
@param text: target text that you want to detect its language
@type text: str
@type api_key: str
@param api_key: your private API key
"""
if not api_key:
... | e21e8733eec00bc78616b18a8d93c18dc2b20449 | 17,116 |
def generate_sample_task(project):
""" Generate task example for upload and check it with serializer validation
:param project: project with label config
:return: task dict
"""
task = generate_sample_task_without_check(project.label_config)
# check generated task
'''if project:
try... | 1e3259b320e46a938139b0dde8ed5b999290d6cd | 17,117 |
def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to seri... | 839d59e92c4249359367d07700bd55f80eafe98b | 17,118 |
import pandas
def fetch_fi2010(normalization=None) -> pandas.DataFrame:
"""
Load the FI2010 dataset with no auction.
Benchmark Dataset for Mid-Price Forecasting of Limit Order Book Data with Machine
Learning Methods. A Ntakaris, M Magris, J Kanniainen, M Gabbouj, A Iosifidis.
arXiv:1705.03233 [cs... | bb6e6e484d6d3d3d1d831a9194fe4f629b820db8 | 17,119 |
def get_netcdf_filename(batch_idx: int) -> str:
"""Generate full filename, excluding path."""
assert 0 <= batch_idx < 1e6
return f"{batch_idx:06d}.nc" | 5d916c4969eb96653ea9f0a21ab8bec93ebcfafa | 17,120 |
def CreateBoardConfigs(site_config, boards_dict, ge_build_config):
"""Create mixin templates for each board."""
# Extract the full list of board names from GE data.
separate_board_names = set(config_lib.GeBuildConfigAllBoards(ge_build_config))
unified_builds = config_lib.GetUnifiedBuildConfigAllBuilds(ge_build_... | 7d0dfeca13015c6fa5b75d10106476f347de0cbb | 17,121 |
def area_calc(radius, point_in, total_points):
"""Calculates the partial area of ball
:param radius: radius of ball
:param point_in: points of the total points to include
:param total_points: number of sampled points
:return: area
"""
return (4 * pi * radius ** 2) * (point_in / total_points) | a660776a4f4a1d2d04a28255b7ee0892ddc5d136 | 17,122 |
import gettext
import math
def results_framework_export(request, program):
"""Returns .XLSX containing program's results framework"""
program = Program.rf_aware_objects.get(pk=program)
wb = openpyxl.Workbook()
wb.remove(wb.active)
ws = wb.create_sheet(gettext("Results Framework"))
get_font = l... | 79cf9f84243f089dd463909f9f64d13a1bb39444 | 17,123 |
import copy
def generate_subwindow(pc, sample_bb, scale, offset=2, oriented=True):
"""
generating the search area using the sample_bb
:param pc:
:param sample_bb:
:param scale:
:param offset:
:param oriented: use oriented or axis-aligned cropping
:return:
"""
rot_mat = np.tran... | af86fdd4409f98ccd503a9587a6e4b19b0763a31 | 17,124 |
def tsfigure(num=None, figsize=None, dpi=None, facecolor=None,
edgecolor=None, frameon=True, subplotpars=None,
FigureClass=TSFigure):
"""
Creates a new :class:`TimeSeriesFigure` object.
Parameters
----------
num : {None, int}, optional
Number of the figure.
... | 578b8299ea8b7b8eb05a1f0e68ce4b1f1dca4682 | 17,125 |
import zipfile
import json
def load_predict_result(predict_filename):
"""Loads the file to be predicted"""
predict_result = {}
ret_code = SUCCESS
try:
predict_file_zip = zipfile.ZipFile(predict_filename)
except:
ret_code = FILE_ERROR
return predict_result, ret_code
for ... | c26cc24fcdcaa774d05ed6963f66cae346617f46 | 17,126 |
import os
def localize_all(roi, ignore_exception=True, **kwargs):
""" localize all variable local sources in the roi, make TSmaps and associations if requested
ignore if extended -- has 'spatial_model'
kwargs can have prefix to select subset with name starting with the prefix, e.g. 'SEED'
"""... | 0bf5c056ebc23a448954884ca06a3e29fd71de34 | 17,127 |
def convert_post_to_VERB(request, verb):
"""
Force Django to process the VERB.
"""
if request.method == verb:
if hasattr(request, '_post'):
del(request._post)
del(request._files)
try:
request.method = "POST"
request._load_post_and_files()
... | 3c304d07ab04950ac65f58405acc3103a3b64dcf | 17,128 |
def close(x, y, rtol, atol):
"""Returns True if x and y are sufficiently close.
Parameters
----------
rtol
The relative tolerance.
atol
The absolute tolerance.
"""
# assumes finite weights
return abs(x-y) <= atol + rtol * abs(y) | bd2597c0c94f2edf686d0dc9772288312cb36d83 | 17,129 |
import warnings
def plot_precip_field(
precip,
ptype="intensity",
ax=None,
geodata=None,
units="mm/h",
bbox=None,
colorscale="pysteps",
probthr=None,
title=None,
colorbar=True,
axis="on",
cax=None,
map_kwargs=None,
**kwargs,
):
"""
Function to plot a pre... | 7e9429310ffdfdb38ac2b6e03b4c846d017060f5 | 17,130 |
def get_for_repo(repo, name, default=None):
"""Gets a configuration setting for a particular repository. Looks for a
setting specific to the repository, then falls back to a global setting."""
NOT_FOUND = [] # a unique sentinel distinct from None
value = get(name, NOT_FOUND, repo)
if value is NOT_... | 5848e4da859f26788ab02b733bc61135c1ea3b80 | 17,131 |
from typing import AnyStr
def new_user(tenant: AnyStr, password: AnyStr) -> bool:
"""Return a boolean containing weither a new tenant is created or no."""
if not query.get_tenant_id(tenant):
return True
return False | ac1bc45213c76712d1ec3553a8545fac5ab67f3a | 17,132 |
def home():
"""
Home page control code
:return Rendered page:
"""
error = request.args.get("error", None)
state, code = request.args.get("state", None), request.args.get("code", None)
if code and not has_user() and 'state' in session and session['state'] == state:
tok = reddit_get_access_t... | 280f17feff363fa73decfa15bc615aa0c320d3d9 | 17,133 |
from datetime import datetime
import pytz
def get_date_list(num_days):
"""
For an integer number of days (num_days), get an ordered list of
DateTime objects to report on.
"""
local_tz = tzlocal.get_localzone()
local_start_date = local_tz.localize(datetime.datetime.now()).replace(hour=0, minute... | 5f338cf6ffcbb10569cfd7878a91f6a2d60831ca | 17,134 |
def is_even(val):
"""
Confirms if a value if even.
:param val: Value to be tested.
:type val: int, float
:return: True if the number is even, otherwise false.
:rtype: bool
Examples:
--------------------------
.. code-block:: python
>>> even_numbers = list(filter(is_even, ran... | 1ef0716e1e86ff77b3234bbd664c6b973352c3ea | 17,135 |
import os
def get_fremont_data(filename = "Fremont.csv", url = URL, force_download = False):
""" Download and cache the fremont data
Parameters
----------
csv file Fremont.csv
url URL
force download
Returns
-------
data : pandas dataframe
"""
... | c61683423585e52c42bb96c21bcd6dd21ed9edc8 | 17,136 |
def min_spacing(mylist):
"""
Find the minimum spacing in the list.
Args:
mylist (list): A list of integer/float.
Returns:
int/float: Minimum spacing within the list.
"""
# Set the maximum of the minimum spacing.
min_space = max(mylist) - min(mylist)
# Iteratively find ... | b8ce0a46bacb7015c9e59b6573bc2fec0252505d | 17,137 |
import re
import os
def extract_dawn_compiler_options() -> list:
"""Generate options_info for the Dawn compiler options struct."""
options_info = []
regex = re.compile(r"OPT\(([^,]+), ?(\w+)")
DAWN_CPP_SRC_ROOT = os.path.join(
os.path.dirname(__file__), os.pardir, os.pardir, "src", "dawn"
... | a79f9700f1d0b5c512a5b77b04a16c7fd4c8c105 | 17,138 |
def sign(x):
"""Return the mathematical sign of the particle."""
if x.imag:
return x / sqrt(x.imag ** 2 + x.real ** 2)
return 0 if x == 0 else -1 if x < 0 else 1 | 0dca727afbc9c805a858c027a8a4e38d59d9d218 | 17,139 |
def wrap_strings(lines: [str], line_width: int):
"""Return a list of strings, wrapped to the specified length."""
i = 0
while i < len(lines):
# if a line is over the limit
if len(lines[i]) > line_width:
# (try to) find the rightmost occurrence of a space in the first 80 chars
... | 0a6fa989fd6d27276d2e7d8c91cf8be37f6a3aff | 17,140 |
def has_even_parity(message: int) -> bool:
""" Return true if message has even parity."""
parity_is_even: bool = True
while message:
parity_is_even = not parity_is_even
message = message & (message - 1)
return parity_is_even | 8982302840318f223e9c1ab08c407d585a725f97 | 17,141 |
def is_primitive(structure):
"""
Checks if a structure is primitive or not,
:param structure: AiiDA StructureData
:return: True if the structure can not be anymore refined.
prints False if the structure can be futher refined.
"""
refined_cell = find_primitive_cell(structure)
prim = Fals... | 9f7034bb92d3fdd0505a56bc7d53d1528846ef76 | 17,142 |
def mock_mkdir(monkeypatch):
"""Mock the mkdir function."""
def mocked_mkdir(path, mode=0o755):
return True
monkeypatch.setattr("charms.layer.git_deploy.os.mkdir", mocked_mkdir) | e4e78ece1b8e60719fe11eb6808f0f2b99a933c3 | 17,143 |
import zipfile
import os
def zip_dir_recursively(base_dir, zip_file):
"""Zip compresses a base_dir recursively."""
zip_file = zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED)
root_len = len(os.path.abspath(base_dir))
for root, _, files in os.walk(base_dir):
archive_root = os.pa... | 79dc58f508b2f1e78b2cc32208471f75c6a3b15c | 17,144 |
def saferepr(obj, maxsize=240):
"""return a size-limited safe repr-string for the given object.
Failing __repr__ functions of user instances will be represented
with a short exception info and 'saferepr' generally takes
care to never raise exceptions itself. This function is a wrapper
around the Re... | d02f68581867e64a6586548ab627b6893328c42a | 17,145 |
from typing import Callable
from re import A
def filter(pred : Callable[[A], bool], stream : Stream[A]) -> Stream[A]:
"""Filter a stream of type `A`.
:param pred: A predicate on type `A`.
:type pred: `A -> bool`
:param stream: A stream of type `A` to be filtered.
:type stream: `Stream[A]`
:r... | 93b3d4c30d4295b2be73200451436c6a4e9ab5cd | 17,146 |
def _get_kernel_size_numel(kernel_size):
"""Determine number of pixels/voxels. ``kernel_size`` must be an ``N``-tuple."""
if not isinstance(kernel_size, tuple):
raise ValueError(f"kernel_size must be a tuple. Got {kernel_size}.")
return _get_numel_from_shape(kernel_size) | fb004817950ece275fc10b4824ee83a1d1b9a6a9 | 17,147 |
import uuid
def random():
"""Get a random UUID."""
return str(uuid.uuid4()) | 411aeb5254775473b43d3ac4153a27a2f15014cb | 17,148 |
def reautorank(reaumur):
""" This function converts Reaumur to rankine, with Reaumur as parameter."""
rankine = (reaumur * 2.25) + 491.67
return rankine | aec2299999e9798530272939125cb42476f095c3 | 17,149 |
def list_pets():
"""Shows list of all pets in db"""
pets = Pet.query.all()
return render_template('list.html', pets=pets) | 60df575932d98ab04e949d6ef6f1fdfa6734ba92 | 17,150 |
import os
import glob
def BundleFpmcuUnittests(chroot, sysroot, output_directory):
"""Create artifact tarball for fingerprint MCU on-device unittests.
Args:
chroot (chroot_lib.Chroot): The chroot containing the sysroot.
sysroot (sysroot_lib.Sysroot): The sysroot whose artifacts are being
archived.
... | ee737c5a938e069d36d7f1c963aec8ae7dd2b81a | 17,151 |
import glob
def get_lif_list(path):
"""
Returns a list of files ending in *.lif in provided folder
:param: path
:return: list -- filenames
"""
path += '/*.lif'
return glob.glob(path) | 8a26d65fc2c69b1007a40ded82225038ead67783 | 17,152 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Single image depth estimation')
parser.add_argument('--dataset', dest='dataset',
help='training dataset',
default='custom', type=str)
parser... | 62fd1a807d662253d41c65d9b6add2822fdacca9 | 17,153 |
def compute_distance_matrix(users, basestations):
"""Distances between all users and basestations is calculated.
Args:
users: (obj) list of users!
basestations: (obj) list of basestations!
Returns:
(list of) numpy arrays containing the distance between a user and all basestations ... | 07b6175047d7602288436d163f838077e54054fc | 17,154 |
from .core import resolver
def __getattr__(name):
"""Lazy load the global resolver to avoid circular dependencies with plugins."""
if name in _SPECIAL_ATTRS:
res = resolver.Resolver()
res.load_plugins_from_environment()
_set_default_resolver(res)
return globals()[name]
e... | 20dd678be2b9d3f08513912a40098dc8b436ac81 | 17,155 |
def img_newt(N, xran=(-3, 3), yran=(-3, 3), tol=1e-5, niter=100):
"""
Add colors to a matrix according to the fixed point
of the given equation.
"""
sol = [-(np.sqrt(3.0)*1j - 1.0)/2.0,
(np.sqrt(3.0)*1j + 1.0)/2.0,
-1.0]
col_newt = np.zeros((N, N, 3))
Y, X = np.mgrid[yr... | 166aa3c5e144972f7ec825f973885f9b528047f0 | 17,156 |
def pack_block_header(hdr: block.BlockHeader,
abbrev: bool = False,
pretty: bool = False,
) -> str:
"""Pack blockchain to JSON string with b64 for bytes."""
f = get_b2s(abbrev)
hdr_ = {'timestamp': f(hdr['timestamp']),
'previous_h... | a6df547918ab82bc990ca915d956730cb6a62b87 | 17,157 |
def get_datasets(recipe):
"""Get dataset instances from the recipe.
Parameters
----------
recipe : dict of dict
The specifications of the core datasets.
Returns
-------
datasets : dict of datasets
A dictionary of dataset instances, compatible with torch's
DataLoader... | f525cf379f13069a1f5255798d963af3389dd5ed | 17,158 |
import re
def is_sedol(value):
"""Checks whether a string is a valid SEDOL identifier.
Regex from here: https://en.wikipedia.org/wiki/SEDOL
:param value: A string to evaluate.
:returns: True if string is in the form of a valid SEDOL identifier."""
return re.match(r'^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}... | 207ff94a4df99e7a546440cef1242f9a48435118 | 17,159 |
def create_substrate(dim):
"""
The function to create two-sheets substrate configuration with specified
dimensions of each sheet.
Arguments:
dim: The dimensions accross X, Y axis of the sheet
"""
# Building sheet configurations of inputs and outputs
inputs = create_sheet_space(-1,... | 9a47bf213d796aecec4b6f630ae30b04dc035d63 | 17,160 |
def remove_artefacts(signal: np.array, low_limit: int = 40, high_limit: int = 210) -> np.array:
"""
Replace artefacts [ultra-low and ultra-high values] with zero
Args:
signal: (np.array) 1D signal
low_limit: (int) filter values below it
high_limit: (int) filter valu... | 0b85e929588bd5895a9a84c5d03fce88c4f9f7cb | 17,161 |
def normalizedBGR(im, display=True):
""" Generate Opponent color space. O3 is just the intensity """
im = img.norm(im)
B, G, R = np.dsplit(im, 3)
b = (B - np.mean(B)) / np.std(B)
g = (G - np.mean(G)) / np.std(G)
r = (R - np.mean(R)) / np.std(R)
out = cv2.merge((np.uint8(img.normUnity(b) * 25... | 810b4a1ee4d9b5d7f68072c72379fa182b7f34fe | 17,162 |
def feeds(url):
"""
Tries to find feeds
for a given URL.
"""
url = _full_url(url)
data = _get(url)
# Check if the url is a feed.
if _is_feed(url):
return [url]
# Try to get feed links from markup.
try:
feed_links = [link for link in _get_feed_links(data, url) i... | dd16dc751f34fbbf496c9b0142fa5d58372538b2 | 17,163 |
def getlog(name):
"""Create logger object with predefined stream handler & formatting
Parameters
----------
name : str
module __name__
Returns
-------
logging.logger
Examples
--------
>>> from smseventlog import getlog
>>> log = getlog(__name__)
"""
name = ... | cd5e0dd4589757e3c8d05614f117b7ce46fe4fb9 | 17,164 |
import sys
def read_new_probe_design(path: str, reference_type: str = 'genome') -> pd.DataFrame:
"""
Read amplimap probes.csv file and return pandas dataframe.
"""
try:
design = pd.read_csv(path)
log.info('Read probe design table from %s -- found %d probes', path, len(design))
... | e8e8ccfffe514e13af26a7cc7ddd59eb51328c7d | 17,165 |
import numpy as np
def replace_nan(x):
"""
Replaces NaNs in 1D array with nearest finite value.
Usage: y = replace_nan(x)
Returns filled array y without altering input array x.
Assumes input is numpy array.
3/2015 BWB
"""
#
x2 = np.zeros(len(x))
np.copyto(x2,x)
#
... | 9100a33dcb7d00b38e7a6a53132db8d13682e499 | 17,166 |
def handson_table(request, query_sets, fields):
"""function to render the scoresheets as part of the template"""
return excel.make_response_from_query_sets(query_sets, fields, 'handsontable.html')
# content = excel.pe.save_as(source=query_sets,
# dest_file_type='handsontable.... | 93c1471c142917f5b0492ddb27fdd6c278e9976d | 17,167 |
from functools import reduce
def is_periodic(G):
"""
https://stackoverflow.com/questions/54030163/periodic-and-aperiodic-directed-graphs
Own function to test, whether a given Graph is aperiodic:
"""
if not nx.is_strongly_connected(G):
print("G is not strongly connected, periodicity not def... | 6671a1bf57ef6ec973c7d283cb447d890cbd93e2 | 17,168 |
def Sphere(individual):
"""Sphere test objective function.
F(x) = sum_{i=1}^d xi^2
d=1,2,3,...
Range: [-100,100]
Minima: 0
"""
#print(individual)
return sum(x**2 for x in individual) | 349b732e931fc5acf8a52213d9ddf88335479b90 | 17,169 |
def find_names_for_google(df_birth_names):
"""
:param df_birth_names: 所有的birth data from the data given by Lu
:return 1: df_country_found,
返回一个dataframe 里面有国家了
先通过country list过滤,有些国家可能有问题(如有好几个名字的(e.g. 荷兰),有些含有特殊符号,如刚果布,刚果金,朝鲜,南朝鲜北朝鲜是三个“国家”,
再比如说南奥塞梯,一些太平洋岛国归属有问题,还就是香港台湾这样的。。。。暂时算是国家)
而后看看... | 6358fd692784389530ebf4c3a2059c3923104d2f | 17,170 |
def make_address_mask(universe, sub=0, net=0, is_simplified=True):
"""Returns the address bytes for a given universe, subnet and net.
Args:
universe - Universe to listen
sub - Subnet to listen
net - Net to listen
is_simplified - Whether to use nets and subnet or universe only,
see User Guid... | d360dde7ecc4ecc99e32df53f2f0806d5d396f1f | 17,171 |
def get_offline_target(featureset, start_time=None, name=None):
"""return an optimal offline feature set target"""
# todo: take status, start_time and lookup order into account
for target in featureset.status.targets:
driver = kind_to_driver[target.kind]
if driver.is_offline and (not name or... | 6297f26e188ae31df3cf76b8e49229876cae23f6 | 17,172 |
def get_img_size(src_size, dest_size):
"""
Возвращает размеры изображения в пропорции с оригиналом исходя из того,
как направлено изображение (вертикально или горизонтально)
:param src_size: размер оригинала
:type src_size: list / tuple
:param dest_size: конечные размеры
:type dest_size: lis... | 133dab529cd528373a1c7c6456a34cf8fd22dac9 | 17,173 |
def laxnodeset(v):
"""\
Return a nodeset with elements from the argument. If the argument is
already a nodeset, it self will be returned. Otherwise it will be
converted to a nodeset, that can be mutable or immutable depending on
what happens to be most effectively implemented."""
if not isinstance(v, Node... | 3210f8d1c1d47c8871d0ba82c793b6cd85069566 | 17,174 |
def load_config():
"""
Loads the configuration file.
Returns:
- (json) : The configuration file.
"""
return load_json_file('config.json') | 05099118414d371ebc521e498503be1798c39066 | 17,175 |
import subprocess
def dtm_generate_footprint(tile_id):
"""
Generates a footprint file using gdal.
:param tile_id: tile id in the format "rrrr_ccc" where rrrr is the row number and ccc is the column number
:return execution status
"""
# Initiate return value and log output
return_value = '... | da8526a61b75b4ec3ce22e052ba75d9ecee84f62 | 17,176 |
def favicon(request):
"""
best by tezar tantular from the Noun Project
"""
if settings.DEBUG:
image_data = open("static/favicon-dev.ico", "rb").read()
else:
image_data = open("static/favicon.ico", "rb").read()
# TODO add cache headers
return HttpResponse(image_data, content_t... | 8824d8e6ff313c3773b3c6dddc0833eca3847fba | 17,177 |
from bs4 import BeautifulSoup
def text_from_html(body):
"""
Gets all raw text from html, removing all tags.
:param body: html
:return: str
"""
soup = BeautifulSoup(body, "html.parser")
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return " ".join(t.str... | 313a5f404120c17290b726cb00b05e2276a07895 | 17,178 |
def alert_history():
"""
Alert History: RESTful CRUD controller
"""
return s3_rest_controller(rheader = s3db.cap_history_rheader) | 34a2b6bf90ab0b73eae3b64c83ffebc918e2f1a3 | 17,179 |
def chat():
"""
Chat room. The user's name and room must be stored in
the session.
"""
if 'avatar' not in session:
session['avatar'] = avatars.get_avatar()
data = {
'user_name': session.get('user_name', ''),
'avatar': session.get('avatar'),
'room_key': session.get... | d7024960ac8a03082deb696e0c0e6009dfe8e349 | 17,180 |
def _get_split_idx(N, blocksize, pad=0):
"""
Returns a list of indexes dividing an array into blocks of size blocksize
with optional padding. Padding takes into account that the resultant block
must fit within the original array.
Parameters
----------
N : Nonnegative integer
Total ... | 21935190de4c42fa5d7854f6608387dd2f004fbc | 17,181 |
def buydown_loan(amount, nrate, grace=0, dispoints=0, orgpoints=0, prepmt=None):
"""
In this loan, the periodic payments are recalculated when there are changes
in the value of the interest rate.
Args:
amount (float): Loan amount.
nrate (float, pandas.Series): nominal interest rate per ... | 46eb6bbaaa940b5cf1abd702ee5d9e2e20c6dab3 | 17,182 |
from typing import Optional
def ffill(array: np.ndarray, value: Optional[int] = 0) -> np.ndarray:
"""Forward fills an array.
Args:
array: 1-D or 2-D array.
value: Value to be filled. Default is 0.
Returns:
ndarray: Forward-filled array.
Examples:
>>> x = np.array([0,... | f5774c3e50ddbf2ffa9cf84df5cb57b135d1549a | 17,183 |
def svn_stringbuf_from_file(*args):
"""svn_stringbuf_from_file(char const * filename, apr_pool_t pool) -> svn_error_t"""
return _core.svn_stringbuf_from_file(*args) | b375a43bf8e050aa5191f387d930077680e9b019 | 17,184 |
def poly4(x, b, b0):
"""
Defines a function with polynom 4 to fit the curve
Parameters
----------
x: numpy.ndarray:
x of f(x)
b: float
Parameter to fit
b0 : int
y-intercept of the curve
Returns
-------
f : numpy.ndarray
Result of f(x)
"""
... | aed3603640400488219f2cca82e57268f32de000 | 17,185 |
from teospy.tests.tester import Tester
def chkiapws06table6(printresult=True,chktol=_CHKTOL):
"""Check accuracy against IAPWS 2006 table 6.
Evaluate the functions in this module and compare to reference
values of thermodynamic properties (e.g. heat capacity, lapse rate)
in IAPWS 2006, table 6.
... | c0fce67d3a268ec0b67ff845f5671c67aa394846 | 17,186 |
def flat(arr):
"""
Finds flat things (could be zeros)
___________________________
"""
arr = np.array(arr)
if arr.size == 0:
return False
mean = np.repeat(np.mean(arr), arr.size)
nonzero_residuals = np.nonzero(arr - mean)[0]
return nonzero_residuals.size < arr.size/100 | ce2697d95165b46cec477265df6ccb337cb89af1 | 17,187 |
def sensitive_fields(*paths, **typed_paths):
"""
paths must be a path like "password" or "vmInfo.password"
"""
def ret(old_init):
def __init__(self, *args, **kwargs):
if paths:
ps = ["obj['" + p.replace(".", "']['") + "']" for p in paths]
setattr(s... | e174519c253d4676ae7c07c1b11eb18e532d5f61 | 17,188 |
from datetime import datetime
import time
def get_timestamp_diff(diff):
"""获取前后diff天对应的时间戳(毫秒)"""
tmp_str = (datetime.today() + timedelta(diff)).strftime("%Y-%m-%d %H:%M:%S")
tmp_array = time.strptime(tmp_str, "%Y-%m-%d %H:%M:%S")
return int(time.mktime(tmp_array)) * 1000 | 61ca093471103376ee44d940552db6337a4e65f5 | 17,189 |
def can_delete(account, bike):
""" Check if an account can delete a bike.
Account must be a team member and bike not borrowed in the future.
"""
return (team_control.is_member(account, bike.team)
and not has_future_borrows(bike)) | f962e465b6a5eb62feea2683cdd8328b5591fb43 | 17,190 |
import os
def config_file():
"""
Returns the config file ($HOME/.config/python-pulseaudio-profiles-trayicon/config.json).
:return: the directory for the configurations
:rtype: str
"""
return os.path.join(config_dir(), "config.json") | 2841d6b52f2b95a194b2858ee1522f0516efbd9d | 17,191 |
def get_node_types(nodes, return_shape_type = True):
"""
Get the maya node types for the nodes supplied.
Returns:
dict: dict[node_type_name] node dict of matching nodes
"""
found_type = {}
for node in nodes:
node_type = cmds.nodeType(node)
if node_... | 7867f97f7228ac77ae44fda04672a8224aa7c1f4 | 17,192 |
import csv
from typing import OrderedDict
def updateDistances(fileName):
"""
Calculate and update the distance on the given CSV file.
Parameters
----------
fileName: str
Path and name of the CSV file to process.
Returns
-------
ret: bool
Response indicating if the upd... | c19e0adcf731f9fd1af87f5dfe3a61889d395457 | 17,193 |
def hr(*args, **kwargs):
"""
The HTML <hr> element represents a thematic break between
paragraph-level elements (for example, a change of scene in a
story, or a shift of topic with a section). In previous versions
of HTML, it represented a horizontal rule. It may still be
displayed as a horizont... | 959106dc2c71334b5a88045f8a26a9f42a2d2fdb | 17,194 |
def as_linker_option(p):
"""Return as an ld library path argument"""
if p:
return '-Wl,' + p
return '' | 452c06034be5c3c2525eb2bfad011e468daef02b | 17,195 |
def split_backbone(options):
"""
Split backbone fasta file into chunks.
Returns dictionary of backbone -> id.
"""
backbone_to_id = {}
id_counter = 0
# Write all backbone files to their own fasta file.
pf = ParseFasta(options.backbone_filename)
tuple = pf.getRecord()
while tup... | 6446e90a1aa2e38ca01ebb8a86b8cd1dbd3abd75 | 17,196 |
import pkg_resources
def _get_highest_tag(tags):
"""Find the highest tag from a list.
Pass in a list of tag strings and this will return the highest
(latest) as sorted by the pkg_resources version parser.
"""
return max(tags, key=pkg_resources.parse_version) | 8d2580f6f6fbb54108ee14d6d4834d376a65c501 | 17,197 |
def add_comment(request, pk):
"""
Adds comment to the image - POST.
Checks the user and assigns it to the comment.posted_by
"""
form = PhotoCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.save()
else:... | 4488a183ca7786c65d355991cec38fed01864ab1 | 17,198 |
import os
def predict():
"""
runs the three models and displays results view
"""
filename = request.form['filename']
file_root = os.path.splitext(filename)[0]
full_filename = os.path.join(app.config['STATIC_MATRIX_PATH'],
filename)
# run YOLOv5 model
... | 5eeb7452228562b0881105f2e991a781f26921ef | 17,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.