content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_string_with_non_paren_elements():
"""Test input string where not all elems are parens."""
with pytest.raises(TypeError):
assert proper_parenthetics('((7)1') | 44,500 |
def forbidden(error) -> str:
""" Forbidden resource
"""
return jsonify({"error": error.description}), 403 | 44,501 |
def get_parameter(model, name):
"""
Finds the named parameter within the given model.
"""
for n, p in model.named_parameters():
if n == name:
return p
raise LookupError(name) | 44,502 |
def _update_method(oldmeth, newmeth):
"""Update a method object."""
# XXX What if im_func is not a function?
_update(oldmeth.im_func, newmeth.im_func)
return oldmeth | 44,503 |
def romanize(string, system):
"""
Transliterate Burmese text with latin letters.
>>> romanize("ကွန်ပျူတာ", IPA)
'kʊ̀ɴpjùtà'
>>> romanize("ပဒေသရာဇာ", MLC)
'padezarājā'
>>> romanize("ဘင်္ဂလားအော်", BGN_PCGN)
'bin-gala-aw'
"""
romans = []
for syllable in PhonemicSyllableBrea... | 44,504 |
def get_stats_asmmemmgr(space):
"""Returns the raw memory currently used by the JIT backend,
as a pair (total_memory_allocated, memory_in_use)."""
m1 = jit_hooks.stats_asmmemmgr_allocated(None)
m2 = jit_hooks.stats_asmmemmgr_used(None)
return space.newtuple([space.newint(m1), space.newint(m2)]) | 44,505 |
def parse_function(filename):
""" Parse a filename and load the corresponding image. Used for faces.
Parameters
----------
filename : str
Path to the faces image.
Returns
-------
image : tensorflow.Tensor
Image object.
Raises
------
None
No... | 44,506 |
async def do_periodic_update(appliance: GeAppliance):
"""Request a full state update every minute forever"""
_LOGGER.debug(f'Registering update callback for {appliance:s}')
while True:
await asyncio.sleep(60 * 1)
_LOGGER.debug(f'Requesting update for {appliance:s}')
await appliance.a... | 44,507 |
def calc_final_speed(v_i, a, d):
"""
Computes the final speed given an initial speed, distance travelled,
and a constant acceleration.
:param:
v_i: initial speed (m/s)
a: acceleration (m/s^2)
d: distance to be travelled (m)
:return:
v_f: the final speed (m/s)... | 44,508 |
def build_samples(ctx, version="DEBUG", filter="", delphi_version=DEFAULT_DELPHI_VERSION):
"""Builds samples"""
init_build(version)
delphi_projects = get_delphi_projects_to_build('samples', delphi_version)
return build_delphi_project_list(ctx, delphi_projects, version, filter, delphi_version) | 44,509 |
def write_table(fh, data, samples=None, tree=None, rankdic=None, namedic=None,
name_as_id=False):
"""Write a profile to a tab-delimited file.
Parameters
----------
fh : file handle
Output file.
data : dict
Profile data.
samples : list, optional
Ordered sa... | 44,510 |
def data_context_notification_context_notif_subscriptionuuid_notificationnotification_uuid_changed_attributesvalue_name_get(uuid, notification_uuid, value_name): # noqa: E501
"""data_context_notification_context_notif_subscriptionuuid_notificationnotification_uuid_changed_attributesvalue_name_get
returns tapi... | 44,511 |
def angular_misalignment_loss_db(n, w, theta, lambda0):
"""
Calculate the loss due to angular fiber misalignment.
See Ghatak eqn 8.75
Args:
n: index between fiber ends [-]
w: mode field radius [m]
theta: angular misalignment [radians]
lambda0... | 44,512 |
def test_mintempyear_failure():
"""Test that we can handle some GIGO here."""
text = get_test_file("CLI/CLISAD.txt")
prod = cliparser(text)
assert 2002 in prod.data[0]["data"]["temperature_minimum_record_years"] | 44,513 |
def queue(filename):
"""queue a file for playing
A maximum of one current and one queued is supported. If there is no current song, the queued song will fill that
slot and begin playing immediately. If the current slot is filled the queued song will be added to the queued slot,
and when the curren... | 44,514 |
def test_overridden_base_uri_must_be_uri_ref():
"""
The base URI, if specified, must match the URI-reference grammar. i.e. it
is a relative or absolute URI.
"""
bad_uri = "x:/some/path/spaces not allowed/oops"
assert not uri.is_uri_reference(bad_uri)
with pytest.raises(ValueError):
... | 44,515 |
def replace_number(token):
"""Replaces a number and returns a list of one or multiple tokens."""
if number_match_re.match(token):
return number_split_re.sub(r' @\1@ ', token)
return token | 44,516 |
def dnscl_rpz(
ip_address: str,
filename: str = FILENAME,
tail_num: int = 0,
quiet_mode: bool = False,
) -> int:
"""Return rpz names queried by a client IP address."""
start_time = timeit.default_timer()
rpz_dict: DefaultDict = defaultdict(int)
line_count = 0
ip_address_search = ip_a... | 44,517 |
def disable_site_packages():
"""
Remove all entries mentioning ``site-packages`` or ``Extras`` from
:attr:sys.path. Used primarily for testing on OS X within a virtualenv,
where OS X bundles some ancient version of the :mod:`six` module.
"""
for entry in sys.path[:]:
if 'site-packages' i... | 44,518 |
def case_args(methods):
"""Define benchmark parameters in this generator
Parameters
----------
methods : list of str
Voting methods to evaluate.
Yields
---------
args : tuple
Arguments passed onto benchmark `model` function.
"""
for i in range(15):... | 44,519 |
def test_pal_paljaxensemble(binh_korn_points):
"""Test the ensemble of finite width
neural networks with the Binh-Korn testfunction"""
X, y = binh_korn_points # pylint:disable=invalid-name
network_a = build_dense_network([512])
network_b = build_dense_network([512])
optimizer_a = get_optimize... | 44,520 |
def test_logged_in_has_authenticated_permission(web_server, dbsession: Session, browser, permission_app):
"""Logged in users can access views behind authenticated permission."""
b = browser
with transaction.manager:
create_user(dbsession, permission_app.init.config.registry)
b.visit(web_serve... | 44,521 |
def test_measure_containment():
"""Test measure_containment function"""
image = generate_gaussian_image()
frac = measure_containment(image, 0, 0, 0.2 * np.sqrt(2 * np.log(5)))
assert_allclose(frac, 0.8, rtol=0.01) | 44,522 |
def sweep_centroids(nrays, rscale, nbins, elangle):
"""Construct sweep centroids native coordinates.
Parameters
----------
nrays : int
number of rays
rscale : float
length [m] of a range bin
nbins : int
number of range bins
elangle : float
elevation angle [ra... | 44,523 |
def test_aggregate_chosen(
chosen: general.ParameterListType, value_type: type, assumed_results: dict
):
"""
Test aggregate_chosen.
"""
assert isinstance(chosen, list)
if len(chosen) > 0:
assert isinstance(chosen[0], dict)
result = subsampling.aggregate_chosen(chosen)
assert isi... | 44,524 |
def toc():
"""
对应MATLAB中的toc
:return:
"""
t = time.clock() - globals()['tt']
print('\nElapsed time: %.8f seconds\n' % t)
return t | 44,525 |
def assert_allclose(
actual: Tuple[float, numpy.float64, numpy.float64, numpy.float64],
desired: Tuple[float, numpy.float64, numpy.float64, numpy.float64],
rtol: float,
atol: float,
):
"""
usage.scipy: 2
"""
... | 44,526 |
def dashboard():
"""
This function deals with the server side of the flask application
:return: render the html page
"""
logging.info("client accessed either route")
deaths, hospital_cases, nat_week_ava = covid_API_request('England', 'Nation')
local_average = covid_API_request()[2]
... | 44,527 |
def read_images_binary(path_to_model_file):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesBinary(const std::string& path)
void Reconstruction::WriteImagesBinary(const std::string& path)
"""
images = {}
with open(path_to_model_file, "rb") as fid:
num_reg_i... | 44,528 |
def Filter_Readouts_by_RNAfold(cand_readout_file='selected_candidates_genome.fasta',
rnafold_exe=r'E:\Shared_Apps\ViennaRNA\RNAfold',
energy_th =-6.0, readout_folder=_readout_folder,
make_plot=False, verbose=True):
"""Filt... | 44,529 |
def suggest_name_as_missing_import(name, objdict, frame):
"""Suggest that name could come from missing import.
Example: 'foo' -> 'import mod, mod.foo'.
"""
for mod in STAND_MODULES:
if mod not in objdict and name in dir(import_from_frame(mod, frame)):
yield "'{0}' from {1} (not impo... | 44,530 |
def test_import_raw():
"""This tests whether the `tsdata` package loads a dataset."""
from tsdata.raw import available_data, load_data
assert len(available_data()) > 0
assert "LakeHuron" in available_data()
load_data("LakeHuron") | 44,531 |
def int3(params, ctxt, scope, stream, coord, interp):
"""Define the ``Int3()`` function in the interpreter. Calling
``Int3()`` will drop the user into an interactive debugger.
"""
if interp._no_debug:
return
if interp._int3:
interp.debugger = PfpDbg(interp)
interp.debugger.c... | 44,532 |
def CheckSyntaxCheap(lex):
""" Parse() builds a static tree of StaticObjs by parsing text file.
-The "lex" argument is afile or input stream which has been converted
to a "TemplateLexer" object (similar to the python's built-in shlex lexer).
"""
fnames_found = set([])
prematurely_read_token = ... | 44,533 |
def enable_loki_logging(default_config):
""" Start logging to Loki """
if not default_config.get("loki", None):
return
loki_url = default_config["loki"].get("url", None)
if not loki_url:
logging.warning("No Loki URL in config. Skipping Loki logging")
return
loki_username =... | 44,534 |
def __no_conflicts(items):
"""Return True if each possible pair, from a list of items, has no conflicts."""
return all(__no_conflict(combo[0], combo[1]) for combo in it.combinations(items, 2)) | 44,535 |
def _demo_home(options):
"""For convenience demo home is in the same folder as jar file"""
bp, fn = os.path.split(options.jar_file)
demo_home = os.path.join(bp, 'demo')
assert os.path.isdir(demo_home), 'Folder does not exist: "%s"' % demo_home
return demo_home | 44,536 |
def test_single_axial_reg(testdir):
"""Test that I can use just one simple axial region below the rod
bundle (rather than two, one above and one below)"""
inp = dassh.DASSH_Input(
os.path.join(testdir, 'test_inputs', 'input_one_axial_reg.txt')
)
assert len(inp.data['Assembly']['driver']['Axi... | 44,537 |
def valid_tetrodes(tetrode_ids, tetrode_units):
"""
Only keep valid tetrodes with neuron units so that there is corresponding spike train data.
:param tetrode_ids: (list) of tetrode ids in the order of LFP data
:param tetrode_units: (dict) number of neuron units on each tetrode
:return: (list) of t... | 44,538 |
def assert_array_equal(x: numpy.ndarray, y: Literal["red"]):
"""
usage.matplotlib: 1
"""
... | 44,539 |
def PreviewApply(source,
deployment_full_name,
stage_bucket,
messages,
location,
ignore_file,
source_git_subdir='.',
preview_format=_PREVIEW_FORMAT_TEXT,
config_controller=None):
"""... | 44,540 |
def get_us_week(date):
"""Determine US (North American) week number"""
# Each date belongs to some week. Each week has a Saturday. The week_sat_offset is number of
# days between the Saturday and the date:
week_sat_offset = (12 - date.weekday()) % 7
week_sat = date + datetime.timedelta(days=week_sat... | 44,541 |
def test_api_challenges_get_solve_info_score_visibility():
"""Does the challenge list API show solve info if scores are hidden?"""
app = create_ctfd()
with app.app_context(), app.test_client() as pub_client:
set_config("challenge_visibility", "public")
# Generate a challenge, user and solve... | 44,542 |
def _create_tag_graph(tag: str, nb=None):
""" --tag -> nb/graph-tag-{tag}.md
"""
tag = tag.strip('#')
ll = [ch for ch in ascii_uppercase] # link letters
for i in range(2, 31): # support ~800 notes here (but mermaid might break)
ll += [c*i for c in ascii_uppercase] # -> "AA", ... -> "AAA", ... ->
nnames = [n... | 44,543 |
def is_street_name(elem):
"""This function takes an element and returns whether it contains an attrib key
'addr:street'.
This is an modification from https://classroom.udacity.com/nanodegrees/nd002/parts/0021345404/modules/316820862075461/lessons/5436095827/concepts/54446302850923"""
return (elem.attr... | 44,544 |
def enforce_csrf(request):
"""
Enforce CSRF validation
"""
check = CSRFCheck()
# populates request.META['CSRF_COOKIE'], which is used in process_view()
check.process_request(request)
reason = check.process_view(request, None, (), {})
logging.warning(reason)
if reason:
# CSRF ... | 44,545 |
def run_fast_scandir(path: str, ext: List[str]) -> (List[str], List[str]):
"""
From [stack overflow](https://stackoverflow.com/a/59803793/9163028) answer
Searches all files with extensions below path
"""
subfolders, files = [], []
for i in os.scandir(path):
if i.is_dir():
su... | 44,546 |
def read_youtube_urls():
"""
Required format that the txt file containing the youtube urls must have:
url_1
url_2
.
.
.
url_n
:param filepath:
:return:
"""
yt_urls = []
file_to_read = askopenfile(mode="r", filetypes=[("Text file", "*.txt")])
... | 44,547 |
def mkdir_p(path: str) -> None:
"""Create directory tree, ignore if already exists"""
if not exists(path):
_logger.info('Creating directory `%s`', path)
makedirs(path) | 44,548 |
def _get_search_direction(state):
"""Computes the search direction to follow at the current state.
On the `k`-th iteration of the main L-BFGS algorithm, the state has collected
the most recent `m` correction pairs in position_deltas and gradient_deltas,
where `k = state.num_iterations` and `m = min(k, num_corr... | 44,549 |
async def get_config(guildid):
"""
:param guildid:
:return: Guild-Config as Json
"""
path = os.path.join("data", "configs", f"{guildid}.json")
with open(path, "r") as f:
data = json.load(f)
return data | 44,550 |
def basevectors_sm(time, dipole=None):
"""
Computes the unit base vectors of the SM coordinate system with respect to
the standard geographic coordinate system (GEO).
Parameters
----------
time : float or ndarray, shape (...)
Time given as modified Julian date, i.e. with respect to the ... | 44,551 |
def log_thermo(label, path):
"""
Logging thermodata from an Arkane output file
"""
logging.info('\n\n')
logging.debug('Thermodata for species {0}'.format(label))
thermo_block = ''
log = False
with open(path, 'r') as f:
line = f.readline()
while line != '':
if ... | 44,552 |
def rewrite_metadata(content, dic):
"""From content, which is the old text with the metadata and dic which has the new data, return new_txt which has data replaced by dic content, with relevant headers added """
#Splitting into headers and body. Technically, body is a list of paragraphs where first one is the ... | 44,553 |
def rotate_points(points, axis, angle, origin=None):
"""Rotates points around an arbitrary axis in 3D (radians).
Parameters:
points (sequence of sequence of float): XYZ coordinates of the points.
axis (sequence of float): The rotation axis.
angle (float): the angle of rotation in radian... | 44,554 |
def add_LeMaitre_fields(plot_axes, fontsize=8, color=(0.6, 0.6, 0.6)):
"""Add fields for geochemical classifications from LeMaitre et al (2002)
to pre-existing axes. If necessary, the axes object can be retrieved via
plt.gca() command. e.g.
ax1 = plt.gca()
add_LeMaitre_fields(ax1)
ax1.plot... | 44,555 |
def resolve_translation(instance, info, language_code):
"""Get translation object from instance based on language code."""
loader = TYPE_TO_TRANSLATION_LOADER_MAP.get(type(instance))
if loader:
return loader(info.context).load((instance.pk, language_code))
raise TypeError(f"No dataloader found ... | 44,556 |
def osu_import(file, folder):
"""Selects the specified archived file,
and extracts it into your osu! folder"""
zip_ref = zipfile.ZipFile(downloads_folder + file, 'r')
zip_ref.extractall(folder + file[:-4])
zip_ref.close()
print(file[:-4], "has been imported!")
os.remove(downloads_folder + f... | 44,557 |
def reverse_dict_old(dikt):
"""
takes a dict and return a new dict with old values as key and old keys as values (in a list)
example
_reverse_dict({'AB04a':'b', 'AB04b': 'b', 'AB04c':'b', 'CC04x': 'c'})
will return
{'b': ['AB04a', 'AB04b', 'AB04c'], 'c': 'CC04x'}
"""
new_dikt = {... | 44,558 |
def get_active_user(request):
"""
Endpoint for getting the active user
through the authtoken
"""
return Response(UserSerializer(request.user, context={'is_public_view': False}).data, status=status.HTTP_200_OK) | 44,559 |
def append_globals_to_builtins(globals, builtins):
"""Appends the SEAL context variables to the builtins.
This allows the following variables to be called from functions globally. Only use for testing purposes.
"""
variables = ["public_key", "secret_key", "relin_keys", "galois_keys",
... | 44,560 |
def subprocessdec(func, jobtype="source", cache_dir="."):
"""calls function as subprocess (allows for nested multiprocessing)"""
@wraps(func)
def nfunc(*args, **kwds):
# collapse args into kwds to dump to json
nkwds = genkwds(func, *args, **kwds)
kwds_hash = joblib.hash(nkwds)
... | 44,561 |
def upsert_website(admin_id, root, data, force_insert=False):
"""Method to update and insert new website to live streaming.
Args:
admin_id (str): Admin privileges flag.
root (str): Root privileges activation flag.
data (dict): ... | 44,562 |
def rest_query_object_by_id(bc_app, url, obj_id, json_obj_name, object_type, para_query_mode=False):
"""
query object by id
:param bc_app: used to attach app sign
:param url: do NOT contain params at the end
:param obj_id: object id
:param json_obj_name: like 'plan' for plan query
:param obj... | 44,563 |
def bert_clean_text(text):
"""Performs invalid character removal and whitespace cleanup on text."""
text = re.sub('[_—.]{4,}', '__', text)
text = unicodedata.normalize("NFKC", text)
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xFFFD or _is_control(char):
... | 44,564 |
def _fail_callback(die_lock_file: str,
actor_rank: int = 0,
fail_iteration: int = 6):
"""Returns a callback to cause an Xgboost actor to fail training.
Args:
die_lock_file (str): A file lock used to prevent race conditions
when causing the actor to fail... | 44,565 |
def get_successors(curr_seq):
""" Function to generate a list of 100 random successor sequences
by swapping any cities. Please note that the first and last city
should remain unchanged since the traveller starts and ends in
the same city.
Parameters
----------
curr_seq : [list]
[lis... | 44,566 |
def adjust_learning_rate(optimizer, epoch, lr_max):
"""https://towardsdatascience.com/faster-training-of-efficient-cnns-657953aa080"""
lr_min = lr_max/25
if epoch < 60:
lr = get_lr(epoch+4, cycle_len=5, lr_max=lr_max, lr_min=lr_min)
else:
lr = get_lr(epoch, cycle_len=60, lr_max=lr_min, l... | 44,567 |
def test_sagemaker_pyspark_sse_s3(role, image_uri, sagemaker_session, region, sagemaker_client):
"""Test that Spark container can read and write S3 data encrypted with SSE-S3 (default AES256 encryption)"""
spark = PySparkProcessor(
base_job_name="sm-spark-py",
image_uri=image_uri,
role=r... | 44,568 |
def sigint_handler(signum, frame):
"""Signal handler for SIGINT."""
logger.debug("caught SIGINT")
emulator = network_emulator.NetworkEmulator.get_instance()
emulator.stop() | 44,569 |
def refresh_assets(ctx, development=True):
"""
Clean up and refresh Collector's assets and config files
"""
# ensure BIN_PATH exists
if not os.path.exists(BIN_PATH):
os.mkdir(BIN_PATH)
dist_folder = os.path.join(BIN_PATH, "dist")
if os.path.exists(dist_folder):
shutil.rmtree... | 44,570 |
def fstart(cli, nick, chan, rest):
"""Forces the game to start immediately."""
cli.msg(botconfig.CHANNEL, "\u0002{0}\u0002 has forced the game to start.".format(nick))
start(cli, nick, botconfig.CHANNEL, forced = True) | 44,571 |
def Q(lambda_0, lambda_, eps_c, Delta, norm_zeta2, nu):
"""
Quadratic upper bound of the duality gap function initialized at lambda_0
"""
lmd = lambda_ / lambda_0
Q_lambda = (lmd * eps_c + Delta * (1. - lmd) +
0.5 * nu * norm_zeta2 * (1. - lmd) ** 2)
return Q_lambda | 44,572 |
def solve(equation):
"""
Solves equation using shunting-yard algorithm
:param equation: string
equation to be solved
:return: float
result of equation
"""
postfix = rpn(equation)
result = shunting_yard(postfix)
return result | 44,573 |
def get_project_url(): # pragma no cover
"""Open .git/config file and git the url from it."""
project_info = {}
try:
with open('./.git/config', 'r') as git_config:
for line in git_config:
if "url = git@" in line:
dont_need, need = line.split(' = ')
... | 44,574 |
def filter_yaml(yaml: Union[str, List[str], Blob], labels: dict=None, name: str=None, namespace: str=None, kind: str=None, api_version: str=None):
"""Call this with a path to a file that contains YAML, or with a ``Blob`` of YAML.
(E.g. it can be called on the output of ``kustomize`` or ``helm``.)
Captures the YA... | 44,575 |
def replace_one(
database: pymongo.database.Database, item: MongoDocument,
filter_keys: List, upsert=False):
"""Replaces one item in the database having the same filter_keys."""
filter = {key: item[key] for key in filter_keys}
database[item.__collection__].replace_one(filter, item, upsert=up... | 44,576 |
def sign_out(entry, time_out=None, forgot=False):
"""Sign out of an existing entry in the timesheet. If the user
forgot to sign out, flag the entry.
:param entry: `models.Entry` object. The entry to sign out.
:param time_out: (optional) `datetime.time` object. Specify the sign out time.
:param forg... | 44,577 |
def get_button_write(deck_id: str, page: int, button: int) -> str:
"""Returns the text to be produced when the specified button is pressed"""
return _button_state(deck_id, page, button).get("write", "") | 44,578 |
def process_file(module_doc):
"""
Read the given C{ModuleDoc}'s file, and add variables
corresponding to any objects defined in that file. In
particular, read and tokenize C{module_doc.filename}, and
process each logical line using L{process_line()}.
"""
# Keep track of the current line num... | 44,579 |
def test_hit_efa(
region,
scheduler,
instance,
pcluster_config_reader,
clusters_factory,
test_datadir,
architecture,
network_interfaces_count,
):
"""
Test all EFA Features.
Grouped all tests in a single function so that cluster can be reused for all of them.
"""
max_... | 44,580 |
def parse():
"""Parse the command line inputs and execute the subcommand."""
parser = generate_parser()
# Display help if no arguments are provided
if len(sys.argv) == 1:
parser.print_help()
else:
args = vars(parser.parse_args())
run_cmd = args.pop('run_cmd')
run_cm... | 44,581 |
def opensafety_a(data: bytes) -> int:
"""
Compute a CRC-16 checksum of data with the opensafety_a algorithm.
:param bytes data: The data to be computed
:return: The checksum
:rtype: int
:raises TypeError: if the data is not a bytes-like object
"""
_ensure_bytes(data)
return _crc_16_... | 44,582 |
def EM_frac(pdf, iters=30, EPS=1E-12, verbose=True):
""" EM-algorithm for unknown integrated class fractions
Args:
pdf : (n x K) density (pdf) values for n measurements, K classes
iter : Number of iterations
Returns:
frac : Integrated class fractions
"""
n = pdf.shape[0]
K = pdf.shape[1]
P = np.z... | 44,583 |
def quad_explain(output=sys.stdout):
"""
Print extra information about integrate.quad() parameters and returns.
Parameters
----------
output : instance with "write" method
Information about `quad` is passed to ``output.write()``.
Default is ``sys.stdout``.
Returns
-------
... | 44,584 |
def get_files(extensions, args):
"""Generates a list of paths whose boilerplate should be verified.
If a list of file names has been provided on the command line, it will be
treated as the initial set to search. Otherwise, all paths within rootdir
will be discovered and used as the initial set.
Once... | 44,585 |
def mark_output(cell: NotebookNode) -> None:
"""Mark text at cell outputs by flag.
Args:
cell (NotebookNode): Cell with outputs.
"""
output_flag = process_cell_collapse_output(cell)
for output in cell.outputs:
if output.get("name", None) == "stdout":
output.text = output... | 44,586 |
def gaussian_loss(y_true, y_pred, interval, eta):
""" non zero mean absolute loss for one batch
This function parameterizes a loss of the form
Loss = - exp(- x ^ 2 / 2*sigma ^ 2)
where x = y_true - y_pred and
sigma = eta * y_true
and eta is a constant, generally much less than 1
Args:
... | 44,587 |
def create(params):
"""
Create Neo4j Docker instance
:param params: dict
:return: Help message for end user
"""
con_name = params['dbname']
config_dat = Config.info[params['dbtype']]
volumes = config_dat['volumes']
for vol in volumes:
if vol[0] == 'DBVOL': vol[0] = params['db... | 44,588 |
def str_to_verbosity(verbosity_str: str) -> int:
"""
Return a logging level from a string (compared in lower case).
- `DEBUG` <=> {`debug`, `d`, `10`}
- `INFO` <=> {`info`, `i`, `20`}
- `WARNING` <=> {`warning`, `w`, `warn`}
- `ERROR` <=> {`error`, `e`, `err`}
.. code-block:: python... | 44,589 |
def revision(message, autogenerate, sql, head, splice, branch_label, version_path, rev_id):
"""Create a new revision file."""
config = _get_config()
alembic.command.revision(
config,
message,
autogenerate=autogenerate,
sql=sql,
head=head,
splice=splice,
branch_label=branch_label,
version_path=version... | 44,590 |
def create_registration_data(legal_type, identifier='FM1234567', tax_id=None):
"""Test data for registration."""
person_json = {
'officer': {
'id': 2,
'firstName': 'Peter',
'lastName': 'Griffin',
'middleName': '',
'partyType': 'person'
... | 44,591 |
def customization_data(client=None):
"""
Returns a Generator of ImportDefinitions (Customizations).
Install them using `resilient-circuits customize`
Contents:
- Message Destinations:
- fn_anomali_staxx
- Functions:
- staxx_query
- staxx_import
- Workflows:
-... | 44,592 |
def proctored_exam_results_csv(entry_id, xmodule_instance_args):
"""
Compute proctored exam results report for a course and upload the
CSV for download.
"""
action_name = 'generating_proctored_exam_results_report'
task_fn = partial(upload_proctored_exam_results_report, xmodule_instance_args)
... | 44,593 |
def get_twiter_position(twit, market):
"""
Get's Vicki's position on the appropriate stock
:param twit: Twitter API Object
:param market: The market pair which to observe
:type twit: twitter
:type market: str
:return: String contining Vicki's position on the relavant market
:rtype : st... | 44,594 |
def build_new_devices_list(module):
"""
Build List of new devices to register in CV.
Structure output:
>>> configlets_get_from_facts(cvp_device)
{
[
{
"name": "veos01",
"configlets": [
"cv_device_test01",
"S... | 44,595 |
def preprocess(input_path: str, image_size: int) -> Tuple[pd.Series, np.ndarray]:
"""
Preprocss imager data into a depth, image tuple.
Image is resized to a given width.
Additionally, to avoid floating point difficulties, depth measurements are converted
to centimeters and integer type.
Parame... | 44,596 |
def convert_session_to_sample(session_file, sample_file):
"""
convert_session_to_sample
"""
fout = open(sample_file, 'w')
with open(session_file, 'r') as f:
for _, line in enumerate(f):
session = json.loads(line.strip(), encoding="utf-8", \
o... | 44,597 |
def import_template_ids() -> List[str]:
"""Return a list of all the supported template IDs."""
return subprocess.check_output(["meme", "-list-templates"]).decode("utf-8").splitlines() | 44,598 |
def test136():
"""
ensure we grow a list when merging one in that contains strings
"""
cmd: ExecAction = ExecAction(command=['echo', 'wassup'])
dup: ExecAction = cmd.dup()
del dup.command[0]
dup.command[0] = None
dup.merge(cmd)
assert len(dup.command) == 2 | 44,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.