content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def calculate_bbox_iou(bbox_a: BBox, bbox_b: BBox) -> float:
"""Calculates the IoU between 2 bboxes.
Args:
bbox_a (BBox): BBox.
bbox_b (BBox): BBox.
Returns:
float: IoU between the two bboxes.
"""
intersect_area = bbox_a.intersection_area_with(bbox_b)
union_area = bbox... | c4519ba8219e6b8a98fc35c7fa4130ff07637e9d | 3,601,800 |
def get_settings():
"""Return module settings global settings.
This method is cached through python's lru_cache decorator, so
only the first request creates an object, and all other requests
to this method returns the same object created the first time.
"""
return Settings() | 869686ffa1b1dd17e63b276324869c734e398c41 | 3,601,801 |
from typing import List
from typing import Dict
def collate_batched_meshes(batch: List[Dict]): # pragma: no cover
"""
Take a list of objects in the form of dictionaries and merge them
into a single dictionary. This function can be used with a Dataset
object to create a torch.utils.data.Dataloader whi... | ba6b37091c81e514282220aafcf8c60b52021273 | 3,601,802 |
def resnet18(num_classes):
"""A slightly modified ResNet-18 model"""
def resnet_block(num_channels, num_residuals, first_block=False):
blk = nn.Sequential()
for i in range(num_residuals):
if i == 0 and not first_block:
blk.add(d2l.Residual(
num_cha... | 52ab1ff4feddb329aea4b3b6f74db705f2bb8e71 | 3,601,803 |
def person_lookup(request, details):
"""
Lists the demographic for a specific student
"""
data = {'status': 'error', 'message': 'No information for '+str(details)}
profiles = {}
for db in uqx_api.courses.EDX_DATABASES:
if db == 'default' or db == 'personcourse' or db == 'Course_Event':
... | c1a9611db5e2ae408757c591698643167c22f1c3 | 3,601,804 |
def md5shuffle(arr: ndarray, salt: str = None) -> ndarray:
"""
md5shuffle
Will shuffle the input array pseudo-randomly in a deterministic manner using MD5 hashing.
Parameters
----------
arr: list, ndarray
The array of values that you want shuffled
salt: str
A sting to appen... | 76bbce003290e1040ca4f5dadda4efa6b0732de2 | 3,601,805 |
def design_matrix(bvals, bvecs):
"""Return the diffusion kurtosis imaging design matrix.
Parameters
----------
bvals : numpy.ndarray
Floating-point array with shape (number of acquisitions,).
bvecs : numpy.ndarray
Floating-point array with shape (number of acquisitions, 3).
Ret... | 62a6e916d8df3d7e07ab30b5e39c20a9e5b21ca1 | 3,601,806 |
def residual_predicted_chart(predicted, residuals, title="Residual vs Predicted Values"):
"""Residual vs predicted values curve."""
source = pd.DataFrame({"x": predicted, "y": residuals})
return scatter_chart(source, "Prediction", "Residual", title=title) | a8c6b83eaa5896f8caf2a2af74cbc44f8a0004be | 3,601,807 |
def ecs_efs_encryption_status(status):
"""
Property: EFSVolumeConfiguration.TransitEncryption
"""
valid_status = ["ENABLED", "DISABLED"]
if status not in valid_status:
raise ValueError(
'ECS EFS Encryption in transit can only be one of: "%s"'
% (", ".join(valid_statu... | 85e0d0f8b3c33331c8d877f0554126ca72c023bc | 3,601,808 |
import yaml
def GetSchedulingNodeAffinityListFromArgs(args,
messages,
support_node_project=False):
"""Returns a list of ScheduleNodeAffinity messages populated from args."""
operator_enum = messages.SchedulingNodeAffinity.Operator... | c3f5c4a2b17ea1302baa58ea34fe671d89ac1998 | 3,601,809 |
def load_model(model_file, check_size=True):
"""
Loads a svm model from a file and computes its size
:param model_file: The file name of the model to load
:return: A dictionary with keys model, file, and size
"""
model = svm_load_model(model_file)
model_dict = {'model': model}
if check_s... | 73741e43603c270d73463ab2db28d5d9290a49a6 | 3,601,810 |
def robust_zscore(x: pd.Series, zscore=False):
"""Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
"""
x = x - x.median()
mad = x... | 060d80ce5159b73dc2d68d265d2ae6eb965fa166 | 3,601,811 |
import warnings
def GlobalHandleGetBytes(handle, offset, count):
""" Backward compatible alias for :func:`global_handle_get_bytes` """
warnings.warn("GlobalHandleGetBytes is deprecated, use global_handle_get_bytes instead", DeprecationWarning)
return global_handle_get_bytes(handle, offset, count) | 75001aaa968b4789961d1fc8370f54d468907faa | 3,601,812 |
def folder_contents_html(folder_path, files, folders):
"""Given files and folders generate html."""
html = "<!DOCTYPE html><html><body>{}</body></html>"
atag = '<a href="{}">{}</a>'
files_and_folders = ''
for folder in folders:
files_and_folders += '<h4>' + atag.format(folder_path + '/' + fo... | 6b6b37ca9452319d309a61c877ebf6d1fba201aa | 3,601,813 |
def onehot_features(train, test, features, full=False, sparse=False, dummy_na=True):
"""Encode categorical features using a one-hot scheme.
Parameters
----------
train : pd.DataFrame
test : pd.DataFrame
features : list
Column names in the DataFrame to be encoded.
full : bool, defaul... | d42e6bd843cfc3ae990b0c8309c95b7b34f52f4d | 3,601,814 |
import os
def get_logdir_name(flags):
"""Generates the name of the log directory from the values of flags
Parameters
----------
flags: neural net architecture generated by get_arguments()
Outputs
-------
the name of the directory to store the training and evaluation results
"""... | 2caa6a8005bfb76b52847be3acc64ba93a0d72e0 | 3,601,815 |
def is_valid_chars(value: str, chars: str = _input_character_set) -> bool:
"""
**is_valid_chars**
checks if all characters are valid
:param value: value to check
:param chars: valid characters
:return: bool indicating if characters are valid or not
"""
return not bool([inval... | 3b4fba6c79cd23430e78a9eb1a9f924cc353a572 | 3,601,816 |
def concentration_monthly_trend(hemisphere=None, year=None, month=None,
search_paths=nt.DEFAULT_SEA_ICE_PATHS,
min_days_for_valid_month=nt.MINIMUM_DAYS_FOR_VALID_MONTH,
trend_start_year=None, *, clipping_threshold):
"""R... | ab4b28b2dd22f568c87e71214ddd71e52200485f | 3,601,817 |
def prediction(outDir, model_weight):
"""
predict single sample breast cancer risk
:param outDir: output directory
:param model_weight: the MiScan model weight file path
:return: (risk_to_be_patient, probability_to_be_normal)
"""
logger.info('start model evaluation')
model = build_mode... | 2b65884a5ac88ecd45276a5488269807494d1d29 | 3,601,818 |
def find_package(sought_package):
"""Is this name mentioned anywhere? Then return it as a suggestion?
"""
# First check top-level keys
if sought_package in PACKAGE_MAP.keys():
return PACKAGE_MAP[sought_package]
for package in PACKAGE_MAP.keys():
for install_type in PACKAGE_MAP[package].keys():
if sought_pac... | e07962da8a48559abfbd3211c795a4d83a3ba3cb | 3,601,819 |
def launch():
""" Initialize the module. """
return UEMeasurementsWorker(UEMeasurements,
EP_ACT_UE_MEASURE,
UE_MEAS_RESPONSE) | a017fd4468c034efcce1880c82a76845df414af8 | 3,601,820 |
def search_date():
"""Function to search entries by date"""
date_printer()
user_parsed = date_checker()
date_query = Task.select().where(Task.date == user_parsed)
final_values = query_to_dict(date_query)
return final_values | 18d2a5b46da2267fdc199917526d3312e0028fac | 3,601,821 |
import functools
import inspect
import warnings
def deprecatedmethod(func):
"""
This is a decorator which can be used to mark class member
functions as deprecated.
"""
@functools.wraps(func)
def new_func(self, *args, **kwargs):
call_loc = inspect.stack()[-1]
warnings.warn_expli... | cdab9d45301c3ca9cee6b059b3ae44cbcc5a9a1f | 3,601,822 |
def set_defaults(module_path):
"""
Creates a module metadata using default values
"""
metadata = module_metadata.create_default_metadata(module_path)
return metadata | f8d215a8c0ef9d15d1d28f157f8770fb00224912 | 3,601,823 |
from typing import Union
def parallel_range(arg: Union[int, slice]) -> ParallelFor:
"""
Builds a parallel iterator.
"""
return _pygauss.parallel_range(arg) | bc569c08f2fe024d0e853673083685dc13ac921d | 3,601,824 |
import requests
from datetime import datetime
import os
def download_from_site(url: str, dest: str = None) -> dict:
"""
downloads files and resources from websites
returns a ditionary of information relating to the resource downloaded
"""
res = {}
if not _confirm_webpage(url):
raise V... | 1d25dd168956182ce981f5d8774c72fca75dd2ba | 3,601,825 |
def cvtStokesToDoP(img_stokes):
"""
Convert stokes vector image to DoP (Degree of Polarization) image
Parameters
----------
img_stokes : np.ndarray, (height, width, 3)
Stokes vector image
Returns
-------
img_DoP : np.ndarray, (height, width)
DoP image ∈ [0, 1]
"""
... | d5ceaf3dd1e801bef0b498a057876c0c19a0bddb | 3,601,826 |
import torch
import copy
def ResNet101_conv5_body(pretrained=True, model_path = None):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model_path = cfg.RESNETS.IMAGENET_PRETRAINED_WEIGHTS if model_path is None else model_path
mo... | a0d20abdb4692f02998db4fe4cf267d75b5647d0 | 3,601,827 |
def getConfig( config_file_path = "/etc/monitor.conf" ):
"""
Reads the process configuration from the config file.
Config file contains the processes to be monitored.
"""
process_dict = {}
parser = SafeConfigParser()
parser.read( config_file_path )
for section in parser.sections():
... | a258d61ddf8a859d7cda99a8e7d59715ced307af | 3,601,828 |
def calculateGainFactor(numerator:list, denominator:list, passband_freq:float) -> float:
"""Calculate and return the coefficent needed to normalise the passband gain of an IIR filter to unity"""
# Initalise variables
num_coeff = len(numerator) # Calculate number of tap coefficents
numerator_sum = 0 # T... | 035748dfd3bcd0aefe1aa56472f1559133eeb656 | 3,601,829 |
def setUnitValue(plug, value):
"""
Updates the unit value for the supplied unit plug.
:type plug: om.MPlug
:type value: Union[om.MDistance, om.MAngle]
:rtype: None
"""
return __setunitvalue__[getUnitType(plug.attribute())](plug, value) | e391037bd4041eb7d294ae380786aa09277e2ac8 | 3,601,830 |
from typing import List
from typing import Union
def select(evaluated_population: List[Eval], random_seed: Union[int, float] = 0.12345, num_elites: int = 5,
method: SelectionMethod = SelectionMethod.TOURNAMENT, tournament_size: int = 5,
temperature: float = 1.0) -> List[Parents]:
"""Uses the... | d29f8834cb268765bc8cef7dd9c48e896525c45b | 3,601,831 |
import re
import dateutil
import pytz
def convert_date_range_option(date_range):
"""Convert a DateRange option to datetime objects
Parameters
----------
date_range: str
The value of a DateRange option.
Returns
-------
start: datetime.datetime
The date range's start value
... | dc9be7add77ab94af0a1e361ce5dd21ae387cc6d | 3,601,832 |
def dummy(xy_in, params, invert=False):
"""
"""
return xy_in | 74e6986c37bd1367dbc152e77b5cef2097bf8e14 | 3,601,833 |
import random
def pick_sites(grid):
"""
Randomly pick two adjacent sites on a grid.
@type grid: Grid object
@param grid: grid
"""
# Pick the first site
site1 = (random.randrange(grid.height), random.randrange(grid.width))
# Pick an adjacent site
site2 = random.choice(grid.cells[si... | 18ed6a17aae292a23cec4a66dab98b290c0c5992 | 3,601,834 |
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False, concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = ... | 37ff58f9c85904f937fdc9cd122d6a51d84eb009 | 3,601,835 |
from typing import Dict
from typing import Set
from typing import Any
def unique(domains: Dict[str, Set[Any]]) -> bool:
""" Each variable has exactly one value """
return all((len(domain) == 1
for domain in domains.values())) | 64551d938135b1a288ca97d480abe4282eddeefd | 3,601,836 |
def expand_flattened_path(flattened_path, value=None, separator='.'):
"""
Expands a dotted path into a nested dict; if value is set, the
final key in the path will be set to value.
:param str flattened_path: flattened path to expand
:param str separator: character(s) separating path components
... | 41c8cf40495e9922df3d31b641235fad2a823b4d | 3,601,837 |
def update_interview_questions_endpoint():
"""
Updates an interview question
Request body:
- `id`: Question ID
- `new_question`: New question for that interview
"""
content = request.json
headers = request.headers
if not validate_authentication(headers):
return jsonify({"status": auth_error})
... | 3d0fbd5de6c9c38445b04ab3f73e055f280b3504 | 3,601,838 |
def get_iou_scores(boxes, gt, mask):
"""
Compute and return IoU scores between two tensor of bounding boxes, and mask them with `mask`.
:param boxes: A [..., d, 4] tensor
:param gt: A [..., d, 4] tensor
:param mask: A [..., d, 1] tensor
:return: A [..., d, 1] tensor with IoU scores where mask i... | 4b50cd51dbeadc89d39326a10d19031b5ab22e5b | 3,601,839 |
def toMaiden(lat: float, lon: float = None, *, precision: int = 3) -> str:
"""
Returns a maidenhead string for latitude, longitude at specified level.
Parameters
----------
lat : float or tuple of float
latitude or tuple of latitude, longitude
lon : float, optional
longitude (i... | 6dba5f6cc0826a5def861105a672eca0d6108192 | 3,601,840 |
import html
def create_download_button(key):
"""
Creates a button that submits a POST request to the /download/ route.
Args:
key (str): S3 key
Returns:
html.Form
"""
return html.Form(
[
dbc.Input(type='hidden', name='key', value=serialize(key)),
... | 8f8cb8865c6bca468c1587e7c24dcd7d75055ba9 | 3,601,841 |
def _map_listparameter(value, separator=',', dtype=None):
"""
Map a string list into a python list
:param value: str or list, if list returns if string tries to evaluate
:param separator: str, where to split the str at to make a list
:param dtype: type, if set forces elements of list to this data t... | f3fbb7ae8415976842d980ab456f8de071068294 | 3,601,842 |
def handle_hashes(f):
"""
Normalize torrent hash arguments.
Initial implementations of this client used 'hash' and 'hashes'
as function arguments for torrent hashes. Since 'hash' collides
with an internal python name, all arguments were updated to
'torrent_hash' or 'torrent_hashes'. Since both ... | 7f59cc73f47bef073f5f24d2f209f061bf1fc031 | 3,601,843 |
def create_app(injector: Injector) -> Flask:
"""
Creates a Flask app
:param injector: The injector
:return: Returns the Flask app
"""
app_flask = Flask(__name__)
injector.binder.bind(Application, to=app_flask)
app_flask.config.from_object(Config)
registers = injector.get(Application... | f40759cad801963cb3f08d94208576a56d385bed | 3,601,844 |
from typing import Optional
def parse_dot_notation(input: str) -> tuple[str, Optional[tuple[str, ...]]]:
""" Parse dot-notation
Example:
parse_dot_notation('a') #-> 'a', None
parse_dot_notation('a.b.c') #-> 'a', ['b', 'c']
"""
name, _, sub_path_str = input.partition('.')
sub_path ... | 06650868fb773b41b97a839b0d423cc8f3cd4a85 | 3,601,845 |
def zero_pad(number, padding=_DEFAULT_PADDING):
"""Converts an int into a zero padded string.
Args:
number(int): The number to convert.
padding(int): The number of chars in the output. Note that if you pass for
example number=23456 and padding=4, the output will still be '23456',
i.e. it will n... | 7045756f51c2dd66c690ea4b92081e52b6c9373b | 3,601,846 |
def header_categories(_request=None):
"""
Required for header category navigation.
"""
categories = Category.objects.all()
return {"nav_categories": list(categories)} | 9276260af126e664b174d89b8cb74fcb7d823447 | 3,601,847 |
import json
def get_all_cards():
"""
Return all cards
"""
cards = [item for item in card_collection.values()]
response = json.loads(models.CardResponse(cards=cards).json())
return JSONResponse(content=response) | 2ab4f75b70a0344b67dbce7561cf2a73489fa6d6 | 3,601,848 |
from typing import List
def contest_from(description: ContestDescription) -> PlaintextBallotContest:
"""
Construct a `BallotContest` from a specific `ContestDescription` with all false fields.
This function is useful for filling contests and selections when a voter undervotes a ballot.
:param descrip... | d42388debe7c0cb6f3025bdf1903bc2b18942767 | 3,601,849 |
def ranking_ativo_func(pa_long_ativo):
"""
o ranking_ativo retorna o ranking de price action dos ativos
Parameters
----------
pa_long_ativo : dataframe
dataframe do price action por ativo
Returns
-------
Retorna o ranking de retorno classificado por ativo com as seguintes colun... | 89c87c7452461875fb75e5ba4948259a586e20f2 | 3,601,850 |
def createURIString(valueString, delimiter, vocab):
"""This function takes a delimiter separted string of values and returns a string
in which every of these values is prefixed with the specified vocab URI.
>>> createURIString('nl;fr;de', ';', 'http://id.loc.gov/vocabulary/languages/')
'http://id.loc.gov/vo... | 6fb6898b1531b5741dd890452c9ddd9e4db6f205 | 3,601,851 |
def illustrate_shuffle():
"""
Illustrate how shuffling in time changes the autocorrelation
"""
# Generate some data
np.random.seed(2)
details = sim_exp.behav_details['landau']
t = sim_behav.time_vector(details['fs'],
details['t_start'],
... | 56a4c0771a043381da59d33d53d98875b2333200 | 3,601,852 |
import requests
from bs4 import BeautifulSoup
def get_page(url, **kwargs):
"""Pulls in the HTML from a URL and returns the results as a BeautifulSoupt object.
Parameters
----------
url : str
The URL to scrape
Returns
-------
soup : bs4.BeautifulSoup
The BeautifulSoup rep... | 392c83be8b24bdeb27cf482c9df72c30b4b945dc | 3,601,853 |
def yn_ask(msg):
"""Ask for a [y/n] user response
returns the response
"""
resp=ask(msg)
while not (resp=='y' or resp=='n'):
pmsg="Please respond with a 'y' or 'n':"
resp=ask(pmsg)
if resp=='y':
resp=True
else:
resp=False
return resp | 82a8b7cb70fdbee4b6fdd75d8e781c8714db98fe | 3,601,854 |
def simple_is_valid(position, velocity, acceleration, jerk):
"""
Checks values against constant bounds.
"""
p_end = 10.0
v_max = 10.0
a_max = 10.0
j_max = 10.0
if position < 0.0 or position > p_end + traj.discrete_time_parameterization.POSITION_THRESHOLD:
return False
if velo... | 19ad21a0d7df1bb04373d86633c3a4afe0a3ee82 | 3,601,855 |
def get_counter(given_name):
"""
Assuming the given name adheres to the naming convention of crab this
will extract the counter element of the name.
:param given_name: Name to extract from
:type given_name: str or pm.nt.DependNode
:return: int
"""
parts = given_name.split('_')
for... | 15cba70e0ab2c258af565026b6e04385981d74dc | 3,601,856 |
import os
def make_process(*args, **kwargs):
"""Set up the environment for subprocesses."""
process_cls = process.Process
# Add the current working directory and /data/multiversion to the PATH.
env_vars = kwargs.get("env_vars", {}).copy()
path = get_path_env_var(env_vars)
if config.INSTALL_D... | 0213722c2d451af1ab481e962d22f89629f2c45b | 3,601,857 |
def _get_default_attributes_dict(name, **kwargs):
"""
@param kwargs any initial item values can be passed in this
argument
@return dictionary with default properties of any attribute
of CIM class, instance or instance name
"""
if not isinstance(name, basestring):
raise TypeError("nam... | 9ebe6e782235ac0f988714fb37c9d6418d3d45e9 | 3,601,858 |
def _instantiate_single_record(model, unique_fields, record):
"""Create unsaved model instances, ready to be sent to bulk_create"""
assert isinstance(model, str) or isinstance(model, unicode)
assert isinstance(unique_fields, list)
assert isinstance(record, dict)
app, model_name = model.split('.', 1... | 1b444158799a7a3dc339f1f4adbfff429ef9dc5e | 3,601,859 |
def change_cm(request, cm_id, success_url='mai_main'):
"""
View changing used CM.
"""
request.session['user'].cm_id = int(cm_id)
request.session.modified = True
messages.success(request, _('Cluster Manager changed.'))
return redirect(request.META['HTTP_REFERER'] or success_url) | 807d041a131d33e7cf36df655e842baa76f11157 | 3,601,860 |
import six
from datetime import datetime
def obj_to_dict(obj, *filter_fields, **kwargs):
"""
filter_fields: 指定输出字段(默认输出所有)
示例: obj_to_dict(obj, 'field1', 'field2', filter_fields=['field3', 'field4'])
exclude_fields: 指定不要输出字段
limit_deep: 限制递归深度, 默认5层. 设为0则不限制递归深度(不建议设为0!)
p... | 08b732094cc2408bed317400af2163beed774eb0 | 3,601,861 |
def envelope_flattop_cos(t, t_pulse, t_rise, t_start=0,
normalize=True, **not_needed_kwargs):
"""
Envelope for a flattopped pulse with cosine-shaped edges.
Parameters
----------
t : float
Time at which the value of the envelope is to be returned.
t_pulse : float... | ae1cad59edb6d10c6ee194424e7d706c1f475f5a | 3,601,862 |
def parse_float(string:str) -> float:
"""
A function to parse string characters into float
-> string: str => a string of chars, ex : "abc12a.a3"
----
=> float: numbers present inside the string passed in, ex : 12.3
"""
if not isinstance(string, str):
raise TypeError('string must be ... | 305c945979d4eb880d53207a9a1466f46cb7d981 | 3,601,863 |
def check_for_string_unmapped_values(string):
"""
:type string: str
:rtype: str
"""
unmapped_values = ""
for s in string:
if s not in known_values:
unmapped_values += s
return unmapped_values | 61925733563ed96dbb0c23bf7b18d53074a94ac6 | 3,601,864 |
def invert_dict(dct):
"""Inverts a dictionary from A -> B into one from B -> [A]"""
ret = defaultdict(list)
for k, v in dct.items():
ret[v].append(k)
return ret | 9b69709aa7c518b85ededae24877376825838169 | 3,601,865 |
from typing import List
from typing import Dict
def createWordsLines(wordsTable: List, col_lengths: List[int], border: Dict[str, str], centered: bool, extra_spaces: int = 2) -> str:
""" Creates the part of table with the words as a multiline string.
Args:
wordsTable (List): The list of the words of t... | ec903ede975f832ed599ec9278465ab2ba8336fd | 3,601,866 |
from pathlib import Path
import json
def read_jupyter_as_json(filepath: Path) -> Path:
"""
Read in rendered notebook-- read in the JSON representation that is 'under
the hood'
:param filepath: path to jupyter notebook.
"""
with open(filepath, "r") as fout:
contents = fout.read()
... | d91344b1bddcd0e1078effe6dd7947f7e04ea6af | 3,601,867 |
from typing import Dict
def node_to_bel(node: Dict, graph, hgnc_manager: HgncManager, chebi_manager: ChebiManager, species) -> BaseEntity:
"""Convert node dictionary to BEL node object."""
node_types = node['entity_type']
identifier, name, namespace = get_valid_node_parameters(node, hgnc_manager, chebi_m... | 70ea7751b94b14f9e3fe1396ac954421ebfbf0b1 | 3,601,868 |
def styled_text(text, new_styles, old_styles=None, supplement_style=False):
"""Return a styled text tuple that can be used within urwid.Text.
.. note::
If an urwid.Text instance is passed in as the ``text`` parameter,
alignment values will be lost and must be explicitly re-added by the
... | 1283433859d9207bd73c512fc307b68ec781c98c | 3,601,869 |
def cdf_function_1(cd: ChemicalDiagram):
"""inclusion: one of the connected components contains only C N H"""
sets = []
for scd in cd.get_components():
sets.append(set(scd.get_element_list()))
return {"C", "N", "H"} in sets | 00b53571798fe1e086fe8df6f36fc369c2cabced | 3,601,870 |
def _imports(graph: mapry.Graph) -> str:
"""
Generate the import declaration.
:param graph: mapry definition of the object graph
:return: generated code
"""
import_set = set() # type: Set[str]
if graph.classes:
import_set.add("fmt")
if mapry.needs_type(a_type=graph, query=map... | 78b983c7b0e2f30f7b0ca47fa98bed716120c69c | 3,601,871 |
def _to_db_str(sequential_list):
"""Convert a list or tuple object to a string of database format."""
entry_list = []
for _entry in sequential_list:
# I know only text type need to be converted by now. More types could
# be added in the future when we know.
if isinstance(_entry, str)... | 42a4e008964c0accb3e596dc75859641e999a0f4 | 3,601,872 |
def generate_personalized_recommendations(
submission_ids: list,
data: list,
index: str,
nbrs_model: NearestNeighbors = None,
):
"""
Generate personalized recommendations
for a given submission ids, given data, index, and nearest neighbors model
submission_ids: list, list of IDs that we... | 8d9cfada05de4a787e023b35afdac7c87499a2ea | 3,601,873 |
import glob
def get_file_sets(root_path, resnet_version, dlc_network_shuffle= 'shuffle2',dlc_network_iteration = '500000', filtered=False):
""" function intended to fetch the proper network file sets for a given session. A session directory
may have multiple predictions from unique DLC networks saved to a fol... | d7920667545dece6d6c4fccc6075a14c8eb53837 | 3,601,874 |
import time
def retry(ex, tries=4, delay=3, backoff=2, logger=log):
"""Retry calling the decorated function using exponential backoff based on
* http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
* http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ex: the excepti... | 61a743b3f6260bac1ed82afe132ab94579848358 | 3,601,875 |
def max_index(X):
"""Return the index of the maximum in a numpy array.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
The input array.
Returns
-------
i : int
The row index of the maximum.
j : int
The column index of the maximum.
Raises... | 83897767822597088268180dd3fc0671da001c5c | 3,601,876 |
def parse_errors(root_dir, lines):
"""
Parse and add special markers to all error found in the `ERRORS` section.
:param root_dir: This is the test root dir found in the pytest report.
:param lines: All reported output lines from the `ERRORS` section.
:returns: The original input list augmented wit... | f52cd2ab5e01330247930be88bf0bfda5654a9dd | 3,601,877 |
def air_port_add(request):
""" Add new air_port and see the list of air_ports packages """
success_message, error_message = None, None
form = AirPortForm
air_ports = AirPort.objects.all()
if request.method=="POST":
form = AirPortForm(request.POST)
if form.is_valid():
... | d8264c1265c8cb538cb7990117a9249099314ee2 | 3,601,878 |
def pull_address_data(url=None):
"""
Libraries with active extended wi-fi programs have their websites listed.
Access websites and pull street address and zip code. If an street address
intersection is given e.g.,
"16 Brighton First Rd. at Brighton Beach Ave."
remove the int... | d17029b3a04050cfc5cc51215eb0671f59d5e5e9 | 3,601,879 |
import requests
from typing import Match
def get_match(match_id):
"""Returns Score dicts list of the recent scores of the user"""
payload = {KEY_API_KEY: constants.OSU_API_KEY, KEY_MATCH: get_from_string(match_id)}
request = requests.get(URL_GET_MATCH, params=payload)
if request.status_code != 200:
... | 5ccfc596ff87c68283bd1cd77036a052d6e2d07f | 3,601,880 |
from typing import Tuple
import logging
async def test_send_custom_json(node: str) -> Tuple[str, float]:
"""Builds but doesn't send a custom_json not async."""
try:
hive = beem.Hive(node=node, nobroadcast=True, wif=Config.posting_keys)
data = {"something": "here"}
start = timer()
... | 12e27f679fd5cc4d62346f6f703eab44872c8b3e | 3,601,881 |
def transform_rows_nonlinear_and_categorical02(data, **kwargs):
"""
Nonlinear and categorical row transformation 02. 7 numerical data sources (x^4, log, exp2, log1p, x^5, log10, log2) and 3 categorical (8, 4 and 2 categories).
"""
sources_transformers = [
lambda x: np.power(x, 4),
lambd... | 8a277a860b017766d8aa154527fc27a44ec52da5 | 3,601,882 |
def histogram(s):
"""to check s in string"""
d={}
for c in s:
d[c]=1+d.get(c,0)
return d | 4b643a05f97ae0829235b1296e37ee73ad8807f4 | 3,601,883 |
def format_rot_dist_consts(rot_dists):
""" Format the rotational distortion constants.
"""
# Build rotational dists string
rot_dists_string = ''
for i, const in enumerate(rot_dists):
rot_dists_string += ' '.join(map(str, const))
if (i+1) != len(rot_dists):
rot_dists_str... | dbcb285f6886f6065ddd02497d12a230e1d74dff | 3,601,884 |
def read_get_schema(data):
"""Reads and parses a GSC ('Get Schema') request."""
return {"user": read(data, "S", 0), "group": read(data, "S", 2),
"schema": read(data, "S", 4),
"session_id": read(data, "S", 6)} | a84706b9e9fd8341c44cda718705b40839581b97 | 3,601,885 |
def svn_txdelta_send_string(*args):
"""svn_txdelta_send_string(svn_string_t const * string, svn_txdelta_window_handler_t handler, void * handler_baton, apr_pool_t pool) -> svn_error_t"""
return _delta.svn_txdelta_send_string(*args) | 630f0a58a289ff2a252f84089f94f8c2f2ab3359 | 3,601,886 |
import os
def compute_additional_layer(args):
"""Compute the additional layer the sea level rise index.
Inputs:
-args['additional_layer_uri']: uri to the additional layer data.
-args['aoi_uri']: uri to datasource of the area of interest
-args['shore_raster_uri']: uri t... | 3db8dca57ba2a9b0261fdf4da6650a9f01512cc9 | 3,601,887 |
def _to_spdx(lic):
"""
we are munging this stuff from conda-build
d_license = {'agpl3': ['AGPL-3', 'AGPL (>= 3)', 'AGPL',
'GNU Affero General Public License'],
'artistic2': ['Artistic-2.0', 'Artistic License 2.0'],
'gpl2': ['GPL-2', 'GPL (>= 2)',... | 66aaa5fa8428ec680ab347b9a33ed7f03f18281c | 3,601,888 |
import logging
def remote_ring(host: str, command: list, log: logging.Logger):
"""Remote ring over ssh. Returns `True` on success.
"""
ssh = ["/usr/bin/ssh",
"-t",
"-o", "ConnectTimeout=1",
"-o", "StrictHostKeyChecking=no",
host]
return system_call(ssh + com... | a3a05e98c49ca2af9f9c10625e8d9ad9baa00536 | 3,601,889 |
def geometry2layer(dataset, geom):
""" Convert geometry to a virtual-memory layer. """
# create layer
layer = dataset.CreateLayer(
'geom', geom.GetSpatialReference(), geom.GetGeometryType()
)
# add feature
feature = ogr.Feature(layer.GetLayerDefn())
feature.SetGeometry(geom)
laye... | fbbc6cd5c5dee6af790113bc6297a49aa6479a0d | 3,601,890 |
import numpy
def plane_fit(coordinates, center=None):
"""
Compute n-dimensional plane to a series or coordinates and return the
normal to that plane
:param coordinates: coordinates to fit a plane to
:type coordinates: :numpy:ndarray
:param center: point on the plane used as origin for t... | 4922b42c7c8a6c4faa7227386396ebc93bc1bafb | 3,601,891 |
def atanh(x : float) -> float:
"""
Inverse trigonometric function
Domain (-1 < x < 1)
"""
if not -1 < x < 1:
raise ValueError("Math domain error not in (-1,+1)")
return 0.5*functions.ln((1+x)/(1-x)) | a63ac82383d90d3c790035a901fbdabfca098b3b | 3,601,892 |
from typing import NamedTuple
from typing import Optional
def prepare_data_for_train(
# pylint: disable=g-bare-generic
input_tables: list,
preprocess_metadata: dict,
model_feature_columns: Optional[list] = None,
# pylint: enable=g-bare-generic
) -> NamedTuple(
'Outputs',
[
('time_s... | 112b340de85aee8199c528e830a76427cb3d18aa | 3,601,893 |
from typing import Any
import glob
import ast
import importlib
def process_args(args) -> Any:
"""
Validates args
:param args:
:return:
"""
possible_extensions = {'.g', '.gml', '.txt', '.gml', '.mat'}
graph_names = {fname[: fname.find(ext)].split('/')[-1]
for ext in poss... | 24432c251479b9bd3e7ad351075043ac64048d81 | 3,601,894 |
def vendor_factory(vendor_name):
"""
Given a full name of a vendor, retrieve or create the canonical
`~trigger.netdevices.Vendor` object.
Vendor instances are cached to improve startup speed.
:param vendor_name:
The vendor's full manufacturer name (e.g. 'CISCO SYSTEMS')
"""
return ... | d475c16e8c9561056564064ad0165efed9a6005b | 3,601,895 |
def hierachical_rollout2(
env,
scheduler,
worker,
skill_horizon=1,
max_path_length=np.inf,
render=False,
render_kwargs=None,
exclude_obs_ind=None,
obs_ind=None,
goal_ind=None,
):
"""
The following value for the following keys will b... | cbe1e7162aa77e8145a880d6f62a5006c98df55a | 3,601,896 |
def classify_Q_states(Q, Q_folded):
"""
This function determines the conformational state of each element of the native contacts array, given a threshold
for being 'folded/unfolded'. ***In the future we can generalize this to n different states.
In the outputted array, 1 is 'folded' and 0 is 'unfolded'.... | 2c667055c2a2d1543620e482651dc225b2153a97 | 3,601,897 |
def pyscv_get_widget(*args):
"""
pyscv_get_widget(py_this) -> TWidget *
"""
return _ida_kernwin.pyscv_get_widget(*args) | 22633cfbe0b62785150fc7ff5c1b5dedd7a5c801 | 3,601,898 |
def linear_scale_between(x1: float, x2: float, y1: float, y2: float, x: float, *, clamp=True, easing_func=None) -> float:
"""Standard linear interpolation function, optionally clamped (between y1 and y2)"""
pct = (x - x1) / (x2 - x1)
if easing_func:
pct = easing_func(pct)
if clamp:
pc... | f488346a4fe07b82f1281b646c3a39171b5fe757 | 3,601,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.