Search is not available for this dataset
text stringlengths 75 104k |
|---|
def deprecated(fun_name=None, msg=""):
'''Issue a deprecation warning for a function'''
def _deprecated(fun):
'''Issue a deprecation warning for a function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Issue deprecation warning and forward arguments to fun'''
n... |
def check_wrapper(fun):
'''Decorate a checking function'''
@wraps(fun)
def _wrapper(*args, **kwargs):
'''Sets the title property of the result of running a checker'''
title = fun.__name__.replace('_', ' ').capitalize()
result = fun(*args, **kwargs)
result.title = title
... |
def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in utils.get_files_by_path(path):
L.info(SEPARATOR)
status, summ = self._check_file(_f)
res &= status
... |
def _do_check(self, obj, check_module, check_str):
'''Run a check function on obj'''
opts = self._config['options']
if check_str in opts:
fargs = opts[check_str]
if isinstance(fargs, list):
out = check_wrapper(getattr(check_module, check_str))(obj, *fargs)... |
def _check_loop(self, obj, check_mod_str):
'''Run all the checks in a check_module'''
check_module = self._check_modules[check_mod_str]
checks = self._config['checks'][check_mod_str]
result = True
summary = OrderedDict()
for check in checks:
ok = self._do_chec... |
def _check_file(self, f):
'''Run tests on a morphology file'''
L.info('File: %s', f)
full_result = True
full_summary = OrderedDict()
try:
data = load_data(f)
except Exception as e: # pylint: disable=W0703
L.error('Failed to load data... skipping ... |
def _log_msg(self, msg, ok):
'''Helper to log message to the right level'''
if self._config['color']:
CGREEN, CRED, CEND = '\033[92m', '\033[91m', '\033[0m'
else:
CGREEN = CRED = CEND = ''
LOG_LEVELS = {False: logging.ERROR, True: logging.INFO}
# pylint:... |
def _sanitize_config(config):
'''check that the config has the correct keys, add missing keys if necessary'''
if 'checks' in config:
checks = config['checks']
if 'structural_checks' not in checks:
checks['structural_checks'] = []
if 'neuron_checks' not... |
def read(filename, data_wrapper=DataWrapper):
'''Read an SWC file and return a tuple of data, format.'''
data = np.loadtxt(filename)
if len(np.shape(data)) == 1:
data = np.reshape(data, (1, -1))
data = data[:, [X, Y, Z, R, TYPE, ID, P]]
return data_wrapper(data, 'SWC', None) |
def _merge_sections(sec_a, sec_b):
'''Merge two sections
Merges sec_a into sec_b and sets sec_a attributes to default
'''
sec_b.ids = list(sec_a.ids) + list(sec_b.ids[1:])
sec_b.ntype = sec_a.ntype
sec_b.pid = sec_a.pid
sec_a.ids = []
sec_a.pid = -1
sec_a.ntype = 0 |
def _section_end_points(structure_block, id_map):
'''Get the section end-points'''
soma_idx = structure_block[:, TYPE] == POINT_TYPE.SOMA
soma_ids = structure_block[soma_idx, ID]
neurite_idx = structure_block[:, TYPE] != POINT_TYPE.SOMA
neurite_rows = structure_block[neurite_idx, :]
soma_end_pts... |
def _extract_sections(data_block):
'''Make a list of sections from an SWC-style data wrapper block'''
structure_block = data_block[:, COLS.TYPE:COLS.COL_COUNT].astype(np.int)
# SWC ID -> structure_block position
id_map = {-1: -1}
for i, row in enumerate(structure_block):
id_map[row[ID]] = i... |
def neurite_root_section_ids(self):
'''Get the section IDs of the intitial neurite sections'''
sec = self.sections
return [i for i, ss in enumerate(sec)
if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and
ss.ntype != POINT_TYPE.SOMA)] |
def soma_points(self):
'''Get the soma points'''
db = self.data_block
return db[db[:, COLS.TYPE] == POINT_TYPE.SOMA] |
def add_section(self, id_, parent_id, section_type, points):
'''add a section
Args:
id_(int): identifying number of the section
parent_id(int): identifying number of the parent of this section
section_type(int): the section type as defined by POINT_TYPE
p... |
def _make_datablock(self):
'''Make a data_block and sections list as required by DataWrapper'''
section_ids = sorted(self.sections)
# create all insertion id's, this needs to be done ahead of time
# as some of the children may have a lower id than their parents
id_to_insert_id =... |
def _check_consistency(self):
'''see if the sections have obvious errors'''
type_count = defaultdict(int)
for _, section in sorted(self.sections.items()):
type_count[section.section_type] += 1
if type_count[POINT_TYPE.SOMA] != 1:
L.info('Have %d somas, expected 1... |
def get_datawrapper(self, file_format='BlockNeuronBuilder', data_wrapper=DataWrapper):
'''returns a DataWrapper'''
self._check_consistency()
datablock, sections = self._make_datablock()
return data_wrapper(datablock, file_format, sections) |
def _is_morphology_file(filepath):
""" Check if `filepath` is a file with one of morphology file extensions. """
return (
os.path.isfile(filepath) and
os.path.splitext(filepath)[1].lower() in ('.swc', '.h5', '.asc')
) |
def get_morph_files(directory):
'''Get a list of all morphology files in a directory
Returns:
list with all files with extensions '.swc' , 'h5' or '.asc' (case insensitive)
'''
lsdir = (os.path.join(directory, m) for m in os.listdir(directory))
return list(filter(_is_morphology_file, lsdir)... |
def get_files_by_path(path):
'''Get a file or set of files from a file path
Return list of files with path
'''
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
return get_morph_files(path)
raise IOError('Invalid data path %s' % path) |
def load_neuron(handle, reader=None):
'''Build section trees from an h5 or swc file'''
rdw = load_data(handle, reader)
if isinstance(handle, StringType):
name = os.path.splitext(os.path.basename(handle))[0]
else:
name = None
return FstNeuron(rdw, name) |
def load_neurons(neurons,
neuron_loader=load_neuron,
name=None,
population_class=Population,
ignored_exceptions=()):
'''Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Param... |
def _get_file(handle):
'''Returns the filename of the file to read
If handle is a stream, a temp file is written on disk first
and its filename is returned'''
if not isinstance(handle, IOBase):
return handle
fd, temp_file = tempfile.mkstemp(str(uuid.uuid4()), prefix='neurom-')
os.close... |
def load_data(handle, reader=None):
'''Unpack data into a raw data wrapper'''
if not reader:
reader = os.path.splitext(handle)[1][1:].lower()
if reader not in _READERS:
raise NeuroMError('Do not have a loader for "%s" extension' % reader)
filename = _get_file(handle)
try:
r... |
def _load_h5(filename):
'''Delay loading of h5py until it is needed'''
from neurom.io import hdf5
return hdf5.read(filename,
remove_duplicates=False,
data_wrapper=DataWrapper) |
def _filepath(self, name):
""" File path to `name` morphology file. """
if self.file_ext is None:
candidates = glob.glob(os.path.join(self.directory, name + ".*"))
try:
return next(filter(_is_morphology_file, candidates))
except StopIteration:
... |
def draw(obj, mode='2d', **kwargs):
'''Draw a morphology object
Parameters:
obj: morphology object to be drawn (neuron, tree, soma).
mode (Optional[str]): drawing mode ('2d', '3d', 'dendrogram'). Defaults to '2d'.
**kwargs: keyword arguments for underlying neurom.view.view functions.
... |
def histogram(neurons, feature, new_fig=True, subplot=False, normed=False, **kwargs):
'''
Plot a histogram of the selected feature for the population of neurons.
Plots x-axis versus y-axis on a scatter|histogram|binned values plot.
More information about the plot and how it works.
Parameters :
... |
def population_feature_values(pops, feature):
'''Extracts feature values per population
'''
pops_feature_values = []
for pop in pops:
feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.neurons]
# ugly hack to chain in case of list of lists
if any([isinstance(p, ... |
def population_histogram(pops, feature, new_fig=True, normed=False, subplot=False, **kwargs):
'''
Plot a histogram of the selected feature for the population of neurons.
Plots x-axis versus y-axis on a scatter|histogram|binned values plot.
More information about the plot and how it works.
Paramete... |
def get_segment(neuron, section_id, segment_id):
'''Get a segment given a section and segment id
Returns:
array of two [x, y, z, r] points defining segment
'''
sec = neuron.sections[section_id]
return sec.points[segment_id:segment_id + 2][:, COLS.XYZR] |
def extract_data(data_path, feature):
'''Loads a list of neurons, extracts feature
and transforms the fitted distribution in the correct format.
Returns the optimal distribution, corresponding parameters,
minimun and maximum values.
'''
population = nm.load_neurons(data_path)
featu... |
def local_bifurcation_angle(bif_point):
'''Return the opening angle between two out-going sections
in a bifurcation point
We first ensure that the input point has only two children.
The bifurcation angle is defined as the angle between the first non-zero
length segments of a bifurcation point.
... |
def remote_bifurcation_angle(bif_point):
'''Return the opening angle between two out-going sections
in a bifurcation point
We first ensure that the input point has only two children.
The angle is defined as between the bifurcation point and the
last points in the out-going sections.
'''
as... |
def bifurcation_partition(bif_point):
'''Calculate the partition at a bifurcation point
We first ensure that the input point has only two children.
The number of nodes in each child tree is counted. The partition is
defined as the ratio of the largest number to the smallest number.'''
assert len(b... |
def partition_asymmetry(bif_point):
'''Calculate the partition asymmetry at a bifurcation point
as defined in https://www.ncbi.nlm.nih.gov/pubmed/18568015
The number of nodes in each child tree is counted. The partition
is defined as the ratio of the absolute difference and the sum
of the number of... |
def partition_pair(bif_point):
'''Calculate the partition pairs at a bifurcation point
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two daughter subtrees
at each branch point.'''
n = float(sum(1 for _ in bif_point.children[0].ipreorder(... |
def _match_section(section, match):
'''checks whether the `type` of section is in the `match` dictionary
Works around the unknown ordering of s-expressions in each section.
For instance, the `type` is the 3-rd one in for CellBodies
("CellBody"
(Color Yellow)
(CellBody)
(S... |
def _get_tokens(morph_fd):
'''split a file-like into tokens: split on whitespace
Note: this also strips newlines and comments
'''
for line in morph_fd:
line = line.rstrip() # remove \r\n
line = line.split(';', 1)[0] # strip comments
squash_token = [] # quoted strings get squ... |
def _parse_section(token_iter):
'''take a stream of tokens, and create the tree structure that is defined
by the s-expressions
'''
sexp = []
for token in token_iter:
if token == '(':
new_sexp = _parse_section(token_iter)
if not _match_section(new_sexp, UNWANTED_SECTIO... |
def _parse_sections(morph_fd):
'''returns array of all the sections that exist
The format is nested lists that correspond to the s-expressions
'''
sections = []
token_iter = _get_tokens(morph_fd)
for token in token_iter:
if token == '(': # find top-level sections
section = ... |
def _flatten_subsection(subsection, _type, offset, parent):
'''Flatten a subsection from its nested version
Args:
subsection: Nested subsection as produced by _parse_section, except one level in
_type: type of section, ie: AXON, etc
parent: first element has this as it's parent
... |
def _extract_section(section):
'''Find top level sections, and get their flat contents, and append them all
Returns a numpy array with the row format:
[X, Y, Z, R, TYPE, ID, PARENT_ID]
Note: PARENT_ID starts at -1 for soma and 0 for neurites
'''
# sections with only one element will be ski... |
def _sections_to_raw_data(sections):
'''convert list of sections into the `raw_data` format used in neurom
This finds the soma, and attaches the neurites
'''
soma = None
neurites = []
for section in sections:
neurite = _extract_section(section)
if neurite is None:
co... |
def read(morph_file, data_wrapper=DataWrapper):
'''return a 'raw_data' np.array with the full neuron, and the format of the file
suitable to be wrapped by DataWrapper
'''
msg = ('This is an experimental reader. '
'There are no guarantees regarding ability to parse '
'Neurolucida .... |
def stats(data):
'''Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data
'''
return {'len': len(data),
'mean': np.mean(data),
'sum': np.sum(data),
'std': np.std(data),
... |
def get_config(config, default_config):
'''Load configuration from file if in config, else use default'''
if not config:
logging.warning('Using default config: %s', default_config)
config = default_config
try:
with open(config, 'r') as config_file:
return yaml.load(confi... |
def soma_surface_area(nrn, neurite_type=NeuriteType.soma):
'''Get the surface area of a neuron's soma.
Note:
The surface area is calculated by assuming the soma is spherical.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be soma'
return 4 * math.pi * nrn.soma.radius ** 2 |
def soma_surface_areas(nrn_pop, neurite_type=NeuriteType.soma):
'''Get the surface areas of the somata in a population of neurons
Note:
The surface area is calculated by assuming the soma is spherical.
Note:
If a single neuron is passed, a single element list with the surface
area o... |
def soma_radii(nrn_pop, neurite_type=NeuriteType.soma):
''' Get the radii of the somata of a population of neurons
Note:
If a single neuron is passed, a single element list with the
radius of its soma member is returned.
'''
assert neurite_type == NeuriteType.soma, 'Neurite type must be... |
def trunk_section_lengths(nrn, neurite_type=NeuriteType.all):
'''list of lengths of trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [morphmath.section_length(s.root_node.points)
for s in nrn.neurites if neurite_filter(s)] |
def trunk_origin_radii(nrn, neurite_type=NeuriteType.all):
'''radii of the trunk sections of neurites in a neuron'''
neurite_filter = is_type(neurite_type)
return [s.root_node.points[0][COLS.R] for s in nrn.neurites if neurite_filter(s)] |
def trunk_origin_azimuths(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin azimuths of a neuron or population
The azimuth is defined as Angle between x-axis and the vector
defined by (initial tree point - soma center) on the x-z plane.
The range of the azimuth angle [-pi, pi] ... |
def trunk_origin_elevations(nrn, neurite_type=NeuriteType.all):
'''Get a list of all the trunk origin elevations of a neuron or population
The elevation is defined as the angle between x-axis and the
vector defined by (initial tree point - soma center)
on the x-y half-plane.
The range of the eleva... |
def trunk_vectors(nrn, neurite_type=NeuriteType.all):
'''Calculates the vectors between all the trunks of the neuron
and the soma center.
'''
neurite_filter = is_type(neurite_type)
nrns = neuron_population(nrn)
return np.array([morphmath.vector(s.root_node.points[0], n.soma.center)
... |
def trunk_angles(nrn, neurite_type=NeuriteType.all):
'''Calculates the angles between all the trunks of the neuron.
The angles are defined on the x-y plane and the trees
are sorted from the y axis and anticlock-wise.
'''
vectors = trunk_vectors(nrn, neurite_type=neurite_type)
# In order to avoid... |
def sholl_crossings(neurites, center, radii):
'''calculate crossings of neurites
Args:
nrn(morph): morphology on which to perform Sholl analysis
radii(iterable of floats): radii for which crossings will be counted
Returns:
Array of same length as radii, with a count of the number o... |
def sholl_frequency(nrn, neurite_type=NeuriteType.all, step_size=10):
'''perform Sholl frequency calculations on a population of neurites
Args:
nrn(morph): nrn or population
neurite_type(NeuriteType): which neurites to operate on
step_size(float): step size between Sholl radii
Note... |
def dist_points(bin_edges, d):
"""Return an array of values according to a distribution
Points are calculated at the center of each bin
"""
bc = bin_centers(bin_edges)
if d is not None:
d = DISTS[d['type']](d, bc)
return d, bc |
def calc_limits(data, dist=None, padding=0.25):
"""Calculate a suitable range for a histogram
Returns:
tuple of (min, max)
"""
dmin = sys.float_info.max if dist is None else dist.get('min',
sys.float_info.max)
dmax = sys.float_info... |
def load_neurite_features(filepath):
'''Unpack relevant data into megadict'''
stuff = defaultdict(lambda: defaultdict(list))
nrns = nm.load_neurons(filepath)
# unpack data into arrays
for nrn in nrns:
for t in NEURITES_:
for feat in FEATURES:
stuff[feat][str(t).sp... |
def parse_args():
'''Parse command line arguments'''
parser = argparse.ArgumentParser(
description='Morphology feature plotter',
epilog='Note: Makes plots of various features and superimposes\
input distributions. Plots are saved to PDF file.',
formatter_class=argparse.ArgumentDe... |
def main(data_dir, mtype_file): # pylint: disable=too-many-locals
'''Run the stuff'''
# data structure to store results
stuff = load_neurite_features(data_dir)
sim_params = json.load(open(mtype_file))
# load histograms, distribution parameter sets and figures into arrays.
# To plot figures, do... |
def extract_density(population, plane='xy', bins=100, neurite_type=NeuriteType.basal_dendrite):
'''Extracts the 2d histogram of the center
coordinates of segments in the selected plane.
'''
segment_midpoints = get_feat('segment_midpoints', population, neurite_type=neurite_type)
horiz = segment_mi... |
def plot_density(population, # pylint: disable=too-many-arguments, too-many-locals
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.01,
n... |
def plot_neuron_on_density(population, # pylint: disable=too-many-arguments
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.... |
def bounding_box(obj):
'''Get the (x, y, z) bounding box of an object containing points
Returns:
2D numpy array of [[min_x, min_y, min_z], [max_x, max_y, max_z]]
'''
return np.array([np.min(obj.points[:, 0:3], axis=0),
np.max(obj.points[:, 0:3], axis=0)]) |
def is_monotonic(neurite, tol):
'''Check if neurite tree is monotonic
If each child has smaller or equal diameters from its parent
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
Returns:
True if neurite monotonic
'''
for node in neurite.iter_secti... |
def is_flat(neurite, tol, method='tolerance'):
'''Check if neurite is flat using the given method
Args:
neurite(Neurite): neurite to operate on
tol(float): tolerance
method(string): the method of flatness estimation:
'tolerance' returns true if any extent of the tree is smal... |
def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite... |
def get_flat_neurites(neuron, tol=0.1, method='ratio'):
'''Check if a neuron has neurites that are flat within a tolerance
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
method(string): 'tolerance' or 'ratio' described in :meth:`is_flat`
Return... |
def get_nonmonotonic_neurites(neuron, tol=1e-6):
'''Get neurites that are not monotonic
Args:
neurite(Neurite): neurite to operate on
tol(float): the tolerance or the ratio
Returns:
list of neurites that do not satisfy monotonicity test
'''
return [n for n in neuron.neurite... |
def segment_centre_of_mass(seg):
'''Calculate and return centre of mass of a segment.
C, seg_volalculated as centre of mass of conical frustum'''
h = mm.segment_length(seg)
r0 = seg[0][COLS.R]
r1 = seg[1][COLS.R]
num = r0 * r0 + 2 * r0 * r1 + 3 * r1 * r1
denom = 4 * (r0 * r0 + r0 * r1 + r1 ... |
def neurite_centre_of_mass(neurite):
'''Calculate and return centre of mass of a neurite.'''
centre_of_mass = np.zeros(3)
total_volume = 0
seg_vol = np.array(map(mm.segment_volume, nm.iter_segments(neurite)))
seg_centre_of_mass = np.array(map(segment_centre_of_mass, nm.iter_segments(neurite)))
... |
def distance_sqr(point, seg):
'''Calculate and return square Euclidian distance from given point to
centre of mass of given segment.'''
centre_of_mass = segment_centre_of_mass(seg)
return sum(pow(np.subtract(point, centre_of_mass), 2)) |
def radius_of_gyration(neurite):
'''Calculate and return radius of gyration of a given neurite.'''
centre_mass = neurite_centre_of_mass(neurite)
sum_sqr_distance = 0
N = 0
dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
sum_sqr_distance = np.sum(dist_sqr)
N = len... |
def view(input_file, plane, backend):
'''A simple neuron viewer'''
if backend == 'matplotlib':
from neurom.viewer import draw
kwargs = {
'mode': '3d' if plane == '3d' else '2d',
}
if plane != '3d':
kwargs['plane'] = plane
draw(load_neuron(input_fil... |
def generate_annotation(result, settings):
'''Generate the annotation for a given checker
Arguments
neuron(Neuron): The neuron object
checker: A tuple where the first item is the checking function (usually from neuron_checks)
and the second item is a dictionary of settings for ... |
def annotate(results, settings):
'''Concatenate the annotations of all checkers'''
annotations = (generate_annotation(result, setting)
for result, setting in zip(results, settings))
return '\n'.join(annot for annot in annotations if annot) |
def as_point(row):
'''Create a Point from a data block row'''
return Point(row[COLS.X], row[COLS.Y], row[COLS.Z],
row[COLS.R], int(row[COLS.TYPE])) |
def create_superuser(self, email, password, **extra_fields):
"""Save new User with is_staff and is_superuser set to True"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('S... |
def load_file_contents(file_path, as_list=True):
"""Load file as string or list"""
abs_file_path = join(HERE, file_path)
with open(abs_file_path, encoding='utf-8') as file_pointer:
if as_list:
return file_pointer.read().splitlines()
return file_pointer.read() |
def clean_password2(self):
"""
Check wether password 1 and password 2 are equivalent
While ideally this would be done in clean, there is a chance a
superclass could declare clean and forget to call super. We
therefore opt to run this password mismatch check in password2
... |
def _post_clean(self):
"""Run password validaton after clean methods
When clean methods are run, the user instance does not yet
exist. To properly compare model values agains the password (in
the UserAttributeSimilarityValidator), we wait until we have an
instance to compare ag... |
def clean(self):
"""Override default clean method to normalize email.
Call :code:`super().clean()` if overriding.
"""
super().clean()
self.email = self.__class__.objects.normalize_email(self.email) |
def subprocess_func(func, pipe, logger, mem_in_mb, cpu_time_limit_in_s, wall_time_limit_in_s, num_procs, grace_period_in_s, tmp_dir, *args, **kwargs):
# simple signal handler to catch the signals for time limits
def handler(signum, frame):
# logs message with level debug on this logger
logger.debug("signal hand... |
def normalize_feature_inputs(ctx, param, value):
"""Click callback that normalizes feature input values.
Returns a generator over features from the input value.
Parameters
----------
ctx: a Click context
param: the name of the argument or option
value: object
The value argument may... |
def iter_features(geojsonfile, func=None):
"""Extract GeoJSON features from a text file object.
Given a file-like object containing a single GeoJSON feature
collection text or a sequence of GeoJSON features, iter_features()
iterates over lines of the file and yields GeoJSON features.
Parameters
... |
def iter_query(query):
"""Accept a filename, stream, or string.
Returns an iterator over lines of the query."""
try:
itr = click.open_file(query).readlines()
except IOError:
itr = [query]
return itr |
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
query = query.replace(',', ' ')
vals = query.split()
coords = [float(v) for v in vals]
return tuple(coords[:2]) |
def normalize_feature_objects(feature_objs):
"""Takes an iterable of GeoJSON-like Feature mappings or
an iterable of objects with a geo interface and
normalizes it to the former."""
for obj in feature_objs:
if hasattr(obj, "__geo_interface__") and \
'type' in obj.__geo_interface__.key... |
async def api(self, endpoint, params=None, test=False):
"""Comunicate with the API."""
data = {}
url = "{}/{}".format(self._api, endpoint)
try:
async with async_timeout.timeout(8, loop=self._loop):
response = await self._session.get(
url, a... |
async def get_device_info(self, custom_attributes=None):
"""Get the local installed version."""
await self.get_geofences()
await self.get_devices()
await self.get_positions()
devinfo = {}
try: # pylint: disable=too-many-nested-blocks
for dev in self._devices ... |
async def get_geofences(self):
"""Get the local installed version."""
data = await self.api("geofences")
if self.connected and self.authenticated:
for geofence in data or []:
self._geofences[geofence["id"]] = geofence["name"]
else:
self._geofences ... |
async def get_devices(self):
"""Get the local installed version."""
data = await self.api("devices")
if self.connected and self.authenticated:
self._devices = data
else:
self._devices = self._devices
_LOGGER.debug(self._devices) |
async def get_positions(self):
"""Get the local installed version."""
data = await self.api("positions")
if self.connected and self.authenticated:
self._positions = data
else:
self._positions = self._positions
_LOGGER.debug(self._positions) |
async def get_events(
self, device_ids, group_ids=None, from_time=None, to_time=None, event_types=None
):
"""Get the local installed version."""
if to_time is None:
to_time = datetime.utcnow()
if from_time is None:
from_time = to_time - timedelta(seconds=EVENT... |
async def runcli():
"""Debug of pytraccar."""
async with aiohttp.ClientSession() as session:
host = input("IP: ")
username = input("Username: ")
password = input("Password: ")
print("\n\n\n")
data = API(LOOP, session, username, password, host)
await data.test_conn... |
def scramble_string(s, key):
"""
s is the puzzle's solution in column-major order, omitting black squares:
i.e. if the puzzle is:
C A T
# # A
# # R
solution is CATAR
Key is a 4-digit number in the range 1000 <= key <= 9999
"""
key = key_digits(key)
for k in key... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.