content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import time
def wait_for_job(res, ping_time=0.5):
"""
Blocks execution and waits for an async Forest Job to complete.
:param JobResult res: The JobResult object to wait for.
:param ping_time: The interval (in seconds) at which to ping the server.
:return: The completed JobResult
"""
while... | 1a7202f58affa97b0001b246fb7cd187d6a59f44 | 3,630,300 |
def _retr():
"""retrieves a list of all connected spectrometers for all backends"""
params, ids = [], []
if not _running_on_ci():
csb_serials, psb_serials = set(), set()
for serials, backend in [(csb_serials, csb), (psb_serials, psb)]:
if backend is None:
continue... | 3b418fe367ed522f376d840efc0883bfd6ea6e60 | 3,630,301 |
def get_individual_annotations(self, all=False, imported=True):
"""Returns a dict with non-empty individual annotations.
If `all` is true, also annotations with no value are included.
If `imported` is true, also include annotations defined in
imported ontologies.
"""
onto = self.namespace.onto... | c817f51d4918cc97b97c8db2a6d33ce720c6f6aa | 3,630,302 |
def numeric_type(param):
"""
Checks parameter type
True for float; int or null data; false otherwise
:param param: input param to check
"""
if ((type(param) == float or type(param) == int or param == None)):
return True
return False | a5f67a30b3128c1214d8825abbc6ae5170680d80 | 3,630,303 |
def _pre_aggregate_df(df,
dims,
aggregate_dimensions,
show_control,
ctrl_id,
sort_by=None,
auto_decide_control_vals=False,
auto_add_description=True):
"""Process a ... | 6b32b772bd6d1437160c90fff4fb965761431596 | 3,630,304 |
import os
import subprocess
def RunDsymUtil(dsym_path_prefix, full_args):
"""Linker driver action for -Wcrl,dsym,<dsym-path-prefix>. Invokes dsymutil
on the linker's output and produces a dsym file at |dsym_file| path.
Args:
dsym_path_prefix: string, The path at which the dsymutil output should be
... | 7efbffe4dca2f45e7d4c76555b27847281a62dac | 3,630,305 |
def search_data_start(file, identifier, encoding):
"""
Returns the line of an identifier for the start of the data in a file.
"""
if identifier is None:
return 0
search = open(file, encoding=encoding)
i = 1
for line in search:
if identifier in line:
search.close()... | 2c3c903df2162b9f6fe5452b75c4f7ac06ddd194 | 3,630,306 |
def p_sha1(secret, seed, sizes=()):
"""
Derive one or more keys from secret and seed.
(See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0)
Lengths of keys will match sizes argument
"""
full_size = 0
for size in sizes:
full_size += size
result = b''
accum = seed
while len(re... | f0080c973575537691779c50dd7d89fcefe0f2f5 | 3,630,307 |
def get_workload(batch_size, num_classes=1000, image_shape=(3, 224, 224), dtype="float32"):
"""Get benchmark workload for mobilenet
Parameters
----------
batch_size : int
The batch size used in the model
num_classes : int, optional
Number of classes
image_shape : tuple, option... | 1c86d4bd4322dbd8eaa9d07461ff900def79059a | 3,630,308 |
def delete_review(review_id):
"""
It allows the user to delete the review from the page
and automatically from the database as well.
Checks that the user deleting the review is the
creator of the review, as only the that user is allowed
to delete it's own content.
"""
review = mongo.db.... | d8d343ecf09e8f6de031e440e6a20b0b4b72bbe9 | 3,630,309 |
def quotient_mealy(mealy, node_relation=None, relabel=False, outputs={'loc'}):
"""Returns the quotient graph of ``G`` under the specified equivalence
relation on nodes.
Parameters
----------
mealy : NetworkX graph
The graph for which to return the quotient graph with the specified node
... | 9eb7b5652af276d9bfd2a23774fa91a68a5c90fc | 3,630,310 |
import os
import sys
def find_package_data(where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for... | 3cb778525ea08f0958e64ac8e982f55a82e5127c | 3,630,311 |
import requests
def perform_v1_search(khoros_object, endpoint, filter_field, filter_value, return_json=False, fail_on_no_results=False,
proxy_user_object=None):
"""This function performs a search for a particular field value using a Community API v1 call.
.. versionchanged:: 4.0.0
... | 00f7d6716529ff33342104776280da9dd8c788f2 | 3,630,312 |
def get_page_generator(s,max_items=0):
"""Get the generator that returns the Page objects
that we're interested in, from Site s.
"""
page_generator = s.allpages()
if(max_items>0):
page_generator.set_maximum_items(max_items)
return page_generator | d53a890523c999df878fecc71ef1dbd8d17c188c | 3,630,313 |
def get_num_in(profile, key_path):
"""Return the value pointed by the key path in the JSON profile."""
job = __get_job_obj(profile)
obj = job
for key in key_path:
obj = obj[key]
return obj | b432721c5813bfcb5927c39806ffac16470c4a58 | 3,630,314 |
import os
def file_basename_no_extension(filename):
""" Returns filename without extension
>>> file_basename_no_extension('/home/me/file.txt')
'file'
>>> file_basename_no_extension('file')
'file'
"""
base = os.path.basename(filename)
name, extension = os.path.splitext(base)
retur... | d4512a06ecc861d2b9e992691fbabb11b9e6e958 | 3,630,315 |
def rl_modelrl_medium():
"""Small set for larger testing."""
hparams = rl_modelrl_base()
hparams.true_env_generator_num_steps //= 2
return hparams | 6cf1a50a9b3f6d00f8f5ec1cddf33d813d9899ab | 3,630,316 |
def check_flow_information(flow, search_name, pos):
""" Try to find out the type of a variable just with the information that
is given by the flows: e.g. It is also responsible for assert checks.::
if isinstance(k, str):
k. # <- completion here
ensures that `k` is a string.
"""
... | 0ec44d86f87337d5ee0768da19a43a61d6bd1d40 | 3,630,317 |
def accuracy_measures(predictions, trues):
"""Accuracy measures for the predictions of the method vs the groundtruth.
Prints a confusion matrix, accuracy, misclassifcation rate, true positieve rate, false positive rate, specificity, precision, prevalence.
Returns the accuracy score, precision score, and rec... | 306fe745e3ff860d5d99e63d276acaa6f9d369cd | 3,630,318 |
def segment_text_to_sentences(text_file, sentence_splitter):
""" Segment text into sentences. Text is provided by BRAT in .txt
file.
Args:
text_file (str): the full path to the BRAT .txt file.
sentence_splitter (spacy LM): SpaCy EN language model.
Returns:
... | d74857a4931d162b9573b1b086a8720563b4fd41 | 3,630,319 |
def get_folder_offset(folder_list, folder_name):
"""
Check whether there is already a folder named 'folder_name' and if so, increment a counter.
"""
isExists = False
# Check whether a folder with the same name already exists
for folder in folder_list:
if folder['title'] == folder_name:... | b620e6ee6819b2b1aac6b3fd6a05775cde34838e | 3,630,320 |
def get_coords_for_radius(radius):
""" Given a radius, will return x,y coordinates with x=y.
This is useful for plotting the relation between the undistorted and distorted radius.
"""
sq = radius**2;
coord = np.sqrt(sq / 2);
return coord, coord; | 455c6afda78e1ef28980e39278bd77896957a7bf | 3,630,321 |
def _parse_array(values):
""" parse a list of (string) values representing a fortran array
and return a python list
"""
assert type(values) is list
parsed_value = []
for v in values:
if '*' in v:
# 3* "a" === "a", "a", "a"
mult, val = v.split('*')
pars... | 17888b900e06db2d6e766d90cff7184191d2c228 | 3,630,322 |
def word_frequency(text: str, use_cases: bool = False) -> dict[str,int]:
"""
Returns a dictionary of the frequency of all words in given string.
All words turned to lowercase if use_cases left unspecified.
Parameters
------------
text: str
The text to find the word frequency of.
u... | 6acfddc093c68e97c7f014ab7c93e33fd034af25 | 3,630,323 |
def param_to_string(metric) -> str:
"""Convert a list / tuple of parameters returned from IE to a string"""
if isinstance(metric, (list, tuple)):
return ', '.join([str(x) for x in metric])
else:
return str(metric) | 54476f88936336728ba73425bb57860e17fb7561 | 3,630,324 |
import re
def fix_subtitle_hierarchy(ctx, text):
"""Fix subtitle hierarchy to be strict Language -> Etymology ->
Part-of-Speech -> Translation/Linkage."""
assert isinstance(ctx, Wtp)
assert isinstance(text, str)
# Known language names are in languages_by_name
# Known lowercase PoS names are i... | 3ae42200b576e2370c807c7d973f36c2ffc7c8e4 | 3,630,325 |
import os
import json
def embed_dataset(id, source_folder, output_folder):
""" Here we are at the stage where the three splits starting from the training set have been computed.
We have then train.csv, valid.csv, test.csv files and the correspondent files with labels.
[train.csv, valid.csv, test.c... | 744904a1cb7965158e43059411f267797973bb31 | 3,630,326 |
def showStitchedModels_Redundant(mods, ax=None,
cmin=None, cmax=None, **kwargs):
"""Show several 1d block models as (stitched) section."""
x = kwargs.pop('x', np.arange(len(mods)))
topo = kwargs.pop('topo', x*0)
nlay = int(np.floor((len(mods[0]) - 1) / 2.)) + 1
if c... | 4b2428ab7d08c54b32e22c89785b3506e24e21f5 | 3,630,327 |
def export_16(text_col, processed_col, input_filepath,
output_filepath, country):
"""Takes in a file with 8 different sheets containing extracted text.
It will perform mulitple steps to clean the extracted text
and split each sheet into two smaller sheets.
Then export them individ... | 4c6f100c7fd992078f3e9e32aba494930464f625 | 3,630,328 |
import random
def generate_signal(ders, n, sampling, initial_state=None, number_of_variables=1, number_of_perturbations=1, warmup_time=1000.0, tau=3.0, eps=0.5, dt=0.01):
"""generates signal for the oscillator driven by correlated noise from dynamical equations
:param ders: a list of state variable derivatives
:... | f7ebd99aaaf0684b0c5c7a9380b18c6f00d70a50 | 3,630,329 |
from sys import stdout
import os
def get_first_last_line(filePath, encoding=stdout.encoding):
"""Return the first and the last lines of file
The existence of filePath should be check beforehand.
Args:
filePath (str): the path of the file
encoding (str): the encoding of the file. Default ... | 0d2da4c861e118b3b4d29bfc95ac3d56df7804e6 | 3,630,330 |
def getReviewRedirect(entity, params):
"""Returns the redirect to review the specified entity.
"""
return '/%s/review/%s' % (
params['url_name'], entity.key().id_or_name()) | f13aecf226e38809d183d5482e29fe40dfdd40c5 | 3,630,331 |
import imgaug.random
def current_random_state():
"""Get or create the current global RNG of imgaug.
Note that the first call to this function will create a global RNG.
Returns
-------
imgaug.random.RNG
The global RNG to use.
"""
return imgaug.random.get_global_rng() | 1d9064c11ca40e8dca80d456f5a27f3bc92494c6 | 3,630,332 |
def get_remote_station(s3, bucket, dataset_id=None, station_id=None, stn_key=None, version=3):
"""
"""
if isinstance(dataset_id, str):
stn_key = key_patterns[version]['station'].format(dataset_id=dataset_id, station_id=station_id)
try:
obj1 = s3.get_object(Bucket=bucket, Key=stn_key)
... | 477ca3ff9e940d5745b97c082ca36ba17058850c | 3,630,333 |
import os
def getURLitemBasename(url):
"""For a URL, absolute or relative, return the basename string.
e.g. "http://foo/bar/path/foo.dmg" => "foo.dmg"
"/path/foo.dmg" => "foo.dmg"
"""
url_parse = urlparse(url)
return os.path.basename(url_parse.path) | d4fd51b8a03a58f0edfc68662713ba6030564265 | 3,630,334 |
def determine_smallest_atom_index_in_torsion(atom1: 'rdkit.Chem.rdchem.Atom',
atom2: 'rdkit.Chem.rdchem.Atom',
) -> int:
"""
Determine the smallest atom index in mol connected to ``atom1`` which is not ``atom2``.
Retur... | 40ea2e151bd343fff208cb77e14122d021ee4733 | 3,630,335 |
import numpy
from typing import Optional
def structured_array_generic_full(
request: Request,
reader=Depends(reader),
slice=Depends(slice_),
expected_shape=Depends(expected_shape),
format: Optional[str] = None,
serialization_registry=Depends(get_serialization_registry),
):
"""
Fetch a ... | ffc68744741d66f36dd38b23996cf790eff10ff8 | 3,630,336 |
import requests
def _get_api_key(api_url: str, username: str, password: str, save: bool) -> str:
"""Get an RGD API Key for the given user from the server, and save it if requested."""
resp = requests.post(f'{api_url}/api-token-auth', {'username': username, 'password': password})
resp.raise_for_status()
... | c0adc024340310d2047d25c73772c530d17d81fe | 3,630,337 |
def fitness_func_large(vector):
""" returns a very large number for fitness"""
return 9999999999999999999 | 08e6f43c5f891fe7138dfc7b1d0809ba048bf070 | 3,630,338 |
def create_implicit_binary_heap(key_type=float):
"""Create an implicit (array-based) binary heap.
:param key_type: the key type
:type key_type: float, int or object
:returns: the heap
:rtype: :py:class:`.Heap`
"""
heap_type = _HeapType.HEAP_TYPE_BINARY_IMPLICIT
return _create_and_wrap_... | b598a8525b47e65a97578a69d40e22866cf65b4d | 3,630,339 |
def Prob_APD_select_v2(
fitness: list,
uncertainty: list,
vectors: "ReferenceVectors",
penalty_factor: float,
ideal: list = None,
):
"""Select individuals for mating on basis of Angle penalized distance.
Args:
fitness (list): Fitness of the current population.
... | a562c5908d6dab5ca231220dda1eec94f5020d86 | 3,630,340 |
import os
def get_initial_band_powers(bands_min, bands_max, idx_zbin1, idx_zbin2):
"""
get_initial_band_powers(bands_min, bands_max, idx_zbin1, idx_zbin2)
Function supplying the initial guess for the requested {'EE', 'BB', 'EB'} band
powers for the current redshift bin correlation idx_zbin1 x idx_zbi... | 0351ebf0314c687439ed183c07172a03d81e2981 | 3,630,341 |
def remove_prefix(s, pre):
"""
Remove prefix from the beginning of the string
Parameters:
----------
s : str
pre : str
Returns:
-------
s : str
string with "pre" removed from the beginning (if present)
"""
if pre and s.startswith(pre):
return s[len(pre):]
... | 6bae14cddd38fcfabfb0fadb9f4dbeaea81ff4ac | 3,630,342 |
import logging
import os
import glob
import gc
def raw_screenshots_analysis(jobs, job_id):
"""
Returns a report (dict) with:
report["raw_screenshot_mse"] = 0. <- [0, 100], 0 meaning images are equal
report["raw_screenshot_ssim"] = 0. <- [0, 100], 100 meaning images are equal
report["ra... | 1415d2f8a0c81579a7cc9ed6a24c70c037938f2e | 3,630,343 |
def parseString(string, namespaces=True):
"""Parse a document from a string, returning the resulting
Document node.
"""
if namespaces:
builder = ExpatBuilderNS()
else:
builder = ExpatBuilder()
return builder.parseString(string) | bd1da0d0deddd1d09c92979587ffa69e83b54063 | 3,630,344 |
import os
def vcs_dir_contents(path):
"""Return the versioned files under a path.
:return: List of paths relative to path
"""
repo = path
while repo != "/":
if os.path.isdir(os.path.join(repo, ".git")):
ls_files_cmd = [ 'git', 'ls-files', '--full-name',
... | 29adf24f1403ef1a33006a8265c9590c5b2a6f22 | 3,630,345 |
def prompt_present(nbwidget):
"""Check if an In prompt is present in the notebook."""
if WEBENGINE:
def callback(data):
global html
html = data
nbwidget.dom.toHtml(callback)
try:
return ' [ ]:' in html
except NameError:
re... | 9ee7aacf6ad03a22b3b4c002b121e8b61f3649b0 | 3,630,346 |
def _search_range(elem, session, query=None):
"""Perform a range search for DA, DT and TM elements with '-' in them.
Parameters
----------
elem : pydicom.dataelem.DataElement
The attribute to perform the search with.
session : sqlalchemy.orm.session.Session
The session we are using ... | 57ae970c8864f3c00b1df09d3d490a98f6fa82b3 | 3,630,347 |
def is_repo_user(repo_obj, username=None):
""" Return whether the user has some access in the provided repo. """
if username:
user = username
else:
if not authenticated():
return False
user = flask.g.fas_user.username
if is_admin():
return True
usergrps ... | 1692814dcdf967ce31a75d613958851a2ee9a8ad | 3,630,348 |
def block_distance(p1, p2):
"""
Returns the Block Distance of a particular point from rest of the points in dataset.
"""
distance = 0
for i in range(len(p1)-1):
distance += abs(p1[i]-p2[i])
return distance | 29d7febe0bd8fcdfc16cbc27c7f3490f265c9daf | 3,630,349 |
def display_profiles():
"""
Function that returns all save profiles
"""
return Passwords.display_profiles() | 162e5685ccb98c5b962737d2ee2866bc2dca0525 | 3,630,350 |
from contextlib import suppress
def mutate(
_data,
*args,
_keep="all",
_before=None,
_after=None,
**kwargs,
):
"""Adds new variables and preserves existing ones
The original API:
https://dplyr.tidyverse.org/reference/mutate.html
Args:
_data: A data frame
_keep... | d4af5ca1fa9cd423ac3ec036897703e9f636a725 | 3,630,351 |
def test_triangular_mesh():
"""An example of a cone, ie a non-regular mesh defined by its
triangles.
"""
n = 8
t = np.linspace(-np.pi, np.pi, n)
z = np.exp(1j * t)
x = z.real.copy()
y = z.imag.copy()
z = np.zeros_like(x)
triangles = [(0, i, i + 1) for i in range(1, n)]
x... | 4367786b129167223f64f04b989afb79fa536004 | 3,630,352 |
def pos_tag(tokenized_text):
"""
Averaged perceptron tagger from NLTK (originally from @honnibal)
"""
return pos_tag_sents([tokenized_text])[0] | 0405d3090d59260303c82eca46578878246f257d | 3,630,353 |
def cabbeling(SA, CT, p):
"""
Calculates the cabbeling coefficient of seawater with respect to
Conservative Temperature. This function uses the computationally-
efficient expression for specific volume in terms of SA, CT and p
(Roquet et al., 2015).
Parameters
----------
SA : array-lik... | 49ea1ce3485b5b4778702c12a17803ba7ef15de0 | 3,630,354 |
def _variant_to_dsl_helper(tokens) -> Variant:
"""Convert variant tokens to DSL objects.
:type tokens: ParseResult
"""
kind = tokens[KIND]
if kind == HGVS:
return Hgvs(tokens[HGVS])
if kind == GMOD:
concept = tokens[CONCEPT]
return GeneModification(
name=co... | bacb81138e0310a787e9f9d4fb490ad0a4215297 | 3,630,355 |
def remove_empty(df):
"""
Drop all rows and columns that are completely null.
Implementation is shamelessly copied from `StackOverflow`_.
.. _StackOverflow: https://stackoverflow.com/questions/38884538/python-pandas-find-all-rows-where-all-values-are-nan # noqa: E501
Functional usage example:
... | c2ea9fc13bfa57bc357a83c607bfe9ce9348fb2e | 3,630,356 |
from typing import Optional
def calculate_serving_size_weight(
weight: Optional[float], number_of_servings: Optional[float]
) -> Optional[float]:
"""
Given a weight (representing the total weight of the
component included in a recipe) and a number of servings
(how many servings of the component ar... | b22732a60f1f6000277861a615c78e785b4757bb | 3,630,357 |
def validate_positive(value):
"""Check if number is positive."""
if value is not None and value <= 0:
raise ValidationError(f'Expected a positive number, but got {value}')
return value | d4c84a8f8aa476af4e9169b25887f5e5344f22af | 3,630,358 |
import os
from datetime import datetime
import tempfile
import traceback
import subprocess
import sys
def main(args):
"""Process arguments and run validation"""
# Set variables for directory and list of studies
root_dir = args.root_directory
studies = args.list_of_studies
# If studies are filled... | eefbb1307d8101ef479f8ab7b85a29406ef5ce4e | 3,630,359 |
def filter_invalid_matches_to_single_word_gibberish(
matches,
trace=TRACE_FILTER_SINGLE_WORD_GIBBERISH,
reason=DiscardReason.INVALID_SINGLE_WORD_GIBBERISH,
):
"""
Return a filtered list of kept LicenseMatch matches and a list of
discardable matches given a `matches` list of LicenseMatch by remov... | cae97da74f23db50b4c8ed8f6e1b1659eb73f685 | 3,630,360 |
import json
def start_game(player1, player2, symbols=("O", "X")):
"""Starts a command line tic tac toe game between 2 players (bot or human)"""
assert len(symbols) == 2, "`symbols` must have exactly 2 elements"
gstate = TicTacToe("_________", symbols=symbols)
with open(GAME_TREE_FILE, "r") as gt_fil... | 96e712b399596bd2373c35c4e46e283c7efd8317 | 3,630,361 |
def despike_l1b_array(data, dqf, filter_width=7):
"""
Despike SUVI L1b data and return a despiked `numpy.ndarray`.
Parameters
----------
data : `numpy.ndarray`
Array to despike.
dqf : `numpy.ndarray`
Data quality flags array.
filter_width: `int`, optional.
The filter... | 57c3b757856a1c030c245472445f51b33c576cd2 | 3,630,362 |
def scrape(query: str,
listing_age: int = None,
relevance: str = None,
job_type: list = None,
experience: list = None,
locations: list = ['Singapore'],
limit: int = None,
**kwargs):
"""
:param query: str
Job search query
:... | 493cd2efff208d49ca5ce0d05814a0f73c872846 | 3,630,363 |
from datetime import datetime
import json
import os
def info( request ):
""" Returns basic info about the easyrequest_hay webapp.
Triggered by root easyrequest_hay url. """
log.debug( '\n\nstarting info(); request.__dict__, ```%s```' % request.__dict__ )
start = datetime.datetime.now()
context... | 06afce552c2fb98f9eb78daebec3220b2901dd09 | 3,630,364 |
def run_command(arguments, parse_stdout=True):
"""Run a command
Args:
A list with the arguments to execute. For example ['ls', 'foo']
Returns:
stdout, return status.
"""
try:
cmd = sp.Popen(arguments, stdout=sp.PIPE, stderr=sp.STDOUT)
stdout, _ = cmd.communicate()
... | a2183d8c588f0e749462c225e62183df46ac04b0 | 3,630,365 |
def format_key(key):
"""
Format the key provided for consistency.
"""
if key:
return key if key[-1] == "/" else key + "/"
return "/" | 8b5e41bb76c524ec8c45a22ad0dae84c84ed530b | 3,630,366 |
def get_random_parent_asset(instance_id: int, instance_start_id, instance_end_id) -> int:
"""
get random parent asset not linked to any child assets
:param instance_id: asset instance_id
"""
child_list = [instance_id]
child_list = get_child_assets_id(child_list, instance_id)
all_list = list... | 1f366ec08fdda6cfc8157bb6dc862a9700844409 | 3,630,367 |
def logout() -> Response:
"""API call: logout of the system."""
config = CorporaAuthConfig()
client = get_oauth_client(config)
params = {"returnTo": config.redirect_to_frontend, "client_id": config.client_id}
response = redirect(client.api_base_url + "/v2/logout?" + urlencode(params))
# remove t... | 2c9dd72d80ad4a8c27c9da508a932e7dca008ce7 | 3,630,368 |
import time
def elapsed_printer(func):
"""
**中文文档**
此包装器可以打印函数的输入参数, 以及运行时间。
"""
def _wrapper(*args, **kwargs):
print(">>> %s # Running ..." %
_text_of_func_args_and_kwargs(func, args, kwargs))
st = time.clock()
res = func(*args, **kwargs)
elapsed =... | 396289476d48e91185eae4f5e88691b2dd0756ec | 3,630,369 |
def get_init_fn():
"""Returns a function run by the chief worker to warm-start the training."""
checkpoint_exclude_scopes=["resnet_v1_101/logits","resnet_v1_101/fc","deconv32"]
exclusions = [scope.strip() for scope in checkpoint_exclude_scopes]
variables_to_restore = []
for var in slim.ge... | b6ca552c9d1b9cbe67e7cb9af16b8676c107124e | 3,630,370 |
def buildings_from_polygon(polygon, retain_invalid=False):
"""
Get building footprints within some polygon.
Parameters
----------
polygon : Polygon
retain_invalid : bool
if False discard any building footprints with an invalid geometry
Returns
-------
GeoDataFrame
"""
... | 85ecf11c5dfe6d717dffb52c80b1195138dfc556 | 3,630,371 |
from typing import Dict
def _define_problem_with_groups(problem: Dict) -> Dict:
"""
Checks if the user defined the 'groups' key in the problem dictionary.
If not, makes the 'groups' key equal to the variables names. In other
words, the number of groups will be equal to the number of variables, which
... | ab29954f3349509a9153219d040feb8fa3125ec7 | 3,630,372 |
def ljk(epsilon):
"""
Calculates ecliptic triad vectors with respect to BCRS-frame.
(Lindegren, SAG-LL-35, Eq.1)
:param epsilon: obliquity of the equator.
:return: np.array, np.array, np.array
"""
l = np.array([1,0,0])
j = np.array([0, np.cos(epsilon), np.sin(epsilon)])
k = np.arra... | 9e7d8ca724c9bfad11e561f5e6873b938b613341 | 3,630,373 |
from re import DEBUG
def send_mail(subject, message, recipient_list, request):
"""
Wrapper for send_mail() with logging and error messaging
:param subject: Message subject (string)
:param message: Message body (string)
:param recipient_list: Recipients of email (list)
:param request: Request o... | ebc9674b37a3eebb074024d00b9ef5ad172800f8 | 3,630,374 |
def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... | 5608857697c0d6ae46d3d34577f2b4002bacdc28 | 3,630,375 |
import re
def _build_regex(pattern):
"""Compile regex pattern turn comma-separated list into | in regex."""
compiled_pattern = None
if pattern:
# Trip ' " at the beginning and end
pattern = re.sub("(^\"|^\'|\"$|\'$)", "", pattern)
# Escape
pattern = re.sub("/", r"\/", pattern)
# Change "a,... | 7351f461a867b7c875749c6d88fdd5f2b26da496 | 3,630,376 |
def fpSub(rm, a, b, ctx=None):
"""Create a Z3 floating-point subtraction expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpSub(rm, x, y)
fpSub(RNE(), x, y)
>>> fpSub(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_sub... | 2513a4ee917d1e3a773a3637c519a85df28abd69 | 3,630,377 |
def reconstruct_contractility(simulation_folder, d_cyl, l_cyl, r_outer, scalef = 1000, scaleu = 1, scaleb = 1):
"""
Reconstruct the contractility of a given cylindric simulation. Also calculates residuum forces of Inclusion surface and matrix,
which shoould be equal (use to certify simulation and detect ... | f55369580d87e55061934149fad9598c5a29a1fe | 3,630,378 |
def categorical_sample(d):
"""Randomly sample a value from a discrete set based on provided probabilities.
Args:
d: A dictionary mapping choices to probabilities.
Returns:
One of the possible choices.
"""
choice_probs = list(d.items())
probs = [t[1] for t in choice_probs]
... | e99949ebc6d0314f3c2b791415af30c0fe6ed519 | 3,630,379 |
def gaspari_cohn_mid(z,c):
"""
Gaspari-Cohn correlation function for middle distances (between c and 2*c)
Arguments:
- z: Points to be evaluated
- c: Cutoff value
"""
return 1./12*(z/c)**5 - 0.5*(z/c)**4 + 5./8*(z/c)**3 \
+ 5./3*(z/c)**2 - 5*z/c - 2./3*c/z + 4 | 0852e84c1ce10856d69420fcc585054488591e73 | 3,630,380 |
import click
import concurrent
def put(local_file, remote_file, outmode, template, recursive, process):
"""
upload file
example:
pypssh -t 192.168.31.1 put /etc/yum.conf /etc/yum.conf
"""
def _progress(filename, size, sent, peername):
click.echo("(%s:%s) %s's progress: %.2f%% \r" %... | 699bd72c5349609513fdcb45ddd428ad6dfad684 | 3,630,381 |
def home_view(request):
"""
DESCRIPTION:
The only FBV to redirect to the original home_view
"""
# image = {'image': 'https://picsum.photos/1024/756'}
image = {}
return render(request, 'home.html', image) | 24d9602004b696610a69c6f38212db06d272a5c2 | 3,630,382 |
import time
import six
def hparams_pb(hparams, trial_id=None, start_time_secs=None):
# NOTE: Keep docs in sync with `hparams` above.
"""Create a summary encoding hyperparameter values for a single trial.
Args:
hparams: A `dict` mapping hyperparameters to the values used in this
trial. Keys ... | 835edf3b8e6a9def39cf33233215801948a20859 | 3,630,383 |
def create_agents(nagi, age_all, nr_infec, nr_immucmpr, nr_freeroam, nr_social):
"""
Creates the array of agents that will be used in the simulation
Parameters
----------
nagi : int
number of human agents that will be created.
age_all : numpy array of ints
distribution of the ag... | 23b0e92e281521dadcba47f8bfb5b2e8f5de2803 | 3,630,384 |
def get_top_level_data(end, start=20, get_fight_card_stats=False, both=True, avg_pause=.6):
"""
@param end: integer
@param start : integer
@param get_fight_card_stats :
@param both : boolean
@param avg_pause : float
"""
def add_d_set(df_use, name):
df = df_use.copy()
df... | 5d46f67d370b2c9c431f97f132338ca55edf609c | 3,630,385 |
def compute_normalization_binary_search(activations,
t,
num_iters = 10):
"""Returns the normalization value for each example (t < 1.0).
Args:
activations: A multi-dimensional array with last dimension `num_classes`.
t: Temperat... | 86859bf5834c791e1aa268784a1d353ba192551e | 3,630,386 |
from copy import deepcopy
def _match_units(filter_params, fps, fname):
"""
author: EM
The filtering thresholds must match the timeseries units. If the right
conversion is not possible, then check_ok is False, and the feature
summaries will not be calculated for this file.
"""
if filter_p... | de260a5570656c3c419c5df96ef6ad7bc75ff114 | 3,630,387 |
import time
import subprocess
import json
import logging
def gatherMetrics(varnishstatExe, fields):
"""Gather varnish metrics using varnishstat.
:param varnishstatExe: Path to the varnishstat executable.
:param fields: Field inclusion glob for varnishstat.
:return: A tuple containing the timestamp of... | 13550155c06342ee493a720e2df03ae7cc6a321c | 3,630,388 |
def squared_jumps(tracks, n_frames=1, start_frame=None, pixel_size_um=0.16,
pos_cols=["y", "x"]):
"""
Given a set of trajectories, return all of the the squared jumps
as an ndarray.
args
----
tracks : pandas.DataFrame. Must contain the "trajectory"
and "f... | 4fb75a9c4c65c8e8498156defbd4ea1ebfdd1c25 | 3,630,389 |
from typing import get_args
def main():
"""Change vowels of the text into the one selected ("a" as default)"""
args = get_args()
new_text = ''
for char in args.text:
if char in ['a','e','i','o','u']:
new_text = args.text.replace(char, args.vowel) ## doesn't work like this, l... | 638f00d93f53ac56ea6a6c4c1a1893a7abf8dfc3 | 3,630,390 |
def _mt_transpose_ ( self ) :
"""Transpose the graph:
>>> graph = ...
>>> graph_T = graph.transpose ()
>>> graph_T = graph.T() ## ditto
"""
new_graph = ROOT.TMultiGraph()
new_graph._graphs = []
_graphs = mgraph.GetListOfGraps()
for g in _graphs :
tg = g.T(... | 905936ee404551548fdd789489fdba9d9dcc8f3f | 3,630,391 |
import collections
def recursive_dictionary_update(d, u):
"""
Given two dictionaries, update the first one with new values provided by
the second. Works for nested dictionary sets.
:param d: First Dictionary, to base off of.
:param u: Second Dictionary, to provide updated values.
:return: Dic... | 7a040ee36d8d101ed3ce40f96c21c003c5410803 | 3,630,392 |
def uname(space):
""" uname() -> (sysname, nodename, release, version, machine)
Return a tuple identifying the current operating system.
"""
try:
r = os.uname()
except OSError, e:
raise wrap_oserror(space, e)
l_w = [space.wrap(i) for i in [r[0], r[1], r[2], r[3], r[4]]]
retu... | 40ba4d2178fd2701d1ebd07e45c88073efd046e3 | 3,630,393 |
def load_model(
model_path=filepath + "/trained_models/cmu/", model_file_name="model.h5"
):
"""
loads a pre-trained word boundary model
:return: Seq2Seq object
"""
model_path = (
filepath + "/trained_models/{}/".format(model_path)
if model_path in ["cmu"]
else model_path
... | 27e90f879dd06a840ff5fe4589fd0f98b9786ba1 | 3,630,394 |
def _tol_sweep(arr, tol=1e-15, orders=5):
"""
Find best tolerance 'around' tol to choose nonzero values of arr.
# Sweeps over tolerances +- 'orders' orders of magnitude around tol and picks the most
# stable one (one corresponding to the most repeated number of nonzero entries).
Parameters
---... | 6acfce610fe98f4a1aeb4e3417796dd56901f402 | 3,630,395 |
def test_coo_attr():
"""
Feature: Test COOTensor GetAttr in Graph and PyNative.
Description: Test COOTensor.indices, COOTensor.values, COOTensor.shape.
Expectation: Success.
"""
indices = Tensor([[0, 1], [1, 2]])
values = Tensor([1, 2], dtype=mstype.float32)
shape = (3, 4)
coo = COOT... | 17cccc6d45cd2c48d39279d7e7055224fdfb54ec | 3,630,396 |
def get_resource_path_if_exists(atlas_category, id):
""" If the specified ID exists in the atlas, return the full path """
atlas_path = ATLAS_CATEGORIES.get(atlas_category)
atlas = get_atlas(atlas_path)
if id in atlas.textures:
logger.debug(f'Found {id} in atlas')
return f'{atlas_path}/{... | 3b61a8db1299900e8cf9bd6e5f716d7c9a71e8a4 | 3,630,397 |
def get_all_parties():
"""this gets all parties"""
if not app.api.routes.models.political.parties:
return Responses.not_found("No created parties yet"), 404
return Responses.complete_response(app.api.routes.models.political.parties), 200 | e212a15d5296bb9ba6e288a582e829d714bf225a | 3,630,398 |
def send(channel, apdu: list) -> bytes:
"""
Send APDU to the channel and return the data if there are no errors.
"""
data, sw1, sw2 = channel.transmit(apdu)
# success
if [sw1, sw2] == [0x90, 0x00]:
return bytes(data)
# signals that there is more data to read
elif sw1 == 0x61:
... | bb3a1e52b6fdb5480b23f0646e768a7f90500acd | 3,630,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.