content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def unset(config, field):
"""Unset a field of the configuration.
Parameters
----------
config : Configurable
The configuration to manipulate.
field : list of str
The series of field names.
Raises
------
ValueError
If there is no such field.
"""
type(conf... | 5,353,800 |
def get_trigger_function(trigger_message, waiter):
"""Función auxiliar que genera un activador
Args:
trigger_message: mensaje o instruccion para continuar.
waiter: función que pausa el flujo de instrucciones.
"""
def trigger_function():
# Se imprime la instrucción par... | 5,353,801 |
def find_peaks(amplitude):
"""
A value is considered to be a peak if it is higher than its four closest
neighbours.
"""
# Pad the array with -1 at the beginning and the end to avoid overflows.
padded = np.concatenate((-np.ones(2), amplitude, -np.ones(2)))
# Shift the array by one/two value... | 5,353,802 |
def sync(
*,
client: Client,
json_body: CustomFieldOptionsCreateRequestBody,
) -> Optional[CustomFieldOptionsCreateResponseBody]:
"""Create Custom Field Options
Create a custom field option. If the sort key is not supplied, it'll default to 1000, so the option
appears near the end of the list.... | 5,353,803 |
def decrypt_with_private_key(data, private_key):
"""Decrypts the PKCS#1 padded shared secret using the private RSA key"""
return _pkcs1_unpad(private_key.decrypt(data)) | 5,353,804 |
def loadvars(builddir):
"""if builddir does not exist or does not have a cache, returns an
empty odict"""
v = odict()
if builddir is None or not os.path.exists(builddir):
return v
c = os.path.join(builddir, 'CMakeCache.txt')
if os.path.exists(c):
with open(c, 'r') as f:
... | 5,353,805 |
def deprecated (func):
"""
This is a decorator which can be used to mark functions as deprecated. It
will result in a warning being emitted when the function is used.
:param func: original function
:type func: :any:`collections.Callable`
:return: decorated func
:rtype: :any:`collections.Callable`
"""
... | 5,353,806 |
def prediction():
"""
A function that takes a JSON with two fields: "text" and "maxlen"
Returns: the summarized text of the paragraphs.
"""
print(request.form.values())
paragraphs = request.form.get("paragraphs")
paragraphs = re.sub("\d+", "", paragraphs)
maxlen = int(request.form.get("m... | 5,353,807 |
def check_relation_equivalence(
record: tinydb.database.Document,
r_type: str
) -> None:
""" Tests if specified record is self-consistent and enforces hierarchy
downstream. The "relations" field only exists when a record is obtained
through a query (i.e. .read(...), .read_all(...))
# C... | 5,353,808 |
def is_reviewer(user):
"""Return True if this user is a financial aid reviewer"""
# no need to cache here, all the DB lookups used during has_perm
# are already cached
return user.has_perm("finaid.review_financial_aid") | 5,353,809 |
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output(["git","log","--format=%B","-n","1",commitSHA])
return output.strip() | 5,353,810 |
def get_old_stacks(cfn, old_instances, debug=True):
""" Gets all of the stacks for the old RDS instances """
old_stacks = get_cfn_stack_for_rds(cfn, old_instances, debug)
if debug:
print("DEBUG: Old stacks found: %s" % len(old_stacks))
return old_stacks | 5,353,811 |
def set_initialized(initialized):
"""
set the initialization state of the local node
@param initialized: True if node initialized
@type initialized: bool
"""
global _client_ready
_client_ready = initialized | 5,353,812 |
def sup(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translat... | 5,353,813 |
def isnonempty(value):
"""
Return whether the value is not empty
Examples::
>>> isnonempty('a')
True
>>> isnonempty('')
False
:param value: string to validate whether value is not empty
"""
return value != '' | 5,353,814 |
def InstallSystem(config, deployment, options):
"""Install the local host from the sysync deployment configuration files."""
installed = {}
# Create fresh temporary directory
Log('Clearing temporary deployment path: %s' % config['deploy_temp_path'])
run.Run('/bin/rm -rf %s' % config['deploy_temp_path'])
... | 5,353,815 |
def preprocess_input(x):
"""前処理。"""
return tf.keras.applications.imagenet_utils.preprocess_input(x, mode="torch") | 5,353,816 |
def attribute_to_partner_strict(partner, partner_string_or_spec, amount):
"""Return the amount attributable to the given partner."""
spec = (
partner_string_or_spec
if isinstance(partner_string_or_spec, dict)
else parse_partner_string(partner_string_or_spec)
)
if partner not in s... | 5,353,817 |
def _set_op_arguments(mx_operators):
"""Fetch and set operator arguments - nargs, arg_names, arg_types
"""
for op_name in mx_operators:
operator_arguments = mx.operator.get_operator_arguments(op_name)
mx_operators[op_name]["params"] = {"narg": operator_arguments.narg,
... | 5,353,818 |
def drawLines(img, lines, color=(255,0,0)):
"""
Draw lines on an image
"""
centroids = list()
r_xs = list()
r_ys = list()
for line_ in lines:
for rho,theta in line_:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
... | 5,353,819 |
def moments_of_inertia(geo, amu=True):
""" principal inertial axes (atomic units if amu=False)
"""
ine = inertia_tensor(geo, amu=amu)
moms, _ = numpy.linalg.eigh(ine)
moms = tuple(moms)
return moms | 5,353,820 |
def greenblatt_earnings_yield(stock, date=None, lookback_period=timedelta(days=0), period='FY'):
"""
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ['AAPL', 'BA']).
:param date: Can be a datetime (i.e. datetime(2019, 1, 1)) or list of datetimes. The most recen... | 5,353,821 |
def today(context=None):
"""Overwrite <today>.json.gz with all data since 00:00 UTC"""
start = last_midnight_utc()
end = now_utc()
data = getdata(end=end, start=start, context=context)
prettydate = f"{end.date().isoformat()}"
log_head_tail(data)
with gzip.open(prettydate + ".json.gz", "wt", ... | 5,353,822 |
def remove_directory(dir_path):
"""Delete a directory"""
if isdir(dir_path):
try:
shutil.rmtree(dir_path)
return ok_resp(f'Directory removed {dir_path}')
except TypeError as err_obj:
return err_resp(f'Failed to remove directory. {err_obj}')
except Fil... | 5,353,823 |
def deploy(c, rebuild_=False, stack=False, prod=False, ngrok=False):
"""
Deploy the airflow instance.
Args:
c: invoke context
rebuild_: rebuild the images prior to deployment
stack: use docker swarm mode
prod: deploy to production
ngrok: deploy locally, but expose to... | 5,353,824 |
def new_eps_after(since_ep):
"""
:param since_ep: Episode instance
:return: Number of episodes since then
"""
session = Session.object_session(since_ep)
series = since_ep.series
series_eps = session.query(Episode).join(Episode.series).\
filter(Series.id == series.id)
if series.id... | 5,353,825 |
def parse_json_main_index(out_dir: Path=OUTPUT_DIR) -> Iterator[Link]:
"""parse an archive index json file and return the list of links"""
index_path = os.path.join(out_dir, JSON_INDEX_FILENAME)
if os.path.exists(index_path):
with open(index_path, 'r', encoding='utf-8') as f:
links = py... | 5,353,826 |
def commercetools_api(functionapp_env):
"""
Intercept any HTTP requests.
This uses requests mocker, so be careful with mocking other endpoints.
"""
with backend_mocker() as m:
yield m | 5,353,827 |
def header_maxperdisc(ctx, institution, requirement_id):
"""
header_maxperdisc : maxperdisc label? ;
"""
if DEBUG:
print(f'*** header_maxperdisc({class_name(ctx)=}, {institution=}, {requirement_id=}',
file=sys.stderr)
return_dict = {'label': get_label(ctx)}
maxperdisc_ctx = ctx.maxperdis... | 5,353,828 |
def get_solrj_connection_affinity(zk_client):
"""
Get information about where SolrJ clients are connected
This shows information about SolrJ clients, the ip-addresses they are comming from, and the Zookeeper
hosts they are connected to, as well as an overview of their session ids.
Because multiple... | 5,353,829 |
async def run_server(server: rptminigameshub.network.ClientsListener, updater: rptminigameshub.checkout.StatusUpdater, dry_run: bool = False):
"""Runs event's main loop for serving, SIGINT listening and updating tasks until SIGINT is handled or until status updater crashes,
will throw if it happens.
If dry... | 5,353,830 |
def set_route_queue(path_list,user_position,sudden_id,sudden_xy,pi):
"""
最後の患者が一番近い医師が行くようにする
"""
minimum_dis = 100
minimum_idx = 0
for i in range(len(path_list)):
dis = np.sqrt((user_position[path_list[i][-2]][0] - sudden_xy[0])**2 + (user_position[path_list[i][-2]][1] - sudden_xy[1])**... | 5,353,831 |
def add(x, y):
"""Add two numbers together."""
return x+y | 5,353,832 |
def required_values(
*,
schema: types.Schema,
schemas: types.Schemas,
stay_within_model: bool = False,
) -> typing.Iterator[typing.Any]:
"""
Return iterable with all values of the required key of the constructable schema.
Checks for $ref, if it is there resolves to the underlying schema and... | 5,353,833 |
def calcPerSegmentStatsTiled(imgfile, imgbandnum, segfile,
statsSelection):
"""
Calculate selected per-segment statistics for the given band
of the imgfile, against the given segment raster file.
Calculated statistics are written to the segfile raster
attribute table (RAT), so this f... | 5,353,834 |
def _get_thintar_prefix(tarname):
"""
Make sure thintar temporary name is concurrent and secure.
:param tarname: name of the chosen tarball
:return: prefixed tarname
"""
tfd, tmp_tarname = tempfile.mkstemp(
dir=os.path.dirname(tarname),
prefix=".thin-",
suffix=os.path.sp... | 5,353,835 |
def retry_session(tries=2,
backoff_factor=0.1,
status_forcelist=(500, 502, 504),
session=None):
"""
Parameters
----------
tries : int, number of retires.
backoff_factor : A backoff factor to apply between attempts after the
second try (m... | 5,353,836 |
def vc(t, delta, beta):
"""velocity correlation of locus on rouse polymer. beta = alpha/2."""
return ( np.power(np.abs(t - delta), beta)
+ np.power(np.abs(t + delta), beta)
- 2*np.power(np.abs(t), beta)
)/( 2*np.power(delta, beta) ) | 5,353,837 |
def algorithm(name):
"""
A function decorator that is used to add an algorithm's Python class to the
algorithm_table.
Args:
A human readable label for the algorithm that is used to identify it in
the GUI
"""
def decorator(class_):
algorithm_table[name] = class_
r... | 5,353,838 |
def comp_easy():
"""Get easy components."""
return Components(ewlaps, gi_setting.DEFAULT_EASY) | 5,353,839 |
def play(player1, player2, rounds=1, verbose=False, symdict=None):
"""Play a number of `rounds` matches between the two players and return
the score $S = sum_j a_j$, where
a_j = 1 if player1 wone --or-- -1 if player2 wone --or-- 0 otherwise.
"""
if player1 is player2:
raise AttributeEr... | 5,353,840 |
def test_replace_neighbor(test_image):
"""
Tests replace_neighbor function in transform_data
by asserting the output shape
"""
img = test_image
new_img = td.replace_neighbor(img, (0, 500, img.shape[1], 600))
assert img.shape == new_img.shape
img = test_image
new_img = td.replace_con... | 5,353,841 |
def calc_deltabin_3bpavg(seq, files, bin_freqs, seqtype = "fastq"):
"""
At each position (starting at i), count number of sequences where
region (i):(i+3) is mutated. This is sort of a rolling average and not critical
to the result. It just ends up a bit cleaner than if we looked at a single
base pa... | 5,353,842 |
def make_right_handed(l_csl_p1, l_p_po):
"""
The function makes l_csl_p1 right handed.
Parameters
----------------
l_csl_p1: numpy.array
The CSL basis vectors in the primitive reference frame of crystal 1.
l_p_po: numpy.array
The primitive basis vectors of the underlying lattic... | 5,353,843 |
def process_task(f, module_name, class_name, ftype, f_parameters, f_returns,
task_kwargs, num_nodes, replicated, distributed,
on_failure, time_out):
"""
Function that submits a task to the runtime.
:param f: Function or method
:param module_name: Name of the module con... | 5,353,844 |
def write_point_cloud(name, verts):
"""Write a .obj file for a point cloud.
Parameters
----------
name : str
Ouput file name.
verts : array
Spatial coordinates for vertices as returned by skimage.measure.marching_cubes_lewiner().
"""
with open(name, "w") as thefile:
... | 5,353,845 |
def upgrade(migrate_engine):
"""Add UUID primary key column to encryption."""
meta = MetaData()
meta.bind = migrate_engine
encryptions = Table('encryption', meta, autoload=True)
# NOTE: SQLite doesn't support 'drop constraint' statament
if migrate_engine.name == 'sqlite':
_upgrade_sqli... | 5,353,846 |
def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | 5,353,847 |
def delete_schedule():
"""
При GET запросе возвращает страницу для удаления расписания.
При POST запросе, удаляет выбранное расписани
(Запрос на удаление идэт с главной страницы(func index), шаблона(template) функция не имеет).
"""
if not check_admin_status():
flash(f'У вас нет прав для ... | 5,353,848 |
def dict_from_JSON(JSON_file: str) -> dict:
"""
Takes a WDL-mapped json file and creates a dict containing the bindings.
:param JSON_file: A required JSON file containing WDL variable bindings.
"""
json_dict = {}
# TODO: Add context support for variables within multiple wdl files
with ope... | 5,353,849 |
def show(id):
"""Renderiza a página de um político específico."""
p = Politico.query.get_or_404(id)
# Aplica os filtros de mes, ano e a paginação
mes, ano, tipo, page = (request.args.get("mes"),
request.args.get("ano", 2020, type=int),
request.args... | 5,353,850 |
def map_datapoint(data_point: DATAPOINT_TYPE) -> SFX_OUTPUT_TYPE:
"""
Create dict value to send to SFX.
:param data_point: Dict with values to send
:type data_point: dict
:return: SignalFx data
:rtype: dict
"""
return {
"metric": data_point["metric"],
"value": data_point[... | 5,353,851 |
def write_obs(mdict, obslist, flag=0):
"""
"""
# Print epoch
epoch = mdict['epoch']
res = epoch.strftime("> %Y %m %d %H %M %S.") + '{0:06d}0'.format(int(epoch.microsecond))
# Epoch flag
res += " {0:2d}".format(flag)
# Num sats
res += " {0:2d}".format(len(mdict)-1)
res += '\n'
... | 5,353,852 |
def open_view(
path: str,
*,
filesystem: Optional[Union[fsspec.AbstractFileSystem, str]] = None,
synchronizer: Optional[sync.Sync] = None,
) -> view.View:
"""Open an existing view.
Args:
path: View storage directory.
filesystem: The file system used to access the view.
s... | 5,353,853 |
def smi2xyz(smi, forcefield="mmff94", steps=50):
"""
Example:
utils.smi2xyz("CNC(C(C)(C)F)C(C)(F)F")
returns:
C 1.17813 0.06150 -0.07575
N 0.63662 0.20405 1.27030
C -0.86241 0.13667 1.33270
C -1.46928 -1.21234 ... | 5,353,854 |
def pgm_to_pointcloud(
depth_image: np.ndarray, color_image: Optional[np.ndarray],
intrinsics: Tuple[float, float, float, float],
distortion: List[float]) -> Tuple[np.ndarray, Optional[np.ndarray]]:
"""Fast conversion of opencv images to pointcloud.
Takes ~7 ms per 1280x720 RGBD on my corp laptop (hira... | 5,353,855 |
def plot_runs_with_avg(run_data, only=None):
"""Plot results of simulations sharing a configuration,
with their average results"""
# individual runs
labels_paths = list(enumerate(run_data['runs']))
# output to the run directory + /plots
output_path = os.path.join(run_data['path'], 'plots')
... | 5,353,856 |
def fromfile(file, shape=None):
"""Not supported for ObjectArray"""
raise TypeError("ObjectArray can't be read from a file.") | 5,353,857 |
def matching_poss(poss_1, poss_2):
"""Count how many rows the possibilities have in common.
Arguments:
poss_1 {np.array} -- possibilities 1
poss_2 {np.array} -- possibilities 2
Returns:
int -- the count/matches
"""
matches = 0
for row_2 in poss_2:
for row_1 in p... | 5,353,858 |
def p_statscmdcont_nocomma(p):
"""statscmdcont : STATS_FN
| COMMON_FN
| EVAL"""
p[1] = canonicalize(p[1])
p[0] = ParseTreeNode('_STATSCMDCONT')
fn_node = ParseTreeNode('FUNCTION', raw=p[1])
p[0].add_child(fn_node) | 5,353,859 |
def unk_emb_stats(sentences, emb):
"""Compute some statistics about unknown tokens in sentences
such as "how many sentences contain an unknown token?".
emb can be gensim KeyedVectors or any other object implementing
__contains__
"""
from collections import Counter
stats = {
"sents":... | 5,353,860 |
def basename(path: str) -> str:
"""Returns the basename removing path and extension."""
return os.path.splitext(os.path.basename(path))[0] | 5,353,861 |
async def search_dcu(
ldap_conn: LDAPConnection, dcu_id: str = None, uid: str = None, fullname: str = None
) -> List[DCUUser]:
"""
Seach DCU AD for user
Args:
ldap_conn: LDAP connection to use for searching
uid: Usersname to search for
dcu_id: dcu student id number
fulln... | 5,353,862 |
def jump(inst_ptr, program, direction):
"""Jump the instruction pointer in the program until matching bracket"""
count = direction
while count != 0:
inst_ptr += direction
char = program[inst_ptr]
if char == '[':
count += 1
elif char == ']':
count -= 1
... | 5,353,863 |
def htmlResponse(environ, start_response=None, checkuser=False):
"""
htmlResponse - return a Html Page
"""
if checkuser and not check_user_permissions(environ):
environ["url"] = justpath(environ["SCRIPT_FILENAME"])+"/back.html"
return htmlResponse(environ, start_response)
url = env... | 5,353,864 |
def center_image(IM, method='com', odd_size=True, square=False, axes=(0, 1),
crop='maintain_size', verbose=False, center=_deprecated,
**kwargs):
"""
Center image with the custom value or by several methods provided in
:func:`find_origin()` function.
Parameters
----... | 5,353,865 |
def check_header(install_path):
"""Method to check the final genomics headers have a header or not
check_header
============
This method is going to go through each of the files that were created by the recipe,
and it will check if the those files have a header or not.
sam/bam/cram, vcf... | 5,353,866 |
def poc_plot(*args, **kwds):
# based on Ignacio Serrano-Pedraza Excel spreadsheet
# "sdt_serranopedraza (version 1).xls"
"""
Probability of Occurence Curves (POC)
args:
1 argument:
sdt_metrics.SDT object
2 arguments:
pHI
... | 5,353,867 |
async def test__json_request(aresponses):
"""Test JSON response is handled correctly."""
aresponses.add(
"example.com",
"/api/test",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"},
text='{"status": "ok"}',
... | 5,353,868 |
def get_mapping(mapping_name):
"""
Reads in the given mapping and returns a dictionary of letters to keys. If the given mapping is a dictionary,
does nothing an returns the mapping
mpaping_name can be a path to different file formats
"""
# read in mapping
if type(mapping_name) =... | 5,353,869 |
def evaluate(model, reward_gen, n_steps=1000000, delta=1):
"""Evaulate the regrets and rewards of a given model based on a given reward
generator
Args:
model (TYPE): Description
n_steps (int, optional): Description
delta (int, optional): Number of steps for feedback delay
re... | 5,353,870 |
def get_photo_from_response(response: dict):
"""
parse json response and return an Photo
Keyword arguments:
response -- meetup api response in a dict
return -> get or create Photo
"""
photo, create = Photo.objects.get_or_create(meetup_id=response["id"])
# add optional fields
if "... | 5,353,871 |
def composition_plot(adata: AnnData, by: str, condition: str, stacked: bool = True, normalize: bool = True,
condition_sort_by: str = None, cmap: Union[str, List[str], Tuple[str]] = None,
**kwds) -> hv.core.element.Element:
"""
Generate a composition plot, which shows t... | 5,353,872 |
def node_clone_for_pipeline(graph, orig_op, micro_batch_idx, device):
"""Clone a operation to 'device' from 'orig_op' for pipeline."""
micro_batch_prefix = common.get_micro_batch_prefix(micro_batch_idx)
# get node def
node_def = copy.deepcopy(orig_op.node_def)
node_def.name = micro_batch_prefix + node_def.nam... | 5,353,873 |
def threadbased():
"""threadbased-session
This is threadbased-session test
"""
port = get_free_port()
print('free port', port)
run_as_function(target()) | 5,353,874 |
def test_read_cwd_file(config_file, config, tmpdir):
"""
:GIVEN: Nothing.
:WHEN: Loading the config file from the cwd.
:THEN: Verify the correct file is loaded.
"""
with tmpdir.as_cwd():
assert sut.Config._read_cwd_file() == config | 5,353,875 |
def region_of_province(province_in: str) -> str:
"""
Return the corresponding key in ITALY_MAP whose value contains province_in
:param province_in: str
:return: str
"""
region = None
for r in ITALY_MAP:
for p in ITALY_MAP[r]:
if province_in == p:
region = ... | 5,353,876 |
def filter_stopwords(words:list)->iter:
"""
Filter the stop words
"""
words = filter(is_not_stopword, words)
return words | 5,353,877 |
def numpy_jaccard(box_a, box_b):
"""计算两组矩形两两之间的iou
Args:
box_a: (tensor) bounding boxes, Shape: [A, 4].
box_b: (tensor) bounding boxes, Shape: [B, 4].
Return:
ious: (tensor) Shape: [A, B]
"""
A = box_a.shape[0]
B = box_b.shape[0]
box_a_x1y1 = np.reshape(box_a[:, 2:], ... | 5,353,878 |
def test_get_rule(client_rule_factory, client_response_factory, registered_rule):
"""Check request data that client uses to get a rule.
1. Create a subclass of the abstract client.
2. Implement send request so that it checks the request parameters.
3. Invoke the get_rule method.
4. Check the rule, ... | 5,353,879 |
def summaryhsl(all_summaries, summary):
"""
Choose a color for the given system summary to distinguish it from other types of systems.
Returns hue, saturation, and luminance for the start of the range, and how much the hue can be randomly varied while staying distinguishable.
"""
lowest_att = min(a... | 5,353,880 |
def _get_cached_values(instance, translated_model, language_code, use_fallback=False):
"""
Fetch an cached field.
"""
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return None
key = get_translation_cache_key(translated_model, instance.pk, language_co... | 5,353,881 |
def configure(tm_env, app, container_dir):
"""Configures all plugins.
"""
for hook in plugin_manager.load_all(_PLUGINS_NS):
_LOGGER.info('Configuring plugin %r.', hook)
hook(tm_env).configure(app, container_dir) | 5,353,882 |
def tensor_index_by_list(data, list_index):
"""Tensor getitem by list of int and bool"""
data_shape = F.shape(data)
indexes_types = hyper_map(F.typeof, list_index)
if const_utils.judge_indexes_types(indexes_types, mstype.int_type + (mstype.bool_,)):
sub_tuple_index = const_utils.transform_sequen... | 5,353,883 |
def sample_ingridient(user, name='Salt'):
"""Create and return a sample ingridient"""
return Ingridient.objects.create(user=user, name=name) | 5,353,884 |
def remove_duplicates_from_list(params_list):
"""
Common function to remove duplicates from a list
Author: [email protected]
:param params_list:
:return:
"""
if params_list:
return list(dict.fromkeys(params_list))
return list() | 5,353,885 |
def _exec_task(fn, task, d, quieterr):
"""Execute a BB 'task'
Execution of a task involves a bit more setup than executing a function,
running it with its own local metadata, and with some useful variables set.
"""
if not d.getVarFlag(task, 'task', False):
event.fire(TaskInvalid(task, d), d... | 5,353,886 |
def mediaRecognitionApi():
"""
Retrieve the resource id, name, author
and time index of a sampled media.
"""
#TODO: Improve recognition
if 'file' not in request.files:
abort(400, "No file.")
file = request.files['file']
if file.filename == '':
abort(400, "No selected file")
if file and allowed_file(file.fi... | 5,353,887 |
def _scale_and_shift(
x: chex.Array,
params: Sequence[chex.Array],
has_scale: bool,
has_shift: bool,
) -> chex.Array:
"""Example of a scale and shift function."""
if has_scale and has_shift:
scale, shift = params
return x * scale + shift
elif has_scale:
assert len(params) == 1
retu... | 5,353,888 |
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects
:param aLocation1: starting location
:param aLocation2: ending location
:return:
"""
dlat = aLocation2.lat - aLocation1.lat
dlong = aLocation2.lon - a... | 5,353,889 |
def merge_components(a,c,corr_img_all_r,U,V,normalize_factor,num_list,patch_size,merge_corr_thr=0.6,merge_overlap_thr=0.6,plot_en=False):
""" want to merge components whose correlation images are highly overlapped,
and update a and c after merge with region constrain
Parameters:
-----------
a: np.nd... | 5,353,890 |
def RenderSubpassStartInputAttachmentsVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartInputAttachmentsVector(builder, numElems) | 5,353,891 |
def GetCLInfo(cl_info_str):
"""Gets CL's repo_name and revision."""
return cl_info_str.split('/') | 5,353,892 |
def acyclic_run(pipeline):
"""
@summary: 逆转反向边
@return:
"""
deformed_flows = {'{}.{}'.format(flow[PWE.source], flow[PWE.target]): flow_id
for flow_id, flow in pipeline[PWE.flows].items()}
reversed_flows = {}
while True:
no_circle = validate_graph_without_circle(... | 5,353,893 |
def TextAreaFieldWidget(field, request): # pylint: disable=invalid-name
"""IFieldWidget factory for TextWidget."""
return FieldWidget(field, TextAreaWidget(request)) | 5,353,894 |
def _cgroup_limit(cpu, memory_size, pid):
"""Modify 'cgroup' files to set resource limits.
Each pod(worker) will have cgroup folders on the host cgroup filesystem,
like '/sys/fs/cgroup/<resource_type>/kubepods/<qos_class>/pod<pod_id>/',
to limit memory and cpu resources that can be used in pod.
Fo... | 5,353,895 |
def s_wexler(T_K):
"""
Calculates slope of saturation vapor pressure curve over water at each temperature
based on Wexler 1976, with coefficients from Hardy 1998 (ITS-90).
Args:
T_K (np.ndarray (dimension<=2), float, list of floats) : Air or Dewpoint Temperatures [K]
Returns:
s : n... | 5,353,896 |
def get_additional_bases():
"""
Looks for additional view bases in settings.REST_EASY_VIEW_BASES.
:return:
"""
resolved_bases = []
from importlib import import_module
for base in getattr(settings, 'REST_EASY_VIEW_BASES', []):
mod, cls = base.rsplit('.', 1)
resolved_bases.appe... | 5,353,897 |
def load_mask_from_shp(shp_file: Path, metad: dict) -> np.ndarray:
"""
Load a mask containing geometries from a shapefile,
using a reference dataset
Parameters
----------
shp_file : str
shapefile containing a polygon
metad : dict
rasterio-style metadata dictionary
Retu... | 5,353,898 |
def est_corner_plot(estimation, settings=None, show=True, save=None):
"""Wrapper to corner plot of `corner <https://corner.readthedocs.io/en/latest/>`_ module;
visualisation of the parameter posterior distribution by all 2-dimensional and
1-dimensional marginals.
Parameters
----------
estimatio... | 5,353,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.