content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _normalize_dataframe(dataframe, index):
"""Take a pandas DataFrame and count the element present in the
given columns, return a hierarchical index on those columns
"""
#groupby the given keys, extract the same columns and count the element
# then collapse them with a mean
data = dataframe[in... | 5,322,600 |
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None):
"""Function to read the weights from checkpoint based on json description.
Args:
checkpoint: tensorflow checkpoint with trained model to
verify
model_json: path of json file with model description of
the net... | 5,322,601 |
def get_indicator_plugin_manager():
"""
Import all Hook classes that are in the plugins package
and make this availables for be called from master sources
"""
pm = pluggy.PluginManager("indicator")
pm.add_hookspecs(IndicatorSpec)
for class_imported in indicatorPluginClasses: # noqa: F405
... | 5,322,602 |
def cli(*args, **kwargs):
"""Yet another project manager."""
pass | 5,322,603 |
def run(command, **kwargs):
"""Run and return the output of a command.
Raise CalledProcessError on error.
Pass in any kind of shell-executable line you like, with one or more
commands, pipes, etc. Any kwargs will be shell-escaped and then subbed into
the command using ``format()``::
>>> r... | 5,322,604 |
def to_date(string, format="%d/%m/%Y"):
"""Converts a string to datetime
:param string: String containing the date.
:type string: str
:param format: The date format. Use %Y for year, %m for months and %d for daus, defaults to "%d/%m/%Y"
:type format: str, optional
:return: The present data in s... | 5,322,605 |
def invert_apply_grouping2(grouped_items, groupxs, dtype=None):
"""use only when ungrouping will be complete"""
maxval = _max(list(map(_max, groupxs)))
ungrouped_items = np.zeros((maxval + 1,), dtype=dtype)
for itemgroup, ix_list in zip(grouped_items, groupxs):
ungrouped_items[ix_list] = itemgro... | 5,322,606 |
def make_aware_assuming_local(dt):
"""
Just a wrapper for Django's method, which will takes a naive datetime, and makes it timezone
aware, assuming the current timezone if none is passed (which it isn't from this wrapper
function). It will also raise an exception if the passed datetime is already timezo... | 5,322,607 |
def pad_word_array(word_array, MAX_SEQUENCE_LENGTH, padding='pre', truncating='pre'):
"""Return a word array that is of a length MAX_SEQUENCE_LENGTH by truncating the original array or padding it
Args:
word_array:
MAX_SEQUENCE_LENGTH:
padding:
truncating:
Returns:
"""
... | 5,322,608 |
def nbconvert(code):
"""Create Jupyter Notebook code
Return dict in ipynb format
Arguments:
code -- code string separated by \\n
"""
cells = []
for cell in code.split("\n# <codecell>\n"):
cells.append({
"cell_type": "code",
"execution_count": None,
... | 5,322,609 |
def add_box(width, height, depth):
"""
This function takes inputs and returns vertex and face arrays.
no actual mesh data creation is done here.
"""
verts = [
(+1.0, +1.0, 0.0),
(+1.0, -1.0, 0.0),
(-1.0, -1.0, 0.0),
(-1.0, +1.0, 0.0),
(+1.0, +1.0, +2.0),
... | 5,322,610 |
def test_register_simple_extension_class_using_decorator(extensionregistry):
"""
Test registering simple Extension class using the extension decorator
"""
# given & when
@extension
class SimpleExtension(object):
pass
# then
assert len(extensionregistry.extensions) == 1
asser... | 5,322,611 |
def pixmap(randoms, targets, rand_density, nside=256, gaialoc=None):
"""HEALPix map of useful quantities for a Legacy Surveys Data Release
Parameters
----------
randoms : :class:`~numpy.ndarray` or `str`
Catalog or file of randoms as made by :func:`select_randoms()` or
:func:`quantities... | 5,322,612 |
def filter_keys(data: dict, keys: Union[Callable, Sequence],
return_popped=False) -> Union[dict, Tuple[dict, dict]]:
"""
Filters keys from a given data dict
Args:
data: the dictionary to pop the keys from
keys: if callable it must return a boolean for each key indicating
... | 5,322,613 |
def test_cached_db_backend_log_session_access_recently_used_no_cache(api_session):
"""Test when user has accessed but cache has expired"""
backend = CachedDBSessionAccessBackend()
now = timezone.now()
last_access = now - datetime.timedelta(seconds=INACTIVITY_TIMEOUT - 1)
api_session.accesses.create... | 5,322,614 |
def beta_ion(T_rad, species):
"""Case-B photoionization coefficient.
Parameters
----------
T_rad : float
The radiation temperature.
species : {'HI', 'HeI_21s', 'HeI_23s'}
The relevant species.
Returns
-------
float
Case-B photoionization coefficient in s\ :sup:`... | 5,322,615 |
def load_template(template_path, template_name):
"""Loads a Jinja template from a given path and name
Arguments:
template_file {PathToDir: Path/String}
template_name {Filename: String}
Raises:
IOError: This path does not exist
"""
if isinstance(template_path, Path):
... | 5,322,616 |
def html(string):
"""Return inline html element."""
return RawInline('html', string) | 5,322,617 |
def mock_user_moira_lists(mocker):
"""Return a fake moira client"""
mocked = mocker.patch("ui.utils.user_moira_lists")
mocked.return_value = set()
return mocked | 5,322,618 |
def translateAllIndex(text):
"""
This is the translator API
Call this api passing a piece of text and get back the Swedish translation
---
tags:
- Translation API
parameters:
- name: text
in: path
type: string
required: true
description: The text
r... | 5,322,619 |
def get_network_config(net_topology, ignore_env_vars=False,
net_topology_file="network.yaml"):
"""Get network info from environment.
Get network info from network.yaml, override the values if specific
environment variables are set for the undercloud.
This function may be used wh... | 5,322,620 |
def get_testbeds_dict():
"""Return a dictionary containing mapping from dut hostname to testbed name."""
testbed = imp.load_source('testbed', os.path.join(SONIC_MGMT_DIR, 'tests/common/testbed.py'))
testbeds_dict = testbed.TestbedInfo(TESTBED_FILE).testbed_topo
return testbeds_dict | 5,322,621 |
def AIHT(x, A, AT, m, M, thresh, proximalProjection=None):
"""
Accelerated Iterative Hard thresholding algorithm that keeps exactly M elements
in each iteration. This algorithm includes an additional double
overrelaxation step that significantly improves convergence speed without
destroying any of the theoretical... | 5,322,622 |
def permutate(array: list, permutation: list):
""" permutate a fixed array with a given permutation list
Args:
array: An array of random elements
permutation: The permutation of the given array
Returns:
"""
_swapped_array = []
_counter = 0
for i in permutation:
... | 5,322,623 |
def pager_redirect(desc, *, pagercmd=None, istty=None, file=None,
substitutions=None):
""" Redirect output to file/stdout to a pager process. Care is taken to
restore the controlling tty stdio files to their original state. """
if file is None:
file = sys.stdout
if not pagerc... | 5,322,624 |
def write_seg_records(dataset, tfrecord_dir, storm):
"""
"write_seg_records(dataset, tfrecord_dir)"
This function writes a tf.data.Dataset object to TFRecord shards
The version for data preprends "" to the filenames, but otherwise is identical
to write_seg_records
INPUTS:
* dataset [tf.d... | 5,322,625 |
def server():
"""Run the server."""
print('Press CTRL+C to exit...')
loop = asyncio.get_event_loop()
server_instance = Server(loop)
server_instance.start()
try:
loop.run_forever()
except KeyboardInterrupt:
pass
loop.close() | 5,322,626 |
def has_collided_with_wall(
width: int, height: int, segments: list[SnakeSegment]
) -> bool:
"""Return True if the snake has collided with a wall."""
head = segments[0]
return (
head.x <= 1 or head.x > width - 3 or head.y < 1 or head.y >= height - 2
) | 5,322,627 |
def plot_heatmap_max_val(env, value):
"""
Generate heatmap showing maximum value at each state (not for n-armed
bandit).
"""
if env.name == 'n_armed_bandit':
print("Heatmap can only be generated for grid worlds.")
return None
if value.ndim == 1:
value_max = np.reshape(v... | 5,322,628 |
def add_to_fanout(observer):
"""
Add the given observer to the global instance of :class:`FanoutObserver`
:param callable observer: The observer to fan out to.
:return: `None`
"""
global _fanout
if _fanout is None:
_fanout = FanoutObserver(observer)
else:
_fanout.add_obs... | 5,322,629 |
def invalid_image_id():
"""
Invalid Image Id Error.
@raise Ec2stackError: Defining a bad request and message.
"""
raise Ec2stackError(
'400',
'InvalidAMIID.NotFound',
'The specified AMI Id does not exist.'
) | 5,322,630 |
def clear_update_flag(source_id):
"""Clear pending update flag after updating Koku provider."""
source = get_source(source_id, f"[clear_update_flag] error: source_id: {source_id} does not exist.", LOG.error)
if source and source.koku_uuid and source.pending_update:
source.pending_update = False
... | 5,322,631 |
def separate_lines(lines,imshape):
"""
separate_lines(lines)
Classifies left and right lines based on slope
---------------------------------------------------------------------------
INPUT:
lines: line points [[x1,y1,x2,y2]]
OUTPUT:
right{}: right line dictionary with the follo... | 5,322,632 |
def p_climo_one_season( seasonname, datafilenames, omit_files, varnames, fileout_template,
time_units, calendar, dt, force_scalar_avg1,
input_global_attributes, filerank={}, filetag={},
outseasons=None, queue1=None, lock1=None, comm1=None ):
"""cli... | 5,322,633 |
def two_view_reconstruction_rotation_only(p1, p2, camera1, camera2, threshold):
"""Find rotation between two views from point correspondences.
Args:
p1, p2: lists points in the images
camera1, camera2: Camera models
threshold: reprojection error threshold
Returns:
rotation ... | 5,322,634 |
async def async_turn_off(opp, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified vacuum off."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
await opp.services.async_call(DOMAIN, SERVICE_TURN_OFF, data, blocking=True) | 5,322,635 |
def state_lookup():
"""Look up state from given zipcode.
Once state is found, redirect to call_senators for forwarding.
"""
zip_digits = request.values.get('Digits', None)
# NB: We don't do any error handling for a missing/erroneous zip code
# in this sample application. You, gentle reader, sho... | 5,322,636 |
def test_synthesize_edge_selector():
"""
Tests the ability to synthesize an edge selector given information about
selected edge(s).
"""
selected_edges = ["edge_1234"]
selected_edge_types = ["LINE"]
selected_edge_starts = [(5, -5, 5)]
selected_edge_ends = [(5, 5, 5)]
selected_edge_nor... | 5,322,637 |
def vmtkmeshtosurface(mesh, cleanoutput=1):
"""Convert a mesh to a surface by throwing out volume elements and (optionally) the relative points
Args:
mesh: Volumetric mesh.
cleanoutput (bool): Remove unused points.
Returns:
vtkPolyData object.
"""
extractor = vm... | 5,322,638 |
def confirm_wrong_tag(commit, tag):
""" Confirm deployment when commit does not have expected tag. """
require('noinput')
print(red('WARNING: This commit does not have the %s tag.' % tag))
if not env.noinput:
confirmed = confirm('Are you really sure you want to deploy %s?' % commit.hexsha, def... | 5,322,639 |
def time_delta_calc(contiguous_trajectory,order = 2):
"""Computes the time derivatives of a contiguous trajectory.
INPUT
contiguous_trajectory An array of space-time cordinates
order The order up to which the time derivatives are calculated. If
order=1, the velo... | 5,322,640 |
def test_dense2_minimum_fraction():
"""Test fit_transform a dense matrix including NaNs with minimum_fraction=0.5"""
fit_then_transform(
dense2_1h_minimum_fraction,
dense2,
minimum_fraction=0.3
)
fit_then_transform_dense(
dense2_1h_minimum_fraction,
dense2,
... | 5,322,641 |
def generator():
"""生成器函数"""
yield 1 | 5,322,642 |
def tasks_page():
""" Tasks and completions page
"""
return flask.render_template(
'tasks.html',
config=g.project.config,
project=g.project,
version=label_studio.__version__,
**find_editor_files()
) | 5,322,643 |
def outformathtml(pandasdf):
"""
change a few formating things to prettify and make it match
"""
pandas_table = pandasdf.to_html()
pandas_table = pandas_table.replace(""" border="1" """, " ")
pandas_table = pandas_table.replace("""<tr style="text-align: right;">\n <th></th>\n <th></th>... | 5,322,644 |
def get_files(pointing_id, access="isdc"):
"""
Function to get the needed files for a certain pointing_id and save
them in the correct folders.
:param pointing_id: Id of pointing e.g. '180100610010' as string or int
:param access: How to get the data. Possible are "isdc" and "afs"
:return:
"... | 5,322,645 |
def list_catalogs(**kwargs):
"""
Return the available Cone Search catalogs as a list of strings.
These can be used for the ``catalog_db`` argument to
:func:`conesearch`.
Parameters
----------
cache : bool
Use caching for VO Service database. Access to actual VO
websites refe... | 5,322,646 |
def rot_decode(data: str, n: int = 13) -> str:
"""Decode a ROT-encoded string that was shifted by `n` places."""
if not 1 <= n < 26:
raise ValueError('n must be in range [1, 26)')
return rot_encode(data, 26 - n) | 5,322,647 |
def test_pitch_range_clip():
"""Pitch in this time range goes from approximately 48.5 to 175.0 degrees.
pftank2t.json is used as a placeholder to load a new thermal model, and
should be able to be replaced with any other model. Make sure the pitch
range stored in the model object does not get clipped to... | 5,322,648 |
def searchlight(x, y, m=None, groups=None, cv=None,
write=False, logger=None, permutations=0, random_state=42, **searchlight_args):
"""
Wrapper to launch searchlight
:param x: Data
:param y: labels
:param m: mask
:param groups: group labels
:param cv: cross validator
:par... | 5,322,649 |
def test_ap_hs20_no_match_connect(dev, apdev):
"""Hotspot 2.0 and connect attempt without matching cred"""
bssid = apdev[0]['bssid']
params = hs20_ap_params()
hapd = hostapd.add_ap(apdev[0], params)
dev[0].hs20_enable()
dev[0].scan_for_bss(bssid, freq="2412")
id = dev[0].add_cred_values({'... | 5,322,650 |
def show(img, cmap = 'plasma', colorbar = True):
"""Displays image with colorbar."""
imgstd = img.std()
imgmean = img.mean()
ll = imgmean - (2*imgstd)
ul = imgmean + (2*imgstd)
# for i in range(img.shape[0]):
# for j in range(img.shape[1]):
# if np.logical_or((img[i, j] < ll)... | 5,322,651 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_ioc_parser_v2 package"""
reload_params = {"package": u"fn_ioc_parser_v2",
"incident_fields": [],
"action_fields": [],
"function_params": [u"ioc_parser_v2_artifact_id", u"ioc_... | 5,322,652 |
def Pattern2(s):
""" Compute the correlator for this pattern:
↓
↓ ↑ ↑
and symmetry-equivalent patterns
"""
res = 0.0
s = np.pad(s, ((0, 0), (2, 2), (2, 2)))
L = s.shape[-1]
for i in range(L-2):
for j in range(L-2):
res += s[1, i, j] * s[0, i+1,... | 5,322,653 |
def gauss(x, x0, sigma):
"""
This function returns a Gaussian distribution.
"""
return (1/(sigma*math.sqrt(2 * math.pi))) * np.exp(-(x - x0)**2 / (2 * sigma**2)) | 5,322,654 |
def fails_to_deliver(
ticker: str,
stock: pd.DataFrame,
start: datetime,
end: datetime,
num: int,
raw: bool,
export: str = "",
):
"""Display fails-to-deliver data for a given ticker. [Source: SEC]
Parameters
----------
ticker : str
Stock ticker
stock : pd.DataFra... | 5,322,655 |
def distance():
"""
Calculate the distance between two points.
return:
Distance.
"""
return lambda a, b: math.sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*+(a.y-b.y)+(a.z-b.z)*(a.z-b.z)) | 5,322,656 |
def rational_sum(numerator, denominator, *argv):
"""Sum of rational numbers."""
if len(argv) < 2:
gcd = numpy.gcd(numerator, denominator)
num_out, den_out = numerator//gcd, denominator//gcd
else:
num_2 = argv[0]
den_2 = argv[1]
num_3 = numerator*den_2 + num_2*denomina... | 5,322,657 |
def nonce() -> str:
"""Return a nounce counter (monotonic clock).
References:
* https://support.kraken.com/hc/en-us/articles/360000906023-What-is-a-nonce-
""" # pylint: disable=line-too-long
return str(time.monotonic_ns()) | 5,322,658 |
def fetch_single_equity(stock_code, start, end):
"""
从本地数据库读取股票期间日线交易数据
注
--
1. 除OHLCV外,还包括涨跌幅、成交额、换手率、流通市值、总市值、流通股本、总股本
2. 添加后复权价格,使用复权价在图中去除间隙断层
3. 使用bcolz格式写入时,由于涨跌幅存在负数,必须剔除该列
Parameters
----------
stock_code : str
要获取数据的股票代码
start_date : datetime-like
自... | 5,322,659 |
def generate():
"""Generates a dictionary of all the known CRC formats from:
https://reveng.sourceforge.io/crc-catalogue/all.htm
See pwnlib/data/crcsum.txt for more information.
"""
curdir, _ = os.path.split(__file__)
path = os.path.join(curdir, '..', '..', 'data', 'crcsums.txt')
with open... | 5,322,660 |
def base62_encode(number):
"""Encode a number in base62 (all digits + a-z + A-Z)."""
base62chars = string.digits + string.ascii_letters
l = []
while number > 0:
remainder = number % 62
number = number // 62
l.insert(0, base62chars[remainder])
return ''.join(l) or '0' | 5,322,661 |
def handle_update(config_path):
"""
handle changes in globalConfig.json
Args:
config_path : path to globalConfig.json
Returns:
dictionary : schema_content (globalConfig.json)
"""
with open(config_path) as config_file:
schema_content = json.load(config_file)
version... | 5,322,662 |
def encode(s: Sequence[Tuple[str, str]], similar_to: str=None) -> str:
"""
Takes a list of (key, value) tuples and returns a urlencoded string.
If similar_to is passed, the output is formatted similar to the provided urlencoded string.
"""
remove_trailing_equal = False
if similar_to:
... | 5,322,663 |
def save_network(G, prefix = None, suffix = None, use_graphml = False,
use_gpu = False):
"""Save a network to disk
Args:
G (network)
Graph tool network
prefix (str)
Prefix for output file
use_graphml (bool)
Whether to output a graph-tool fil... | 5,322,664 |
def gis_ellipse_polygon(origin, a, b, orientation=0.0, complexity=128):
"""
Generate a polygon of an ellipse suitable for GIS applications.
:param origin: the center of the ellipse (expected to be UTM, m)
:param a: the a/semi-major axis length (expected to be UTM, m)
:param b: the b/semi-minor axis... | 5,322,665 |
def activate_lesson():
"""
{
"id": 51,
"active": "A"
}
"""
domain = request.get_json()
return lesson_service.activate_lesson(domain) | 5,322,666 |
def split(labels, n_per_class=20, seed=0):
"""
Randomly split the training data.
Parameters
----------
labels: array-like [n_nodes]
The class labels
n_per_class : int
Number of samples per class
seed: int
Seed
Returns
-------
split_train: array-like [n_p... | 5,322,667 |
def base():
"""test Setfilter """
# build fixture
from setfilter.setfilter import Setfilter
# initialization
center = np.array([0, 0, 0, 0.])
body = np.array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
... | 5,322,668 |
def test():
"""Opens the test suite on a web browser.
"""
pack()
web_browser = prompt('Please choose your web browser', \
default=env.web_browser)
local('%s %s/testSuite.html &' % (web_browser, env.test_dir)) | 5,322,669 |
def compare_image_folders(folder1, folder2, direction='horizontal', pause_sec=0):
"""
Compare image folders
:param folder1:
:param folder2:
:param direction:
:param pause_sec:
:return:
"""
filenames1 = sorted(get_filenames_in_a_directory(folder1))
for filename in filenames1:
... | 5,322,670 |
def stack(*cons):
"""
Combine constraints into a large constaint
by intersection.
Parameters
----------
cons : [`selection.affine.constraints`_]
A sequence of constraints.
Returns
-------
intersection : `selection.quasi_affine.constraints`_
Notes
-----
Res... | 5,322,671 |
def _create_poi_gdf(
tags,
polygon=None,
north=None,
south=None,
east=None,
west=None,
timeout=180,
memory=None,
custom_settings=None,
):
"""
Create GeoDataFrame from POIs json returned by Overpass API.
Parameters
----------
tags : dict
Dict of tags used ... | 5,322,672 |
def _execute_ndr_job(
global_wgs84_bb, watersheds_path, local_workspace_dir, dem_path,
lulc_path,
runoff_proxy_path, fertilizer_path, biophysical_table_path,
threshold_flow_accumulation, k_param, target_pixel_size,
biophysical_table_lucode_field, stitch_raster_queue_map,
... | 5,322,673 |
def speed_is_less_than_160(my_car):
"""Speed is less than 160."""
my_car.speed = 50 | 5,322,674 |
def update_webpack_loader(webpack_loader_settings, figures_env_tokens):
"""
Update the WEBPACK_LOADER in the settings.
"""
# Specify the 'figures' package directory
figures_app_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Define our webpack asset bundling constants
# ... | 5,322,675 |
def prepare_data(seqs, labels, maxlen=None, x_dim = 3, mapping=None, max_mapping=None):
"""Create the matrices from the datasets.
This pad each sequence to the same length: the length of the
longest sequence or maxlen.
if maxlen is set, we will cut all sequence to this maximum
length.
This sw... | 5,322,676 |
def _get_prediction_tensor(
predictions_dict):
"""Returns prediction Tensor for a specific Estimators.
Returns the prediction Tensor for some regression Estimators.
Args:
predictions_dict: Predictions dictionary.
Returns:
Predictions tensor, or None if none of the expected keys are found in
t... | 5,322,677 |
def gen_confirm_code():
""" Generate a new email confirmation code and return it
"""
return generate_uuid_readable(9) | 5,322,678 |
def make_event_crawl_jobs(entries: List[BugoutSearchResult]) -> List[EventCrawlJob]:
"""
Create EventCrawlJob objects from bugout entries.
"""
crawl_job_by_hash: Dict[str, EventCrawlJob] = {}
for entry in entries:
abi_hash = _get_tag(entry, "abi_method_hash")
contract_address = Web... | 5,322,679 |
def _update_object_class_from_meta(
object_class: type,
new_object_metadata: abc.ObjectMeta,
memo: Dict[str, type],
) -> None:
"""
This function merges new metadata into an existing object model's metadata.
Parameters:
- object_class (type)
- new_object_metadata (sob.meta.Object)
-... | 5,322,680 |
def save_site_settings(settings):
""" Take a settings dictionary as returned by get_site_settings and save it to the database. """
for key, value in settings.items():
setting = model.SiteSettings.query.filter_by(setting=key).first()
if not setting:
setting = model.SiteSettings()
... | 5,322,681 |
def _load_objects():
"""Delay loading expensive modules. We just want to detect if *input
arrays* belong to these types -- and if this is the case, it means the
module has already been imported! So, we only try loading these classes
within autoformat calls. This saves >~500ms of import time."""
glob... | 5,322,682 |
def test_stations_within_radius():
"""Tests subroutine stations_within_radius"""
# Build list of stations
stations = build_station_list()
#Values to try
filter_radius = 10
centre = (52.2053, 0.1218)
station_list = stations_within_radius(stations, centre, filter_radius)
#Find station '... | 5,322,683 |
def update_profile():
"""
Update profile page
"""
form = UpdateProfileForm() # Update profile form
if form.validate_on_submit(): # If form is submitted and validated
if form.picture.data: # If picture is uploaded
picture = save_picture(form.picture.data) # Save picture
... | 5,322,684 |
def get_version_info(pe):
"""Return version information"""
res = {}
for fileinfo in pe.FileInfo:
if fileinfo.Key == 'StringFileInfo':
for st in fileinfo.StringTable:
for entry in st.entries.items():
res[entry[0]] = entry[1]
if fileinfo.Key == '... | 5,322,685 |
def parse_data(objects, out_map, width):
"""Parses tile data from the objects source"""
count = 0
for tile in objects:
col = count % width
row = count // width
count += 1
if tile == 1:
out_map["objects"].append({"x": col, "y": row, "name": "WALL"})
elif t... | 5,322,686 |
def parse_settings(settings_file):
"""Parse settings file"""
settings = yaml.full_load(settings_file)
for item, element in settings.items():
if item == "datapoints":
parse_datapoints(element)
if item == "requests":
parse_requests(element)
if item == "mqtt":
... | 5,322,687 |
def data_prepare(coord, feat, label, split='train', voxel_size=0.04, voxel_max=None, transform=None, shuffle_index=False, origin='min'):
""" coord, feat, label - an entire cloud
"""
if transform:
coord, feat, label = transform(coord, feat, label)
if voxel_size:
# voxelize the entire clou... | 5,322,688 |
async def test_calling_service_basic(hass):
"""Test the calling of a service."""
context = Context()
@callback
def record_call(service):
"""Add recorded event to set."""
calls.append(service)
hass.services.async_register("test", "script", record_call)
schema = cv.SCRIPT_SCHEMA... | 5,322,689 |
def test_add_analytic_vs_tabulated():
"""Compare analytic vs tabulated Gaussian PSFs.
"""
c = CoAdd1D(100., 200., 0.5, 50.)
data = [1, 3, 2], [150, 160, 170, 180], [0.1, 0.2, 0.1]
psf_grid = c.grid_scale * np.arange(-10, +11)
for convolve in True, False:
# Common PSF for all pixels.
... | 5,322,690 |
def init_db_command():
"""Comando para la linea de comandos
llamado init-db que invoca a la función init_db"""
init_db()
# Mensaje para cuando se ejecute init-db
click.echo("Base de datos inicializada en MySQL") | 5,322,691 |
def eliminate_hyphen_in_variety(apps, schema_editor):
"""This operation elminates hypen-corrupted fields"""
mineral_type = apps.get_model("stein", "MineralType")
for m in mineral_type.objects.filter(variety__contains="-").all():
m.variety = ""
m.save() | 5,322,692 |
def add_wsl_blobs(blobs, im_scales, im_crops, roidb):
"""Add blobs needed for training Fast R-CNN style models."""
# Sample training RoIs from each image and append them to the blob lists
for im_i, entry in enumerate(roidb):
frcn_blobs = _sample_rois(entry, im_scales[im_i], im_crops[im_i], im_i)
... | 5,322,693 |
def _right_branching(nodes):
"""
Parameters
----------
nodes: list[T], where T denotes NonTerminal or Terminal
Returns
-------
list[T], where T denotes NonTerminal or Terminal
"""
if len(nodes) == 2:
return nodes
lhs = nodes[0] # The left-most child node is head
ind... | 5,322,694 |
def random_swap(o_a, o_b):
"""
Randomly swap elements of two observation vectors and return new vectors.
:param o_a: observation vector a
:param o_b: observation vector b
:return: shuffled vectors
"""
X, Y = [], []
tf = [True, False]
for x, y in zip(o_a, o_b):
if random.choi... | 5,322,695 |
def test_rrm_beacon_req_table_request_oom(dev, apdev):
"""Beacon request - beacon table mode - request element OOM"""
params = {"ssid": "rrm", "rrm_beacon_report": "1"}
hapd = hostapd.add_ap(apdev[0], params)
dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
addr = dev[0].own_addr()
wit... | 5,322,696 |
def parse_multiplicative(index):
"""Parse multiplicative expression."""
return parse_series(
index, parse_unary,
{token_kinds.star: expr_nodes.Mult,
token_kinds.slash: expr_nodes.Div,
token_kinds.mod: expr_nodes.Mod}) | 5,322,697 |
def return_factorized_dict(ls):
"""
###### Factorize any list of values in a data frame using this neat function
if your data has any NaN's it automatically marks it as -1 and returns that for NaN's
Returns a dictionary mapping previous values with new values.
"""
factos = pd.unique(pd.fa... | 5,322,698 |
def build(dirname: str = "env") -> None:
"""実行環境の生成を行う
WARN: Macは対応してません(使わないので)
Args:
dirname (string): 生成先のディレクトリ. デフォルトはenv/.
Raises:
DirectoryNotFoundError: 実行環境の生成に必要なディレクトリが存在しない時に投げられるエラー
DirectoryAlreadyExistsError: 実行環境が既に生成されていると投げられます
"""
# TODO: .envなどに切り出す... | 5,322,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.