text
stringlengths 3
1.05M
|
|---|
import React from "react";
import * as FaIcons from "react-icons/fa";
import * as AiIcons from "react-icons/ai";
import { sidebarContext } from "./helpers";
export class ToggleSidebarOpen extends React.Component {
render() {
return (
<sidebarContext.Consumer>
{({ sidebar, setSidebarValue }) => (
<AiIcons.AiOutlineClose
onClick={() => setSidebarValue("6rem")}
style={{
width: "100%",
height: "2rem",
borderRadius: "0px",
backgroundColor: "#8B8B8B",
paddingTop: "1rem",
paddingBottom: "1rem",
fontSize: 18,
color: "#FFF4E3",
"&:hover": {
backgroundColor: "#FFF4E3",
color: "#8B8B8B",
},
}}
/>
)}
</sidebarContext.Consumer>
);
}
}
export class ToggleSidebarCancel extends React.Component {
render() {
return (
<sidebarContext.Consumer>
{({ sidebar, setSidebarValue }) => (
<FaIcons.FaBars
onClick={() => setSidebarValue("18rem")}
style={{
width: "100%",
height: "2rem",
borderRadius: "0px",
paddingTop: "1rem",
paddingBottom: "1rem",
backgroundColor: "#FFF4E3",
fontSize: 18,
color: "#8B8B8B",
"&:hover": {
backgroundColor: "#8B8B8B",
color: "#FFF4E3",
},
}}
/>
)}
</sidebarContext.Consumer>
);
}
}
|
#!/usr/bin/env python
"""
Support functions for uframe/component version information.
"""
__author__ = 'Edna Donoughe'
from flask import (jsonify, current_app)
from ooiservices.app.uframe import uframe as api
from ooiservices.app.main.errors import bad_request
from ooiservices.app.uframe.uframe_tools import (uframe_get_versions, uframe_get_component_version, uframe_get_versions_list)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Get uframe versions information.
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@api.route('/versions')
def uframe_versions():
try:
# Get a list of component dictionaries.
"""
[
{"component":"uFrame", "version": "v1.2.4", "release": "2017-08-14"},
{"component":"mi-instrument", "version": "v1.2.1", "release": "2017-04-24"}
]
"""
results = uframe_get_versions()
return jsonify({'versions': results}), 200
except Exception as err:
message = str(err)
current_app.logger.info(message)
return bad_request(message)
@api.route('/versions/<string:component>')
def uframe_versions_component(component=None):
"""
Get version information for a specific component.
"""
try:
# Get a specific component from list of uframe version component dictionaries.
result = uframe_get_versions(component=component)
# To just return the uframe component information.
if result and result is not None:
if 'component' in result:
if result['component'] == component:
return jsonify({'component_versions': result}), 200
else:
message = 'Null or empty result returned from uframe for version of component: %s. ' % component
message += 'Please verify the component name provided is a valid component name.'
raise Exception(message)
return jsonify({'result': result}), 200
except Exception as err:
message = str(err)
current_app.logger.info(message)
return bad_request(message)
@api.route('/versions/<string:component>/release_notes')
def uframe_versions_component_release_notes(component=None):
"""
Get release notes information for a specific component; descending version values.
http://uframe-test.intra.oceanobservatories.org:12590/versions/uFrame/1.2.7
Request: http://localhost:4000/uframe/versions/uFrame/release_notes
Response:
{
"release_notes": [
{
"component": "uFrame",
"notes": [
"Develop a strategy for separately deploying uFrame software on test systems. (12557)",
"Prevent creating/updating annotations where beginDT > endDT. (12509)",
"Add support for open-ended annotations. (11444)",
"Add virtual streams to stream and partition metadata on ingest. (12488)",
"Handle \"PD\" prefix in alert filter pdIds. (12172)",
"Enhance ingestion logging in EDEX. (12618)",
"Uncabled_ingest mode unable to start. (12581)",
"Gracefully handle error in Sensor Inventory Service TOC endpoint. (12546)",
"Fix DOI SQL Errors on uframe-test and production. (12580)",
"Add version endpoint. (12497)"
],
"release": "2017-09-00",
"version": "1.2.7"
},
{
"component": "uFrame",
"notes": [
"Expand ingest request types in EDEX to include cabled playback. (12530)",
"Handle comma separated values for param in data file ingestion. (12506)",
"Expose data purge through web service. (12485)",
"Drop FK constraint in new ingest engine. (12440)",
"Promote uncabled particle timestamps from long to double if needed. (12434)",
"Create ingestion tool for telemetered and recovered data. (12140)",
"Increase default max memory. (12455)",
"Add QcFlag Validation. (12461)",
"DOI cruise handling and asset management updates. (12443)"
],
"release": "2017-08-01",
"version": "1.2.6"
},
. . .
]
}
"""
results = []
try:
# Get a specific component from list of EDEX version component dictionaries.
versions_list = uframe_get_versions_list(component=component)
# To just return the uframe component information.
if not versions_list or versions_list is None:
message = 'No versions returned for component: %s. ' % component
message += 'Please verify the component name provided is a valid component name.'
raise Exception(message)
versions_list.sort(key=lambda s: map(int, s.split('.')), reverse=True)
for version in versions_list:
result = uframe_get_component_version(component, version)
if result and result is not None:
results.append(result)
return jsonify({'release_notes': results}), 200
except Exception as err:
message = str(err)
return bad_request(message)
|
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
import copy as cp
import numpy as np
from ..epochs import Epochs
from ..proj import compute_proj_evoked, compute_proj_epochs
from ..utils import logger, verbose, warn
from ..io.pick import pick_types
from ..io import make_eeg_average_ref_proj
from .ecg import find_ecg_events
from .eog import find_eog_events
def _safe_del_key(dict_, key):
"""Aux function.
Use this function when preparing rejection parameters
instead of directly deleting keys.
"""
if key in dict_:
del dict_[key]
def _compute_exg_proj(mode, raw, raw_event, tmin, tmax,
n_grad, n_mag, n_eeg, l_freq, h_freq,
average, filter_length, n_jobs, ch_name,
reject, flat, bads, avg_ref, no_proj, event_id,
exg_l_freq, exg_h_freq, tstart, qrs_threshold,
filter_method, iir_params, return_drop_log, copy,
meg, verbose):
"""Compute SSP/PCA projections for ECG or EOG artifacts."""
raw = raw.copy() if copy else raw
del copy
raw.load_data() # we will filter it later
if no_proj:
projs = []
else:
projs = cp.deepcopy(raw.info['projs'])
logger.info('Including %d SSP projectors from raw file'
% len(projs))
if avg_ref:
eeg_proj = make_eeg_average_ref_proj(raw.info)
projs.append(eeg_proj)
if raw_event is None:
raw_event = raw
assert mode in ('ECG', 'EOG') # internal function
logger.info('Running %s SSP computation' % mode)
if mode == 'ECG':
events, _, _ = find_ecg_events(raw_event, ch_name=ch_name,
event_id=event_id, l_freq=exg_l_freq,
h_freq=exg_h_freq, tstart=tstart,
qrs_threshold=qrs_threshold,
filter_length=filter_length)
else: # mode == 'EOG':
events = find_eog_events(raw_event, event_id=event_id,
l_freq=exg_l_freq, h_freq=exg_h_freq,
filter_length=filter_length, ch_name=ch_name,
tstart=tstart)
# Check to make sure we actually got at least one usable event
if events.shape[0] < 1:
warn(f'No {mode} events found')
return ([], events) + (([],) if return_drop_log else ())
logger.info('Computing projector')
my_info = cp.deepcopy(raw.info)
my_info['bads'] += bads
# Handler rejection parameters
if reject is not None: # make sure they didn't pass None
if len(pick_types(my_info, meg='grad', eeg=False, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(reject, 'grad')
if len(pick_types(my_info, meg='mag', eeg=False, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(reject, 'mag')
if len(pick_types(my_info, meg=False, eeg=True, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(reject, 'eeg')
if len(pick_types(my_info, meg=False, eeg=False, eog=True,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(reject, 'eog')
if flat is not None: # make sure they didn't pass None
if len(pick_types(my_info, meg='grad', eeg=False, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(flat, 'grad')
if len(pick_types(my_info, meg='mag', eeg=False, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(flat, 'mag')
if len(pick_types(my_info, meg=False, eeg=True, eog=False,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(flat, 'eeg')
if len(pick_types(my_info, meg=False, eeg=False, eog=True,
ref_meg=False, exclude='bads')) == 0:
_safe_del_key(flat, 'eog')
# exclude bad channels from projection
# keep reference channels if compensation channels are present
ref_meg = len(my_info['comps']) > 0
picks = pick_types(my_info, meg=True, eeg=True, eog=True, ecg=True,
ref_meg=ref_meg, exclude='bads')
raw.filter(l_freq, h_freq, picks=picks, filter_length=filter_length,
n_jobs=n_jobs, method=filter_method, iir_params=iir_params,
l_trans_bandwidth=0.5, h_trans_bandwidth=0.5,
phase='zero-double', fir_design='firwin2')
epochs = Epochs(raw, events, None, tmin, tmax, baseline=None, preload=True,
picks=picks, reject=reject, flat=flat, proj=True)
drop_log = epochs.drop_log
if epochs.events.shape[0] < 1:
warn('No good epochs found')
return ([], events) + ((drop_log,) if return_drop_log else ())
if average:
evoked = epochs.average()
ev_projs = compute_proj_evoked(evoked, n_grad=n_grad, n_mag=n_mag,
n_eeg=n_eeg, meg=meg)
else:
ev_projs = compute_proj_epochs(epochs, n_grad=n_grad, n_mag=n_mag,
n_eeg=n_eeg, n_jobs=n_jobs, meg=meg)
for p in ev_projs:
p['desc'] = mode + "-" + p['desc']
projs.extend(ev_projs)
logger.info('Done.')
return (projs, events) + ((drop_log,) if return_drop_log else ())
@verbose
def compute_proj_ecg(raw, raw_event=None, tmin=-0.2, tmax=0.4,
n_grad=2, n_mag=2, n_eeg=2, l_freq=1.0, h_freq=35.0,
average=True, filter_length='10s', n_jobs=1,
ch_name=None, reject=dict(grad=2000e-13, mag=3000e-15,
eeg=50e-6, eog=250e-6),
flat=None, bads=[], avg_ref=False,
no_proj=False, event_id=999, ecg_l_freq=5, ecg_h_freq=35,
tstart=0., qrs_threshold='auto', filter_method='fir',
iir_params=None, copy=True, return_drop_log=False,
meg='separate', verbose=None):
"""Compute SSP (signal-space projection) vectors for ECG artifacts.
%(compute_proj_ecg)s
.. note:: Raw data will be loaded if it hasn't been preloaded already.
Parameters
----------
raw : mne.io.Raw
Raw input file.
raw_event : mne.io.Raw or None
Raw file to use for event detection (if None, raw is used).
tmin : float
Time before event in seconds.
tmax : float
Time after event in seconds.
n_grad : int
Number of SSP vectors for gradiometers.
n_mag : int
Number of SSP vectors for magnetometers.
n_eeg : int
Number of SSP vectors for EEG.
l_freq : float | None
Filter low cut-off frequency for the data channels in Hz.
h_freq : float | None
Filter high cut-off frequency for the data channels in Hz.
average : bool
Compute SSP after averaging. Default is True.
filter_length : str | int | None
Number of taps to use for filtering.
%(n_jobs)s
ch_name : str | None
Channel to use for ECG detection (Required if no ECG found).
reject : dict | None
Epoch rejection configuration (see Epochs).
flat : dict | None
Epoch flat configuration (see Epochs).
bads : list
List with (additional) bad channels.
avg_ref : bool
Add EEG average reference proj.
no_proj : bool
Exclude the SSP projectors currently in the fiff file.
event_id : int
ID to use for events.
ecg_l_freq : float
Low pass frequency applied to the ECG channel for event detection.
ecg_h_freq : float
High pass frequency applied to the ECG channel for event detection.
tstart : float
Start artifact detection after tstart seconds.
qrs_threshold : float | str
Between 0 and 1. qrs detection threshold. Can also be "auto" to
automatically choose the threshold that generates a reasonable
number of heartbeats (40-160 beats / min).
filter_method : str
Method for filtering ('iir' or 'fir').
iir_params : dict | None
Dictionary of parameters to use for IIR filtering.
See mne.filter.construct_iir_filter for details. If iir_params
is None and method="iir", 4th order Butterworth will be used.
copy : bool
If False, filtering raw data is done in place. Defaults to True.
return_drop_log : bool
If True, return the drop log.
.. versionadded:: 0.15
meg : str
Can be 'separate' (default) or 'combined' to compute projectors
for magnetometers and gradiometers separately or jointly.
If 'combined', ``n_mag == n_grad`` is required and the number of
projectors computed for MEG will be ``n_mag``.
.. versionadded:: 0.18
%(verbose)s
Returns
-------
proj : list
Computed SSP projectors.
ecg_events : ndarray
Detected ECG events.
drop_log : list
The drop log, if requested.
See Also
--------
find_ecg_events
create_ecg_epochs
Notes
-----
Filtering is applied to the ECG channel while finding events using
``ecg_l_freq`` and ``ecg_h_freq``, and then to the ``raw`` instance
using ``l_freq`` and ``h_freq`` before creation of the epochs used to
create the projectors.
"""
return _compute_exg_proj(
'ECG', raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg,
l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, flat,
bads, avg_ref, no_proj, event_id, ecg_l_freq, ecg_h_freq, tstart,
qrs_threshold, filter_method, iir_params, return_drop_log, copy,
meg, verbose)
@verbose
def compute_proj_eog(raw, raw_event=None, tmin=-0.2, tmax=0.2,
n_grad=2, n_mag=2, n_eeg=2, l_freq=1.0, h_freq=35.0,
average=True, filter_length='10s', n_jobs=1,
reject=dict(grad=2000e-13, mag=3000e-15, eeg=500e-6,
eog=np.inf), flat=None, bads=[],
avg_ref=False, no_proj=False, event_id=998, eog_l_freq=1,
eog_h_freq=10, tstart=0., filter_method='fir',
iir_params=None, ch_name=None, copy=True,
return_drop_log=False, meg='separate', verbose=None):
"""Compute SSP (signal-space projection) vectors for EOG artifacts.
%(compute_proj_eog)s
.. note:: Raw data must be preloaded.
Parameters
----------
raw : mne.io.Raw
Raw input file.
raw_event : mne.io.Raw or None
Raw file to use for event detection (if None, raw is used).
tmin : float
Time before event in seconds.
tmax : float
Time after event in seconds.
n_grad : int
Number of SSP vectors for gradiometers.
n_mag : int
Number of SSP vectors for magnetometers.
n_eeg : int
Number of SSP vectors for EEG.
l_freq : float | None
Filter low cut-off frequency for the data channels in Hz.
h_freq : float | None
Filter high cut-off frequency for the data channels in Hz.
average : bool
Compute SSP after averaging. Default is True.
filter_length : str | int | None
Number of taps to use for filtering.
%(n_jobs)s
reject : dict | None
Epoch rejection configuration (see Epochs).
flat : dict | None
Epoch flat configuration (see Epochs).
bads : list
List with (additional) bad channels.
avg_ref : bool
Add EEG average reference proj.
no_proj : bool
Exclude the SSP projectors currently in the fiff file.
event_id : int
ID to use for events.
eog_l_freq : float
Low pass frequency applied to the E0G channel for event detection.
eog_h_freq : float
High pass frequency applied to the EOG channel for event detection.
tstart : float
Start artifact detection after tstart seconds.
filter_method : str
Method for filtering ('iir' or 'fir').
iir_params : dict | None
Dictionary of parameters to use for IIR filtering.
See mne.filter.construct_iir_filter for details. If iir_params
is None and method="iir", 4th order Butterworth will be used.
ch_name : str | None
If not None, specify EOG channel name.
copy : bool
If False, filtering raw data is done in place. Defaults to True.
return_drop_log : bool
If True, return the drop log.
.. versionadded:: 0.15
meg : str
Can be 'separate' (default) or 'combined' to compute projectors
for magnetometers and gradiometers separately or jointly.
If 'combined', ``n_mag == n_grad`` is required and the number of
projectors computed for MEG will be ``n_mag``.
.. versionadded:: 0.18
%(verbose)s
Returns
-------
proj: list
Computed SSP projectors.
eog_events: ndarray
Detected EOG events.
drop_log : list
The drop log, if requested.
See Also
--------
find_eog_events
create_eog_epochs
Notes
-----
Filtering is applied to the EOG channel while finding events using
``eog_l_freq`` and ``eog_h_freq``, and then to the ``raw`` instance
using ``l_freq`` and ``h_freq`` before creation of the epochs used to
create the projectors.
"""
return _compute_exg_proj(
'EOG', raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg,
l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, flat,
bads, avg_ref, no_proj, event_id, eog_l_freq, eog_h_freq, tstart,
'auto', filter_method, iir_params, return_drop_log, copy, meg,
verbose)
|
import { matcherHint, printReceived } from 'jest-matcher-utils';
import predicate from './predicate';
const passMessage = received => () =>
matcherHint('.not.toBeArray', 'received', '') +
'\n\n' +
'Expected value to not be an array received:\n' +
` ${printReceived(received)}`;
const failMessage = received => () =>
matcherHint('.toBeArray', 'received', '') +
'\n\n' +
'Expected value to be an array received:\n' +
` ${printReceived(received)}`;
export function toBeArray(expected) {
const pass = predicate(expected);
if (pass) {
return { pass: true, message: passMessage(expected) };
}
return { pass: false, message: failMessage(expected) };
}
|
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class CreatePublicZoneResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'id': 'str',
'name': 'str',
'description': 'str',
'email': 'str',
'zone_type': 'str',
'ttl': 'int',
'serial': 'int',
'status': 'str',
'record_num': 'int',
'pool_id': 'str',
'project_id': 'str',
'created_at': 'str',
'updated_at': 'str',
'links': 'PageLink',
'enterprise_project_id': 'str',
'masters': 'list[str]'
}
attribute_map = {
'id': 'id',
'name': 'name',
'description': 'description',
'email': 'email',
'zone_type': 'zone_type',
'ttl': 'ttl',
'serial': 'serial',
'status': 'status',
'record_num': 'record_num',
'pool_id': 'pool_id',
'project_id': 'project_id',
'created_at': 'created_at',
'updated_at': 'updated_at',
'links': 'links',
'enterprise_project_id': 'enterprise_project_id',
'masters': 'masters'
}
def __init__(self, id=None, name=None, description=None, email=None, zone_type=None, ttl=None, serial=None, status=None, record_num=None, pool_id=None, project_id=None, created_at=None, updated_at=None, links=None, enterprise_project_id=None, masters=None):
"""CreatePublicZoneResponse - a model defined in huaweicloud sdk"""
super().__init__()
self._id = None
self._name = None
self._description = None
self._email = None
self._zone_type = None
self._ttl = None
self._serial = None
self._status = None
self._record_num = None
self._pool_id = None
self._project_id = None
self._created_at = None
self._updated_at = None
self._links = None
self._enterprise_project_id = None
self._masters = None
self.discriminator = None
if id is not None:
self.id = id
if name is not None:
self.name = name
if description is not None:
self.description = description
if email is not None:
self.email = email
if zone_type is not None:
self.zone_type = zone_type
if ttl is not None:
self.ttl = ttl
if serial is not None:
self.serial = serial
if status is not None:
self.status = status
if record_num is not None:
self.record_num = record_num
if pool_id is not None:
self.pool_id = pool_id
if project_id is not None:
self.project_id = project_id
if created_at is not None:
self.created_at = created_at
if updated_at is not None:
self.updated_at = updated_at
if links is not None:
self.links = links
if enterprise_project_id is not None:
self.enterprise_project_id = enterprise_project_id
if masters is not None:
self.masters = masters
@property
def id(self):
"""Gets the id of this CreatePublicZoneResponse.
zone的ID,uuid形式的一个资源标识。
:return: The id of this CreatePublicZoneResponse.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this CreatePublicZoneResponse.
zone的ID,uuid形式的一个资源标识。
:param id: The id of this CreatePublicZoneResponse.
:type: str
"""
self._id = id
@property
def name(self):
"""Gets the name of this CreatePublicZoneResponse.
zone名称。
:return: The name of this CreatePublicZoneResponse.
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this CreatePublicZoneResponse.
zone名称。
:param name: The name of this CreatePublicZoneResponse.
:type: str
"""
self._name = name
@property
def description(self):
"""Gets the description of this CreatePublicZoneResponse.
对zone的描述信息。
:return: The description of this CreatePublicZoneResponse.
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this CreatePublicZoneResponse.
对zone的描述信息。
:param description: The description of this CreatePublicZoneResponse.
:type: str
"""
self._description = description
@property
def email(self):
"""Gets the email of this CreatePublicZoneResponse.
管理该zone的管理员邮箱。
:return: The email of this CreatePublicZoneResponse.
:rtype: str
"""
return self._email
@email.setter
def email(self, email):
"""Sets the email of this CreatePublicZoneResponse.
管理该zone的管理员邮箱。
:param email: The email of this CreatePublicZoneResponse.
:type: str
"""
self._email = email
@property
def zone_type(self):
"""Gets the zone_type of this CreatePublicZoneResponse.
zone类型,公网(public)。
:return: The zone_type of this CreatePublicZoneResponse.
:rtype: str
"""
return self._zone_type
@zone_type.setter
def zone_type(self, zone_type):
"""Sets the zone_type of this CreatePublicZoneResponse.
zone类型,公网(public)。
:param zone_type: The zone_type of this CreatePublicZoneResponse.
:type: str
"""
self._zone_type = zone_type
@property
def ttl(self):
"""Gets the ttl of this CreatePublicZoneResponse.
该zone下SOA记录中的ttl值。
:return: The ttl of this CreatePublicZoneResponse.
:rtype: int
"""
return self._ttl
@ttl.setter
def ttl(self, ttl):
"""Sets the ttl of this CreatePublicZoneResponse.
该zone下SOA记录中的ttl值。
:param ttl: The ttl of this CreatePublicZoneResponse.
:type: int
"""
self._ttl = ttl
@property
def serial(self):
"""Gets the serial of this CreatePublicZoneResponse.
该zone下SOA记录中用于标识zone文件变更的序列值,用于主从节点同步。
:return: The serial of this CreatePublicZoneResponse.
:rtype: int
"""
return self._serial
@serial.setter
def serial(self, serial):
"""Sets the serial of this CreatePublicZoneResponse.
该zone下SOA记录中用于标识zone文件变更的序列值,用于主从节点同步。
:param serial: The serial of this CreatePublicZoneResponse.
:type: int
"""
self._serial = serial
@property
def status(self):
"""Gets the status of this CreatePublicZoneResponse.
资源状态。
:return: The status of this CreatePublicZoneResponse.
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this CreatePublicZoneResponse.
资源状态。
:param status: The status of this CreatePublicZoneResponse.
:type: str
"""
self._status = status
@property
def record_num(self):
"""Gets the record_num of this CreatePublicZoneResponse.
该zone下的recordset个数。
:return: The record_num of this CreatePublicZoneResponse.
:rtype: int
"""
return self._record_num
@record_num.setter
def record_num(self, record_num):
"""Sets the record_num of this CreatePublicZoneResponse.
该zone下的recordset个数。
:param record_num: The record_num of this CreatePublicZoneResponse.
:type: int
"""
self._record_num = record_num
@property
def pool_id(self):
"""Gets the pool_id of this CreatePublicZoneResponse.
托管该zone的pool,由系统分配。
:return: The pool_id of this CreatePublicZoneResponse.
:rtype: str
"""
return self._pool_id
@pool_id.setter
def pool_id(self, pool_id):
"""Sets the pool_id of this CreatePublicZoneResponse.
托管该zone的pool,由系统分配。
:param pool_id: The pool_id of this CreatePublicZoneResponse.
:type: str
"""
self._pool_id = pool_id
@property
def project_id(self):
"""Gets the project_id of this CreatePublicZoneResponse.
zone所属的项目ID。
:return: The project_id of this CreatePublicZoneResponse.
:rtype: str
"""
return self._project_id
@project_id.setter
def project_id(self, project_id):
"""Sets the project_id of this CreatePublicZoneResponse.
zone所属的项目ID。
:param project_id: The project_id of this CreatePublicZoneResponse.
:type: str
"""
self._project_id = project_id
@property
def created_at(self):
"""Gets the created_at of this CreatePublicZoneResponse.
创建时间。 采用UTC时间格式,格式为:YYYY-MM-DDTHH:MM:SSZ
:return: The created_at of this CreatePublicZoneResponse.
:rtype: str
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""Sets the created_at of this CreatePublicZoneResponse.
创建时间。 采用UTC时间格式,格式为:YYYY-MM-DDTHH:MM:SSZ
:param created_at: The created_at of this CreatePublicZoneResponse.
:type: str
"""
self._created_at = created_at
@property
def updated_at(self):
"""Gets the updated_at of this CreatePublicZoneResponse.
更新时间。 采用UTC时间格式,格式为:YYYY-MM-DDTHH:MM:SSZ
:return: The updated_at of this CreatePublicZoneResponse.
:rtype: str
"""
return self._updated_at
@updated_at.setter
def updated_at(self, updated_at):
"""Sets the updated_at of this CreatePublicZoneResponse.
更新时间。 采用UTC时间格式,格式为:YYYY-MM-DDTHH:MM:SSZ
:param updated_at: The updated_at of this CreatePublicZoneResponse.
:type: str
"""
self._updated_at = updated_at
@property
def links(self):
"""Gets the links of this CreatePublicZoneResponse.
:return: The links of this CreatePublicZoneResponse.
:rtype: PageLink
"""
return self._links
@links.setter
def links(self, links):
"""Sets the links of this CreatePublicZoneResponse.
:param links: The links of this CreatePublicZoneResponse.
:type: PageLink
"""
self._links = links
@property
def enterprise_project_id(self):
"""Gets the enterprise_project_id of this CreatePublicZoneResponse.
域名关联的企业项目ID,长度不超过36个字符。
:return: The enterprise_project_id of this CreatePublicZoneResponse.
:rtype: str
"""
return self._enterprise_project_id
@enterprise_project_id.setter
def enterprise_project_id(self, enterprise_project_id):
"""Sets the enterprise_project_id of this CreatePublicZoneResponse.
域名关联的企业项目ID,长度不超过36个字符。
:param enterprise_project_id: The enterprise_project_id of this CreatePublicZoneResponse.
:type: str
"""
self._enterprise_project_id = enterprise_project_id
@property
def masters(self):
"""Gets the masters of this CreatePublicZoneResponse.
主从模式中,从DNS服务器用以获取DNS信息。 目前暂未使用。
:return: The masters of this CreatePublicZoneResponse.
:rtype: list[str]
"""
return self._masters
@masters.setter
def masters(self, masters):
"""Sets the masters of this CreatePublicZoneResponse.
主从模式中,从DNS服务器用以获取DNS信息。 目前暂未使用。
:param masters: The masters of this CreatePublicZoneResponse.
:type: list[str]
"""
self._masters = masters
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CreatePublicZoneResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
# Generated by Django 3.1.3 on 2020-12-07 23:09
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django_update_from_dict
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0003_auto_20201206_1634'),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=255)),
('organized_by', models.CharField(max_length=255)),
('venue_name', models.CharField(max_length=255)),
('description', models.TextField()),
('capacity', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)])),
('start_date_time', models.DateTimeField()),
('end_date_time', models.DateTimeField()),
('image_url', models.URLField()),
('image_id', models.CharField(max_length=100)),
('is_published', models.BooleanField()),
('is_sign_up_allowed', models.BooleanField()),
('is_sign_up_approval_required', models.BooleanField()),
('organizer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')),
],
options={
'ordering': ['-created_at'],
},
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.CreateModel(
name='EventCategoryType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.organization')),
],
options={
'ordering': ['name'],
},
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.CreateModel(
name='EventSignUp',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('status', models.CharField(choices=[('PENDING', 'Pending'), ('CONFIRMED', 'Confirmed'), ('ATTENDED', 'Attended')], default='PENDING', max_length=50)),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.event')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')),
],
options={
'ordering': ['-status', 'created_at'],
},
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.CreateModel(
name='EventCategoryTypeSubscription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.eventcategorytype')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='users.user')),
],
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.CreateModel(
name='EventCategory',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.eventcategorytype')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.event')),
],
bases=(django_update_from_dict.UpdateFromDictMixin, models.Model),
),
migrations.AddConstraint(
model_name='eventsignup',
constraint=models.UniqueConstraint(fields=('user_id', 'event_id'), name='unique_user_event_signup'),
),
migrations.AddConstraint(
model_name='eventcategorytypesubscription',
constraint=models.UniqueConstraint(fields=('category_id', 'user_id'), name='unique_user_event_category_type_subscription'),
),
migrations.AddConstraint(
model_name='eventcategorytype',
constraint=models.UniqueConstraint(fields=('name', 'organization_id'), name='unique_organization_event_category_type'),
),
migrations.AddConstraint(
model_name='eventcategory',
constraint=models.UniqueConstraint(fields=('category_id', 'event_id'), name='unique_event_category'),
),
]
|
engine.audio.buffer.impulse.small = (() => {
const context = engine.audio.context()
const sampleRate = context.sampleRate,
size = 1 * sampleRate
const buffer = context.createBuffer(1, size, sampleRate)
for (let n = 0; n < buffer.numberOfChannels; n += 1) {
const data = buffer.getChannelData(n)
for (let i = 0; i < size; i += 1) {
const factor = ((size - i) / size) ** 4
data[i] = factor * ((2 * Math.random()) - 1)
}
}
return () => buffer
})()
|
import { combineReducers } from "redux";
import podcasts from "./podcasts";
import snippets from "./snippets";
import user from "./user";
import ui from "./ui";
import collections from "./collections";
export default combineReducers({ podcasts, snippets, user, ui, collections });
|
import torch
from mmdet.core import bbox2roi
from ..builder import HEADS, build_head
from .standard_roi_head import StandardRoIHead
@HEADS.register_module()
class MaskScoringRoIHead(StandardRoIHead):
"""Mask Scoring RoIHead for Mask Scoring RCNN.
https://arxiv.org/abs/1903.00241
"""
def __init__(self, mask_iou_head, **kwargs):
assert mask_iou_head is not None
super(MaskScoringRoIHead, self).__init__(**kwargs)
self.mask_iou_head = build_head(mask_iou_head)
def init_weights(self, pretrained):
"""Initialize the weights in head.
Args:
pretrained (str, optional): Path to pre-trained weights.
Defaults to None.
"""
super(MaskScoringRoIHead, self).init_weights(pretrained)
self.mask_iou_head.init_weights()
def _mask_forward_train(self, x, sampling_results, bbox_feats, gt_masks,
img_metas):
"""Run forward function and calculate loss for Mask head in
training."""
pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])
mask_results = super(MaskScoringRoIHead,
self)._mask_forward_train(x, sampling_results,
bbox_feats, gt_masks,
img_metas)
if mask_results['loss_mask'] is None:
return mask_results
# mask iou head forward and loss
pos_mask_pred = mask_results['mask_pred'][
range(mask_results['mask_pred'].size(0)), pos_labels]
mask_iou_pred = self.mask_iou_head(mask_results['mask_feats'],
pos_mask_pred)
pos_mask_iou_pred = mask_iou_pred[range(mask_iou_pred.size(0)),
pos_labels]
mask_iou_targets = self.mask_iou_head.get_targets(
sampling_results, gt_masks, pos_mask_pred,
mask_results['mask_targets'], self.train_cfg)
loss_mask_iou = self.mask_iou_head.loss(pos_mask_iou_pred,
mask_iou_targets)
mask_results['loss_mask'].update(loss_mask_iou)
return mask_results
def simple_test_mask(self,
x,
img_metas,
det_bboxes,
det_labels,
rescale=False):
"""Obtain mask prediction without augmentation."""
# JPEGImages shapes of images in the batch
ori_shapes = tuple(meta['ori_shape'] for meta in img_metas)
scale_factors = tuple(meta['scale_factor'] for meta in img_metas)
num_imgs = len(det_bboxes)
if all(det_bbox.shape[0] == 0 for det_bbox in det_bboxes):
num_classes = self.mask_head.num_classes
segm_results = [[[] for _ in range(num_classes)]
for _ in range(num_imgs)]
mask_scores = [[[] for _ in range(num_classes)]
for _ in range(num_imgs)]
else:
# if det_bboxes is rescaled to the original JPEGImages size, we need to
# rescale it back to the testing scale to obtain RoIs.
if rescale and not isinstance(scale_factors[0], float):
scale_factors = [
torch.from_numpy(scale_factor).to(det_bboxes[0].device)
for scale_factor in scale_factors
]
_bboxes = [
det_bboxes[i][:, :4] *
scale_factors[i] if rescale else det_bboxes[i]
for i in range(num_imgs)
]
mask_rois = bbox2roi(_bboxes)
mask_results = self._mask_forward(x, mask_rois)
concat_det_labels = torch.cat(det_labels)
# get mask scores with mask iou head
mask_feats = mask_results['mask_feats']
mask_pred = mask_results['mask_pred']
mask_iou_pred = self.mask_iou_head(
mask_feats, mask_pred[range(concat_det_labels.size(0)),
concat_det_labels])
# split batch mask prediction back to each JPEGImages
num_bboxes_per_img = tuple(len(_bbox) for _bbox in _bboxes)
mask_preds = mask_pred.split(num_bboxes_per_img, 0)
mask_iou_preds = mask_iou_pred.split(num_bboxes_per_img, 0)
# apply mask post-processing to each JPEGImages individually
segm_results = []
mask_scores = []
for i in range(num_imgs):
if det_bboxes[i].shape[0] == 0:
segm_results.append(
[[] for _ in range(self.mask_head.num_classes)])
mask_scores.append(
[[] for _ in range(self.mask_head.num_classes)])
else:
segm_result = self.mask_head.get_seg_masks(
mask_preds[i], _bboxes[i], det_labels[i],
self.test_cfg, ori_shapes[i], scale_factors[i],
rescale)
# get mask scores with mask iou head
mask_score = self.mask_iou_head.get_mask_scores(
mask_iou_preds[i], det_bboxes[i], det_labels[i])
segm_results.append(segm_result)
mask_scores.append(mask_score)
return list(zip(segm_results, mask_scores))
|
#pragma once
#include <variant>
#include <optional>
#include <utility>
#include <vector>
#include <stdexcept>
#include <concepts/concepts.hpp>
//maybe rename
template<typename T>
struct ref_or_inplace {
//requires default_constructible<T>
ref_or_inplace() requires std::is_default_constructible_v<T> :m_data(std::in_place_type<T>){}
ref_or_inplace(T& t):
m_data(&t) { }
explicit ref_or_inplace(T* t) :
m_data(t) { }
ref_or_inplace(std::nullptr_t) = delete;
ref_or_inplace(T&& t) :
m_data(std::move(t)) { }
template<typename... Args>requires std::constructible_from<T,Args...>
explicit ref_or_inplace(Args&&... args):
m_data(std::in_place_type<T>,std::forward<Args>(args)...) {
}
T& value() {
if(std::holds_alternative<T>(m_data)) {
return std::get<T>(m_data);
}else if(std::holds_alternative<T*>(m_data)) {
return *std::get<T*>(m_data);
}else {
throw std::runtime_error(";-;");
}
}
const T& value() const{
if (std::holds_alternative<T>(m_data)) {
return std::get<T>(m_data);
}
else if (std::holds_alternative<T*>(m_data)) {
return *std::get<T*>(m_data);
}
else {
throw std::runtime_error(";-;");
}
}
private:
std::variant<T, T*> m_data;
};
|
from __future__ import unicode_literals
from frappe import _
import frappe
import unittest
class TestESoCApplicant(unittest.TestCase):
def validate(self):
frappe.throw(_("Test Exception"))
|
from __future__ import annotations
from typing import Type, TypeVar, Union, Tuple, Sized, Mapping, Sequence
import typing
import enum
import sys
import re
import inspect
GenericAlias: Type = typing._GenericAlias
if sys.version_info < (3, 9):
GenericParameterized = GenericAlias
else:
GenericParameterized: Type = type(dict[int, int])
_T = TypeVar("_T")
def verify_length(l: _T, size: int) -> _T:
n = len(verify_type(l, Sized))
if n != size:
raise ValueError(f"Expected length {size}, got {n}")
return l
def isgenericalias(t: Type) -> bool:
return isinstance(t, (GenericAlias, GenericParameterized))
def type_origin(t: Type) -> Type:
return typing.get_origin(t) or t
def type_args(t: Type) -> Tuple[Type, ...]:
return typing.get_args(t)
def verify_type(x: _T, t: Type) -> _T:
t_type = type_origin(t)
t_args = type_args(t)
if t_type is Union:
for t_arg in t_args:
t_arg_origin = type_origin(t_arg)
if isinstance(x, t_arg_origin):
return verify_type(x, t_arg)
# if isinstance(x, tuple([type_origin(v) for v in t_args])):
# return x
elif isgenericalias(t) and issubclass(t_type, Mapping):
x: Mapping = verify_type(x, t_type)
if t_args:
k_T, v_T = verify_length(t_args, 2)
verify_type(list(x.keys()), Sequence[k_T])
verify_type(list(x.values()), Sequence[v_T])
return x
elif isgenericalias(t) and issubclass(t_type, Sequence):
verify_type(x, t_type)
if hasattr(t, '__args__'):
if t_type is tuple:
verify_length(x, len(t_args))
for i, (v, t) in enumerate(zip(x, t_args)):
verify_type(v, t)
else:
v_T = verify_length(t_args, 1)[0]
for i, v in enumerate(x):
verify_type(v, v_T)
return x
# elif len(t_args) <= 0:
# if isinstance(x, t_type):
# return x
elif inspect.isclass(t) and issubclass(t, enum.Enum):
t: enum.EnumMeta
enum_values = [getattr(x, 'value', x) for x in t.__members__.values()]
if getattr(x, 'value', x) in enum_values:
return x
else:
if isinstance(x, t_type):
return x
msg = f"Type mismatch; expected {t!r}, was {type(x)!r} for input value {x!r}"
raise TypeError(re.sub("""<class ['"](.*?)['"]>""", r"\1", msg))
|
# Generated by Django 2.1.7 on 2019-03-25 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('qgisserver', '0012_auto_20190305_1011'),
]
operations = [
migrations.AlterField(
model_name='service',
name='active',
field=models.BooleanField(default=True, help_text='Enable/disable usage'),
),
migrations.AlterField(
model_name='service',
name='visibility',
field=models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', help_text="visibility='Private' restricts usage to authenticated users", max_length=10),
),
]
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGOD_AQL_AST_H
#define ARANGOD_AQL_AST_H 1
#include "Basics/Common.h"
#include "Aql/AstNode.h"
#include "Aql/BindParameters.h"
#include "Aql/Scopes.h"
#include "Aql/Variable.h"
#include "Aql/VariableGenerator.h"
#include "Transaction/Methods.h"
#include "VocBase/AccessMode.h"
#include <functional>
namespace arangodb {
namespace velocypack {
class Slice;
}
namespace aql {
class Query;
class VariableGenerator;
typedef std::unordered_map<Variable const*, std::unordered_set<std::string>>
TopLevelAttributes;
/// @brief the AST
class Ast {
friend class Condition;
public:
/// @brief create the AST
explicit Ast(Query*);
/// @brief destroy the AST
~Ast();
public:
/// @brief return the query
inline Query* query() const { return _query; }
/// @brief return the variable generator
inline VariableGenerator* variables() { return &_variables; }
/// @brief return the root of the AST
inline AstNode const* root() const { return _root; }
/// @brief begin a subquery
void startSubQuery() {
// insert a new root node
AstNodeType type;
if (_queries.empty()) {
// root node of query
type = NODE_TYPE_ROOT;
} else {
// sub query node
type = NODE_TYPE_SUBQUERY;
}
auto root = createNode(type);
// save the root node
_queries.emplace_back(root);
// set the current root node if everything went well
_root = root;
}
/// @brief end a subquery
AstNode* endSubQuery() {
// get the current root node
AstNode* root = _queries.back();
// remove it from the stack
_queries.pop_back();
// set root node to previous root node
_root = _queries.back();
// return the root node we just popped from the stack
return root;
}
/// @brief whether or not we currently are in a subquery
bool isInSubQuery() const { return (_queries.size() > 1); }
/// @brief return a copy of our own bind parameters
std::unordered_set<std::string> bindParameters() const {
return std::unordered_set<std::string>(_bindParameters);
}
/// @brief get the query scopes
inline Scopes* scopes() { return &_scopes; }
/// @brief track the write collection
inline void addWriteCollection(AstNode const* node) {
TRI_ASSERT(node->type == NODE_TYPE_COLLECTION ||
node->type == NODE_TYPE_PARAMETER);
_writeCollections.emplace_back(node);
}
/// @brief whether or not function calls may access collection documents
bool functionsMayAccessDocuments() const {
return _functionsMayAccessDocuments;
}
/// @brief whether or not the query contains a traversal
bool containsTraversal() const { return _containsTraversal; }
/// @brief convert the AST into VelocyPack
std::shared_ptr<arangodb::velocypack::Builder> toVelocyPack(bool) const;
/// @brief add an operation to the root node
void addOperation(AstNode*);
/// @brief find the bottom-most expansion subnodes (if any)
AstNode const* findExpansionSubNode(AstNode const*) const;
/// @brief create an AST passthru node
/// note: this type of node is only used during parsing and optimized away
/// later
AstNode* createNodePassthru(AstNode const*);
/// @brief create an AST example node
AstNode* createNodeExample(AstNode const*, AstNode const*);
/// @brief create an AST for node
AstNode* createNodeFor(char const*, size_t, AstNode const*, bool);
/// @brief create an AST let node, without an IF condition
AstNode* createNodeLet(char const*, size_t, AstNode const*, bool);
/// @brief create an AST let node, without creating a variable
AstNode* createNodeLet(AstNode const*, AstNode const*);
/// @brief create an AST let node, with an IF condition
AstNode* createNodeLet(char const*, size_t, AstNode const*, AstNode const*);
/// @brief create an AST filter node
AstNode* createNodeFilter(AstNode const*);
/// @brief create an AST filter node for an UPSERT query
AstNode* createNodeUpsertFilter(AstNode const*, AstNode const*);
/// @brief create an AST return node
AstNode* createNodeReturn(AstNode const*);
/// @brief create an AST remove node
AstNode* createNodeRemove(AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST insert node
AstNode* createNodeInsert(AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST update node
AstNode* createNodeUpdate(AstNode const*, AstNode const*, AstNode const*,
AstNode const*);
/// @brief create an AST replace node
AstNode* createNodeReplace(AstNode const*, AstNode const*, AstNode const*,
AstNode const*);
/// @brief create an AST upsert node
AstNode* createNodeUpsert(AstNodeType, AstNode const*, AstNode const*,
AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST distinct node
AstNode* createNodeDistinct(AstNode const*);
/// @brief create an AST collect node
AstNode* createNodeCollect(AstNode const*, AstNode const*, AstNode const*,
AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST collect node, COUNT INTO
AstNode* createNodeCollectCount(AstNode const*, char const*, size_t length,
AstNode const*);
/// @brief create an AST sort node
AstNode* createNodeSort(AstNode const*);
/// @brief create an AST sort element node
AstNode* createNodeSortElement(AstNode const*, AstNode const*);
/// @brief create an AST limit node
AstNode* createNodeLimit(AstNode const*, AstNode const*);
/// @brief create an AST assign node
AstNode* createNodeAssign(char const*, size_t, AstNode const*);
/// @brief create an AST variable node
AstNode* createNodeVariable(char const*, size_t, bool);
/// @brief create an AST collection node
AstNode* createNodeCollection(char const*, AccessMode::Type);
/// @brief create an AST reference node
AstNode* createNodeReference(char const*, size_t);
/// @brief create an AST reference node
AstNode* createNodeReference(std::string const&);
/// @brief create an AST reference node
AstNode* createNodeReference(Variable const*);
/// @brief create an AST parameter node
AstNode* createNodeParameter(char const*, size_t);
/// @brief create an AST quantifier node
AstNode* createNodeQuantifier(int64_t);
/// @brief create an AST unary operator
AstNode* createNodeUnaryOperator(AstNodeType, AstNode const*);
/// @brief create an AST binary operator
AstNode* createNodeBinaryOperator(AstNodeType, AstNode const*,
AstNode const*);
/// @brief create an AST binary array operator
AstNode* createNodeBinaryArrayOperator(AstNodeType, AstNode const*,
AstNode const*, AstNode const*);
/// @brief create an AST ternary operator
AstNode* createNodeTernaryOperator(AstNode const*, AstNode const*,
AstNode const*);
/// @brief create an AST attribute access node
AstNode* createNodeAttributeAccess(AstNode const*, char const*, size_t);
/// @brief create an AST attribute access node w/ bind parameter
AstNode* createNodeBoundAttributeAccess(AstNode const*, AstNode const*);
/// @brief create an AST index access node
AstNode* createNodeIndexedAccess(AstNode const*, AstNode const*);
/// @brief create an AST array limit node (offset, count)
AstNode* createNodeArrayLimit(AstNode const*, AstNode const*);
/// @brief create an AST expansion node
AstNode* createNodeExpansion(int64_t, AstNode const*, AstNode const*,
AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST iterator node
AstNode* createNodeIterator(char const*, size_t, AstNode const*);
/// @brief create an AST null value node
static AstNode* createNodeValueNull();
/// @brief create an AST bool value node
static AstNode* createNodeValueBool(bool);
/// @brief create an AST int value node
AstNode* createNodeValueInt(int64_t);
/// @brief create an AST double value node
AstNode* createNodeValueDouble(double);
/// @brief create an AST string value node
AstNode* createNodeValueString(char const*, size_t);
/// @brief create an AST array node
AstNode* createNodeArray();
AstNode* createNodeArray(size_t members);
/// @brief create an AST unique array node, AND-merged from two other arrays
AstNode* createNodeIntersectedArray(AstNode const*, AstNode const*);
/// @brief create an AST unique array node, OR-merged from two other arrays
AstNode* createNodeUnionizedArray(AstNode const*, AstNode const*);
/// @brief create an AST object node
AstNode* createNodeObject();
/// @brief create an AST object element node
AstNode* createNodeObjectElement(char const*, size_t, AstNode const*);
/// @brief create an AST calculated object element node
AstNode* createNodeCalculatedObjectElement(AstNode const*, AstNode const*);
/// @brief create an AST collection pair node
AstNode* createNodeCollectionPair(AstNode const*, AstNode const*);
/// @brief create an AST with collections node
AstNode* createNodeWithCollections (AstNode const*);
/// @brief create an AST collection list node
AstNode* createNodeCollectionList(AstNode const*);
/// @brief create an AST direction node
AstNode* createNodeDirection(uint64_t, uint64_t);
/// @brief create an AST direction node
AstNode* createNodeDirection(uint64_t, AstNode const*);
/// @brief create an AST direction node
AstNode* createNodeCollectionDirection(uint64_t, AstNode const*);
/// @brief create an AST traversal node with only vertex variable
AstNode* createNodeTraversal(char const*, size_t, AstNode const*,
AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST traversal node with vertex and edge variable
AstNode* createNodeTraversal(char const*, size_t, char const*, size_t,
AstNode const*, AstNode const*, AstNode const*,
AstNode const*);
/// @brief create an AST traversal node with vertex, edge and path variable
AstNode* createNodeTraversal(char const*, size_t, char const*, size_t,
char const*, size_t, AstNode const*,
AstNode const*, AstNode const*, AstNode const*);
/// @brief create an AST shortest path node with only vertex variable
AstNode* createNodeShortestPath(char const*, size_t, uint64_t, AstNode const*,
AstNode const*, AstNode const*,
AstNode const*);
/// @brief create an AST shortest path node with vertex and edge variable
AstNode* createNodeShortestPath(char const*, size_t, char const*, size_t,
uint64_t, AstNode const*, AstNode const*,
AstNode const*, AstNode const*);
/// @brief create an AST function call node
AstNode* createNodeFunctionCall(char const*, AstNode const*);
/// @brief create an AST range node
AstNode* createNodeRange(AstNode const*, AstNode const*);
/// @brief create an AST nop node
AstNode* createNodeNop();
/// @brief get the AST nop node
static AstNode* getNodeNop();
/// @brief create an AST n-ary operator
AstNode* createNodeNaryOperator(AstNodeType);
/// @brief create an AST n-ary operator
AstNode* createNodeNaryOperator(AstNodeType, AstNode const*);
/// @brief injects bind parameters into the AST
void injectBindParameters(BindParameters&);
/// @brief replace variables
AstNode* replaceVariables(
AstNode*, std::unordered_map<VariableId, Variable const*> const&);
/// @brief replace a variable reference in the expression with another
/// expression (e.g. inserting c = `a + b` into expression `c + 1` so the
/// latter
/// becomes `a + b + 1`
AstNode* replaceVariableReference(AstNode*, Variable const*, AstNode const*);
/// @brief optimizes the AST
void validateAndOptimize();
/// @brief determines the variables referenced in an expression
static void getReferencedVariables(AstNode const*,
std::unordered_set<Variable const*>&);
/// @brief count how many times a variable is referenced in an expression
static size_t countReferences(AstNode const*, Variable const*);
/// @brief determines the top-level attributes in an expression, grouped by
/// variable
static TopLevelAttributes getReferencedAttributes(AstNode const*, bool&);
static bool populateSingleAttributeAccess(AstNode const* node,
Variable const* variable,
std::vector<std::string>& attributeName);
static bool variableOnlyUsedForSingleAttributeAccess(AstNode const* node,
Variable const* variable,
std::vector<std::string> const& attributeName);
/// @brief replace an attribute access with just the variable
static AstNode* replaceAttributeAccess(AstNode* node,
Variable const* variable,
std::vector<std::string> const& attributeName);
/// @brief recursively clone a node
AstNode* clone(AstNode const*);
/// @brief deduplicate an array
/// will return the original node if no modifications were made, and a new
/// node if the array contained modifications
AstNode const* deduplicateArray(AstNode const*);
/// @brief check if an operator is reversible
static bool IsReversibleOperator(AstNodeType);
/// @brief get the reversed operator for a comparison operator
static AstNodeType ReverseOperator(AstNodeType);
/// @brief get the n-ary operator type equivalent for a binary operator type
static AstNodeType NaryOperatorType(AstNodeType);
/// @brief create an AST node from vpack
AstNode* nodeFromVPack(arangodb::velocypack::Slice const&, bool);
/// @brief resolve an attribute access
static AstNode const* resolveConstAttributeAccess(AstNode const*);
/// @brief traverse the AST using a depth-first visitor
static AstNode* traverseAndModify(AstNode*,
std::function<AstNode*(AstNode*, void*)>,
void*);
private:
/// @brief make condition from example
AstNode* makeConditionFromExample(AstNode const*);
/// @brief create a number node for an arithmetic result, integer
AstNode* createArithmeticResultNode(int64_t);
/// @brief create a number node for an arithmetic result, double
AstNode* createArithmeticResultNode(double);
/// @brief executes an expression with constant parameters
AstNode* executeConstExpression(AstNode const*);
/// @brief optimizes the unary operators + and -
/// the unary plus will be converted into a simple value node if the operand
/// of
/// the operation is a constant number
AstNode* optimizeUnaryOperatorArithmetic(AstNode*);
/// @brief optimizes the unary operator NOT with a non-constant expression
AstNode* optimizeNotExpression(AstNode*);
/// @brief optimizes the unary operator NOT
AstNode* optimizeUnaryOperatorLogical(AstNode*);
/// @brief optimizes the binary logical operators && and ||
AstNode* optimizeBinaryOperatorLogical(AstNode*, bool);
/// @brief optimizes the binary relational operators <, <=, >, >=, ==, != and
/// IN
AstNode* optimizeBinaryOperatorRelational(AstNode*);
/// @brief optimizes the binary arithmetic operators +, -, *, / and %
AstNode* optimizeBinaryOperatorArithmetic(AstNode*);
/// @brief optimizes the ternary operator
AstNode* optimizeTernaryOperator(AstNode*);
/// @brief optimizes an attribute access
AstNode* optimizeAttributeAccess(AstNode*, std::unordered_map<Variable const*, AstNode const*> const&);
/// @brief optimizes a call to a built-in function
AstNode* optimizeFunctionCall(AstNode*);
/// @brief optimizes a reference to a variable
AstNode* optimizeReference(AstNode*);
/// @brief optimizes indexed access, e.g. a[0] or a['foo']
AstNode* optimizeIndexedAccess(AstNode*);
/// @brief optimizes the LET statement
AstNode* optimizeLet(AstNode*);
/// @brief optimizes the FILTER statement
AstNode* optimizeFilter(AstNode*);
/// @brief optimizes the FOR statement
/// no real optimizations are done here, but we do an early check if the
/// FOR loop operand is actually a list
AstNode* optimizeFor(AstNode*);
/// @brief optimizes an object literal or an object expression
AstNode* optimizeObject(AstNode*);
public:
/// @brief traverse the AST, using pre- and post-order visitors
static AstNode* traverseAndModify(AstNode*,
std::function<bool(AstNode const*, void*)>,
std::function<AstNode*(AstNode*, void*)>,
std::function<void(AstNode const*, void*)>,
void*);
/// @brief traverse the AST, using pre- and post-order visitors
static void traverseReadOnly(AstNode const*,
std::function<void(AstNode const*, void*)>,
std::function<void(AstNode const*, void*)>,
std::function<void(AstNode const*, void*)>,
void*);
/// @brief traverse the AST using a depth-first visitor, with const nodes
static void traverseReadOnly(AstNode const*,
std::function<void(AstNode const*, void*)>,
void*);
private:
/// @brief normalize a function name
std::pair<std::string, bool> normalizeFunctionName(char const*);
/// @brief create a node of the specified type
AstNode* createNode(AstNodeType);
public:
/// @brief negated comparison operators
static std::unordered_map<int, AstNodeType> const NegatedOperators;
/// @brief reverse comparison operators
static std::unordered_map<int, AstNodeType> const ReversedOperators;
private:
/// @brief the query
Query* _query;
/// @brief all scopes used in the query
Scopes _scopes;
/// @brief generator for variables
VariableGenerator _variables;
/// @brief the bind parameters we found in the query
std::unordered_set<std::string> _bindParameters;
/// @brief root node of the AST
AstNode* _root;
/// @brief root nodes of queries and subqueries
std::vector<AstNode*> _queries;
/// @brief which collection is going to be modified in the query
std::vector<AstNode const*> _writeCollections;
/// @brief whether or not function calls may access collection data
bool _functionsMayAccessDocuments;
/// @brief whether or not the query contains a traversal
bool _containsTraversal;
/// @brief a singleton no-op node instance
static AstNode const NopNode;
/// @brief a singleton null node instance
static AstNode const NullNode;
/// @brief a singleton false node instance
static AstNode const FalseNode;
/// @brief a singleton true node instance
static AstNode const TrueNode;
/// @brief a singleton zero node instance
static AstNode const ZeroNode;
/// @brief a singleton empty string node instance
static AstNode const EmptyStringNode;
};
}
}
#endif
|
import Navbar from 'react-bootstrap/Navbar';
import React from 'react';
export default function SingleViewHeader(props) {
return (
<>
<Navbar bg={'light'}>
<Navbar.Brand>
<img
onClick={()=>{props.onBack()}}
alt={'Back'}
src={'../resources/arrow-back.png'}
width={30}
height={30}>
</img>
</Navbar.Brand>
<Navbar.Collapse className={'justify-content-center'}
style={{'marginLeft': '-30px'}}>
<Navbar.Brand>
{props.name}
</Navbar.Brand>
</Navbar.Collapse>
</Navbar>
<hr style={{'marginTop': 0}}/>
</>
);
}
|
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
ES5Harness.registerTest({
id: "15.4.4.16-7-c-ii-5",
path: "TestCases/chapter15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-c-ii-5.js",
description: "Array.prototype.every - k values are accessed during each iteration and not prior to starting the loop on an Array",
test: function testcase() {
var called = 0;
var kIndex = [];
//By below way, we could verify that k would be setted as 0, 1, ..., length - 1 in order, and each value will be setted one time.
function callbackfn(val, idx, obj) {
called++;
//Each position should be visited one time, which means k is accessed one time during iterations.
if (typeof kIndex[idx] === "undefined") {
//when current position is visited, its previous index should has been visited.
if (idx !== 0 && typeof kIndex[idx - 1] === "undefined") {
return false;
}
kIndex[idx] = 1;
return true;
} else {
return false;
}
}
return [11, 12, 13, 14].every(callbackfn, undefined) && 4 === called;
},
precondition: function prereq() {
return fnExists(Array.prototype.every);
}
});
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2010 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
import netaddr
import sys
import traceback
from nova import exception
from nova import flags
from nova import image
from nova import log as logging
from nova import test
from nova.tests import utils as test_utils
libvirt = None
FLAGS = flags.FLAGS
LOG = logging.getLogger(__name__)
def catch_notimplementederror(f):
"""Decorator to simplify catching drivers raising NotImplementedError
If a particular call makes a driver raise NotImplementedError, we
log it so that we can extract this information afterwards to
automatically generate a hypervisor/feature support matrix."""
def wrapped_func(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except NotImplementedError:
frame = traceback.extract_tb(sys.exc_info()[2])[-1]
LOG.error('%(driver)s does not implement %(method)s' % {
'driver': type(self.connection),
'method': frame[2]})
wrapped_func.__name__ = f.__name__
wrapped_func.__doc__ = f.__doc__
return wrapped_func
class _VirtDriverTestCase(test.TestCase):
def setUp(self):
super(_VirtDriverTestCase, self).setUp()
self.connection = self.driver_module.get_connection('')
self.ctxt = test_utils.get_test_admin_context()
self.image_service = image.get_default_image_service()
def _get_running_instance(self):
instance_ref = test_utils.get_test_instance()
network_info = test_utils.get_test_network_info()
image_info = test_utils.get_test_image_info(None, instance_ref)
self.connection.spawn(self.ctxt, instance=instance_ref,
image_meta=image_info,
network_info=network_info)
return instance_ref, network_info
@catch_notimplementederror
def test_init_host(self):
self.connection.init_host('myhostname')
@catch_notimplementederror
def test_list_instances(self):
self.connection.list_instances()
@catch_notimplementederror
def test_list_instances_detail(self):
self.connection.list_instances_detail()
@catch_notimplementederror
def test_spawn(self):
instance_ref, network_info = self._get_running_instance()
domains = self.connection.list_instances()
self.assertIn(instance_ref['name'], domains)
domains_details = self.connection.list_instances_detail()
self.assertIn(instance_ref['name'], [i.name for i in domains_details])
@catch_notimplementederror
def test_snapshot_not_running(self):
instance_ref = test_utils.get_test_instance()
img_ref = self.image_service.create(self.ctxt, {'name': 'snap-1'})
self.assertRaises(exception.InstanceNotRunning,
self.connection.snapshot,
self.ctxt, instance_ref, img_ref['id'])
@catch_notimplementederror
def test_snapshot_running(self):
img_ref = self.image_service.create(self.ctxt, {'name': 'snap-1'})
instance_ref, network_info = self._get_running_instance()
self.connection.snapshot(self.ctxt, instance_ref, img_ref['id'])
@catch_notimplementederror
def test_reboot(self):
reboot_type = "SOFT"
instance_ref, network_info = self._get_running_instance()
self.connection.reboot(instance_ref, network_info, reboot_type)
@catch_notimplementederror
def test_get_host_ip_addr(self):
host_ip = self.connection.get_host_ip_addr()
# Will raise an exception if it's not a valid IP at all
ip = netaddr.IPAddress(host_ip)
# For now, assume IPv4.
self.assertEquals(ip.version, 4)
@catch_notimplementederror
def test_resize_running(self):
instance_ref, network_info = self._get_running_instance()
self.connection.resize(instance_ref, 7)
@catch_notimplementederror
def test_set_admin_password(self):
instance_ref, network_info = self._get_running_instance()
self.connection.set_admin_password(instance_ref, 'p4ssw0rd')
@catch_notimplementederror
def test_inject_file(self):
instance_ref, network_info = self._get_running_instance()
self.connection.inject_file(instance_ref,
base64.b64encode('/testfile'),
base64.b64encode('testcontents'))
@catch_notimplementederror
def test_agent_update(self):
instance_ref, network_info = self._get_running_instance()
self.connection.agent_update(instance_ref, 'http://www.openstack.org/',
'd41d8cd98f00b204e9800998ecf8427e')
@catch_notimplementederror
def test_rescue(self):
instance_ref, network_info = self._get_running_instance()
self.connection.rescue(self.ctxt, instance_ref, network_info, None)
@catch_notimplementederror
def test_unrescue_unrescued_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.unrescue(instance_ref, network_info)
@catch_notimplementederror
def test_unrescue_rescued_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.rescue(self.ctxt, instance_ref, network_info, None)
self.connection.unrescue(instance_ref, network_info)
@catch_notimplementederror
def test_poll_rebooting_instances(self):
self.connection.poll_rebooting_instances(10)
@catch_notimplementederror
def test_poll_rescued_instances(self):
self.connection.poll_rescued_instances(10)
@catch_notimplementederror
def test_poll_unconfirmed_resizes(self):
self.connection.poll_unconfirmed_resizes(10)
@catch_notimplementederror
def test_migrate_disk_and_power_off(self):
instance_ref, network_info = self._get_running_instance()
instance_type_ref = test_utils.get_test_instance_type()
self.connection.migrate_disk_and_power_off(
self.ctxt, instance_ref, 'dest_host', instance_type_ref,
network_info)
@catch_notimplementederror
def test_pause(self):
instance_ref, network_info = self._get_running_instance()
self.connection.pause(instance_ref)
@catch_notimplementederror
def test_unpause_unpaused_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.unpause(instance_ref)
@catch_notimplementederror
def test_unpause_paused_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.pause(instance_ref)
self.connection.unpause(instance_ref)
@catch_notimplementederror
def test_suspend(self):
instance_ref, network_info = self._get_running_instance()
self.connection.suspend(instance_ref)
@catch_notimplementederror
def test_resume_unsuspended_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.resume(instance_ref)
@catch_notimplementederror
def test_resume_suspended_instance(self):
instance_ref, network_info = self._get_running_instance()
self.connection.suspend(instance_ref)
self.connection.resume(instance_ref)
@catch_notimplementederror
def test_destroy_instance_nonexistant(self):
fake_instance = {'id': 42, 'name': 'I just made this up!',
'uuid': 'bda5fb9e-b347-40e8-8256-42397848cb00'}
network_info = test_utils.get_test_network_info()
self.connection.destroy(fake_instance, network_info)
@catch_notimplementederror
def test_destroy_instance(self):
instance_ref, network_info = self._get_running_instance()
self.assertIn(instance_ref['name'],
self.connection.list_instances())
self.connection.destroy(instance_ref, network_info)
self.assertNotIn(instance_ref['name'],
self.connection.list_instances())
@catch_notimplementederror
def test_get_volume_connector(self):
result = self.connection.get_volume_connector({'id': 'fake'})
self.assertTrue('ip' in result)
self.assertTrue('initiator' in result)
self.assertTrue('host' in result)
@catch_notimplementederror
def test_attach_detach_volume(self):
instance_ref, network_info = self._get_running_instance()
self.connection.attach_volume({'driver_volume_type': 'fake'},
instance_ref['name'],
'/mnt/nova/something')
self.connection.detach_volume({'driver_volume_type': 'fake'},
instance_ref['name'],
'/mnt/nova/something')
@catch_notimplementederror
def test_get_info(self):
instance_ref, network_info = self._get_running_instance()
info = self.connection.get_info(instance_ref)
self.assertIn('state', info)
self.assertIn('max_mem', info)
self.assertIn('mem', info)
self.assertIn('num_cpu', info)
self.assertIn('cpu_time', info)
@catch_notimplementederror
def test_get_info_for_unknown_instance(self):
self.assertRaises(exception.NotFound,
self.connection.get_info,
{'name': 'I just made this name up'})
@catch_notimplementederror
def test_get_diagnostics(self):
instance_ref, network_info = self._get_running_instance()
self.connection.get_diagnostics(instance_ref['name'])
@catch_notimplementederror
def test_list_disks(self):
instance_ref, network_info = self._get_running_instance()
self.connection.list_disks(instance_ref['name'])
@catch_notimplementederror
def test_list_interfaces(self):
instance_ref, network_info = self._get_running_instance()
self.connection.list_interfaces(instance_ref['name'])
@catch_notimplementederror
def test_block_stats(self):
instance_ref, network_info = self._get_running_instance()
stats = self.connection.block_stats(instance_ref['name'], 'someid')
self.assertEquals(len(stats), 5)
@catch_notimplementederror
def test_interface_stats(self):
instance_ref, network_info = self._get_running_instance()
stats = self.connection.interface_stats(instance_ref['name'], 'someid')
self.assertEquals(len(stats), 8)
@catch_notimplementederror
def test_get_console_output(self):
instance_ref, network_info = self._get_running_instance()
console_output = self.connection.get_console_output(instance_ref)
self.assertTrue(isinstance(console_output, basestring))
@catch_notimplementederror
def test_get_vnc_console(self):
instance_ref, network_info = self._get_running_instance()
vnc_console = self.connection.get_vnc_console(instance_ref)
self.assertIn('internal_access_path', vnc_console)
self.assertIn('host', vnc_console)
self.assertIn('port', vnc_console)
@catch_notimplementederror
def test_get_console_pool_info(self):
instance_ref, network_info = self._get_running_instance()
console_pool = self.connection.get_console_pool_info(instance_ref)
self.assertIn('address', console_pool)
self.assertIn('username', console_pool)
self.assertIn('password', console_pool)
@catch_notimplementederror
def test_refresh_security_group_rules(self):
# FIXME: Create security group and add the instance to it
instance_ref, network_info = self._get_running_instance()
self.connection.refresh_security_group_rules(1)
@catch_notimplementederror
def test_refresh_security_group_members(self):
# FIXME: Create security group and add the instance to it
instance_ref, network_info = self._get_running_instance()
self.connection.refresh_security_group_members(1)
@catch_notimplementederror
def test_refresh_provider_fw_rules(self):
instance_ref, network_info = self._get_running_instance()
self.connection.refresh_provider_fw_rules()
@catch_notimplementederror
def test_compare_cpu(self):
cpu_info = '''{ "topology": {
"sockets": 1,
"cores": 2,
"threads": 1 },
"features": [
"xtpr",
"tm2",
"est",
"vmx",
"ds_cpl",
"monitor",
"pbe",
"tm",
"ht",
"ss",
"acpi",
"ds",
"vme"],
"arch": "x86_64",
"model": "Penryn",
"vendor": "Intel" }'''
self.connection.compare_cpu(cpu_info)
@catch_notimplementederror
def test_ensure_filtering_for_instance(self):
instance_ref = test_utils.get_test_instance()
network_info = test_utils.get_test_network_info()
self.connection.ensure_filtering_rules_for_instance(instance_ref,
network_info)
@catch_notimplementederror
def test_unfilter_instance(self):
instance_ref = test_utils.get_test_instance()
network_info = test_utils.get_test_network_info()
self.connection.unfilter_instance(instance_ref, network_info)
@catch_notimplementederror
def test_live_migration(self):
instance_ref, network_info = self._get_running_instance()
self.connection.live_migration(self.ctxt, instance_ref, 'otherhost',
None, None)
@catch_notimplementederror
def _check_host_status_fields(self, host_status):
self.assertIn('disk_total', host_status)
self.assertIn('disk_used', host_status)
self.assertIn('host_memory_total', host_status)
self.assertIn('host_memory_free', host_status)
@catch_notimplementederror
def test_update_host_status(self):
host_status = self.connection.update_host_status()
self._check_host_status_fields(host_status)
@catch_notimplementederror
def test_get_host_stats(self):
host_status = self.connection.get_host_stats()
self._check_host_status_fields(host_status)
@catch_notimplementederror
def test_set_host_enabled(self):
self.connection.set_host_enabled('a useless argument?', True)
@catch_notimplementederror
def test_host_power_action_reboot(self):
self.connection.host_power_action('a useless argument?', 'reboot')
@catch_notimplementederror
def test_host_power_action_shutdown(self):
self.connection.host_power_action('a useless argument?', 'shutdown')
@catch_notimplementederror
def test_host_power_action_startup(self):
self.connection.host_power_action('a useless argument?', 'startup')
@catch_notimplementederror
def test_add_to_aggregate(self):
self.connection.add_to_aggregate(self.ctxt, 'aggregate', 'host')
@catch_notimplementederror
def test_remove_from_aggregate(self):
self.connection.remove_from_aggregate(self.ctxt, 'aggregate', 'host')
class AbstractDriverTestCase(_VirtDriverTestCase):
def setUp(self):
import nova.virt.driver
self.driver_module = nova.virt.driver
def get_driver_connection(_):
return nova.virt.driver.ComputeDriver()
self.driver_module.get_connection = get_driver_connection
super(AbstractDriverTestCase, self).setUp()
class FakeConnectionTestCase(_VirtDriverTestCase):
def setUp(self):
import nova.virt.fake
self.driver_module = nova.virt.fake
super(FakeConnectionTestCase, self).setUp()
class LibvirtConnTestCase(_VirtDriverTestCase):
def setUp(self):
# Put fakelibvirt in place
if 'libvirt' in sys.modules:
self.saved_libvirt = sys.modules['libvirt']
else:
self.saved_libvirt = None
import fakelibvirt
import fake_libvirt_utils
sys.modules['libvirt'] = fakelibvirt
import nova.virt.libvirt.connection
import nova.virt.libvirt.firewall
nova.virt.libvirt.connection.libvirt = fakelibvirt
nova.virt.libvirt.connection.libvirt_utils = fake_libvirt_utils
nova.virt.libvirt.firewall.libvirt = fakelibvirt
# So that the _supports_direct_io does the test based
# on the current working directory, instead of the
# default instances_path which doesn't exist
FLAGS.instances_path = ''
# Point _VirtDriverTestCase at the right module
self.driver_module = nova.virt.libvirt.connection
super(LibvirtConnTestCase, self).setUp()
self.flags(firewall_driver=nova.virt.libvirt.firewall.drivers[0],
rescue_image_id="2",
rescue_kernel_id="3",
rescue_ramdisk_id=None)
def fake_extend(image, size):
pass
self.stubs.Set(nova.virt.libvirt.connection.disk,
'extend', fake_extend)
def tearDown(self):
# Restore libvirt
import nova.virt.libvirt.connection
import nova.virt.libvirt.firewall
if self.saved_libvirt:
sys.modules['libvirt'] = self.saved_libvirt
nova.virt.libvirt.connection.libvirt = self.saved_libvirt
nova.virt.libvirt.connection.libvirt_utils = self.saved_libvirt
nova.virt.libvirt.firewall.libvirt = self.saved_libvirt
super(LibvirtConnTestCase, self).tearDown()
def test_force_hard_reboot(self):
self.flags(libvirt_wait_soft_reboot_seconds=0)
self.test_reboot()
@test.skip_test("Test nothing, but this method "
"needed to override superclass.")
def test_migrate_disk_and_power_off(self):
# there is lack of fake stuff to execute this method. so pass.
pass
|
#!/usr/bin/env python3
#
# image metadata cleaner
# Corey Goldberg, 2014, 2019
#
"""Recursively scan a directory and clear metadata from image files.
* removes all metadata (Exif, IPTC, XMP, GPS Info, comment, thumbnail)
* works with .jpg and .png formats
* modifications are done in-place
requires:
* gexiv2 (GObject-based wrapper for the Exiv2 library
- Install on Ubuntu/Debian: $ sudo apt-get install gir1.2-gexiv2-X
* exiv2
- Install on Ubuntu/Debian: $ sudo apt-get install exiv2
"""
import subprocess
import os
import sys
import time
try:
from gi.repository import GExiv2
except ImportError:
sys.exit('gexiv2 not installed')
def clear_all_metadata(img_path):
metadata = GExiv2.Metadata(img_path)
metadata.clear_comment()
metadata.clear_exif()
metadata.clear_iptc()
metadata.clear_xmp()
metadata.delete_gps_info()
metadata.erase_exif_thumbnail()
metadata.clear()
metadata.save_file()
if __name__ == '__main__':
dir = os.getcwd()
for root, dirs, filenames in os.walk(dir):
for filename in filenames:
file_path = os.path.join(root, filename)
if filename.lower().endswith(('jpg', 'png')):
# delete all metadata with exiv2
subprocess.call(['exiv2', '-d', 'a', 'delete', file_path])
# delete all metadata again with gexiv
clear_all_metadata(file_path)
print(file_path)
|
/*!
* VisualEditor ContentEditable AbbreviationAnnotation class.
*
* @copyright 2011-2014 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
/**
* ContentEditable abbreviation annotation.
*
* @class
* @extends ve.ce.TextStyleAnnotation
* @constructor
* @param {ve.dm.AbbreviationAnnotation} model Model to observe
* @param {ve.ce.ContentBranchNode} [parentNode] Node rendering this annotation
* @param {Object} [config] Configuration options
*/
ve.ce.AbbreviationAnnotation = function VeCeAbbreviationAnnotation( model, parentNode, config ) {
// Parent constructor
ve.ce.TextStyleAnnotation.call( this, model, parentNode, config );
// DOM changes
this.$element.addClass( 've-ce-AbbreviationAnnotation' );
};
/* Inheritance */
OO.inheritClass( ve.ce.AbbreviationAnnotation, ve.ce.TextStyleAnnotation );
/* Static Properties */
ve.ce.AbbreviationAnnotation.static.name = 'textStyle/abbreviation';
ve.ce.AbbreviationAnnotation.static.tagName = 'abbr';
/* Registration */
ve.ce.annotationFactory.register( ve.ce.AbbreviationAnnotation );
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.aiplatform_v1beta1.types import index
from google.cloud.aiplatform_v1beta1.types import index_service
from google.longrunning import operations_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-aiplatform",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
try:
# google.auth.__version__ was added in 1.26.0
_GOOGLE_AUTH_VERSION = google.auth.__version__
except AttributeError:
try: # try pkg_resources if it is available
_GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version
except pkg_resources.DistributionNotFound: # pragma: NO COVER
_GOOGLE_AUTH_VERSION = None
class IndexServiceTransport(abc.ABC):
"""Abstract transport class for IndexService."""
AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
DEFAULT_HOST: str = "aiplatform.googleapis.com"
def __init__(
self,
*,
host: str = DEFAULT_HOST,
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
scopes_kwargs = self._get_scopes_kwargs(self._host, scopes)
# Save the scopes.
self._scopes = scopes
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise core_exceptions.DuplicateCredentialArgs(
"'credentials_file' and 'credentials' are mutually exclusive"
)
if credentials_file is not None:
credentials, _ = google.auth.load_credentials_from_file(
credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
# If the credentials are service account credentials, then always try to use self signed JWT.
if (
always_use_jwt_access
and isinstance(credentials, service_account.Credentials)
and hasattr(service_account.Credentials, "with_always_use_jwt_access")
):
credentials = credentials.with_always_use_jwt_access(True)
# Save the credentials.
self._credentials = credentials
# TODO(busunkim): This method is in the base transport
# to avoid duplicating code across the transport classes. These functions
# should be deleted once the minimum required versions of google-auth is increased.
# TODO: Remove this function once google-auth >= 1.25.0 is required
@classmethod
def _get_scopes_kwargs(
cls, host: str, scopes: Optional[Sequence[str]]
) -> Dict[str, Optional[Sequence[str]]]:
"""Returns scopes kwargs to pass to google-auth methods depending on the google-auth version"""
scopes_kwargs = {}
if _GOOGLE_AUTH_VERSION and (
packaging.version.parse(_GOOGLE_AUTH_VERSION)
>= packaging.version.parse("1.25.0")
):
scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES}
else:
scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES}
return scopes_kwargs
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.create_index: gapic_v1.method.wrap_method(
self.create_index, default_timeout=5.0, client_info=client_info,
),
self.get_index: gapic_v1.method.wrap_method(
self.get_index, default_timeout=5.0, client_info=client_info,
),
self.list_indexes: gapic_v1.method.wrap_method(
self.list_indexes, default_timeout=5.0, client_info=client_info,
),
self.update_index: gapic_v1.method.wrap_method(
self.update_index, default_timeout=5.0, client_info=client_info,
),
self.delete_index: gapic_v1.method.wrap_method(
self.delete_index, default_timeout=5.0, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def operations_client(self) -> operations_v1.OperationsClient:
"""Return the client designed to process long-running operations."""
raise NotImplementedError()
@property
def create_index(
self,
) -> Callable[
[index_service.CreateIndexRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def get_index(
self,
) -> Callable[
[index_service.GetIndexRequest], Union[index.Index, Awaitable[index.Index]]
]:
raise NotImplementedError()
@property
def list_indexes(
self,
) -> Callable[
[index_service.ListIndexesRequest],
Union[
index_service.ListIndexesResponse,
Awaitable[index_service.ListIndexesResponse],
],
]:
raise NotImplementedError()
@property
def update_index(
self,
) -> Callable[
[index_service.UpdateIndexRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
@property
def delete_index(
self,
) -> Callable[
[index_service.DeleteIndexRequest],
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
]:
raise NotImplementedError()
__all__ = ("IndexServiceTransport",)
|
import os
from datetime import datetime
# Mostrar varias informações sobre um determinado arquivo
print(os.stat('02.txt'))
# Tamanho do arquivo
tamanho = os.stat('02.txt').st_size
print(tamanho)
# Ultima modificação do arquivo
data_modificacao = os.stat('02.txt').st_mtime
print(datetime.fromtimestamp(data_modificacao))
|
from qip.ext.kronprod import cdot_loop
from qip.ext.kronprod import reduce_measure
from qip.ext.kronprod import measure
from qip.ext.kronprod import soft_measure
from qip.ext.kronprod import measure_probabilities
from qip.ext.kronprod import measure_top_probabilities
from qip.ext.kronprod import prob_magnitude
from qip.ext.func_apply import func_apply
from qip.util import kronselect_dot, gen_edit_indices, InitialState, IndexType, MatrixType
import numpy
from typing import Sequence, Mapping, Callable, Optional, Tuple, Union
class StateType(object):
def __init__(self, n: int, state: object):
self.n = n
self.state = state
def get_state(self) -> object:
return self.state
def kronselect_dot(self, mats: Mapping[IndexType, MatrixType],
input_offset: int = 0, output_offset: int = 0) -> None:
raise NotImplemented("kronselect_dot not implemented by base class")
def func_apply(self, reg1_indices: Sequence[int], reg2_indices: Sequence[int], func: Callable[[int],int],
input_offset: int = 0, output_offset: int = 0) -> None:
raise NotImplemented("func_apply not implemented by base class")
def total_prob(self) -> float:
raise NotImplemented("total_prob not implemented by base class")
def measure(self, indices: Sequence[int], measured: Optional[int] = None,
measured_prob: Optional[float] = None,
input_offset: int = 0, output_offset: int = 0) -> Tuple[int, float]:
raise NotImplemented("reduce_measure not implemented by base class")
def reduce_measure(self, indices: Sequence[int], measured: Optional[int] = None,
measured_prob: Optional[float] = None,
input_offset: int = 0, output_offset: int = 0) -> Tuple[int, float]:
raise NotImplemented("reduce_measure not implemented by base class")
def soft_measure(self, indices: Sequence[int], measured: Optional[int] = None,
input_offset: int = 0) -> Tuple[int, float]:
raise NotImplemented("measure not implemented by base class")
def measure_probabilities(self, indices: Sequence[int],
top_k: int = 0) -> Union[Sequence[float], Tuple[Sequence[int], Sequence[float]]]:
"""If top_k is 0 then output array of all probabilities, else tuple of indices, probs for top_k probs."""
raise NotImplemented("measure_probabilities not implemented by base class")
def get_state_size(self) -> int:
raise NotImplemented("get_state_size not implemented by base class")
def get_relative_range(self, start: int, end: int) -> Sequence[complex]:
raise NotImplemented("get_relative_range not implemented by base class")
def overwrite_relative_range(self, start: int, end: int, data: Sequence[complex]):
raise NotImplemented("overwrite_relative_range not implemented by base class")
def addto_relative_range(self, start: int, end: int, data: Sequence[complex]):
raise NotImplemented("addto_relative_range not implemented by base class")
def close(self):
pass
class CythonBackend(StateType):
def __init__(self, n: int, state: numpy.ndarray, arena: numpy.ndarray):
super().__init__(n, state)
self.arena = arena
@staticmethod
def make_state(n: int, index_groups: Sequence[Sequence[int]], feed_list: Sequence[InitialState],
inputstartindex: Optional[int] = None, inputendindex: Optional[int] = None,
outputstartindex: Optional[int] = None, outputendindex: Optional[int] = None,
statetype: type = numpy.complex128) -> 'CythonBackend':
if inputstartindex is None:
inputstartindex = 0
if inputendindex is None:
inputendindex = 2 ** n
if outputstartindex is None:
outputstartindex = 0
if outputendindex is None:
outputendindex = 2 ** n
state = numpy.zeros(inputendindex - inputstartindex, dtype=statetype)
if len(feed_list) == 0:
state[0] = 1
# Set all the entries in state to product of matrix entries
for index, flips in gen_edit_indices(index_groups, n - 1):
# Skip out of range
if index < inputstartindex or index >= inputendindex:
continue
# Make index value
state[index - inputstartindex] = 1.0
for qindex, flip in enumerate(flips):
state[index - inputstartindex] = state[index - inputstartindex] * feed_list[qindex][flip]
arena = numpy.ndarray(outputendindex - outputstartindex, dtype=statetype)
return CythonBackend(n, state, arena)
def get_state(self) -> numpy.ndarray:
return self.state
def swap(self):
self.state, self.arena = self.arena, self.state
def kronselect_dot(self, mats: Mapping[IndexType, MatrixType],
input_offset: int = 0, output_offset: int = 0) -> None:
kronselect_dot(mats, self.state, self.n, self.arena, dot_impl=cdot_loop,
input_offset=input_offset, output_offset=output_offset)
self.state, self.arena = self.arena, self.state
def func_apply(self, reg1_indices: Sequence[int], reg2_indices: Sequence[int], func: Callable[[int], int],
input_offset: int = 0, output_offset: int = 0) -> None:
func_apply(reg1_indices, reg2_indices, func, self.state, self.n, self.arena)
self.state, self.arena = self.arena, self.state
def total_prob(self) -> float:
return prob_magnitude(self.state)
def measure(self, indices: Sequence[int], measured: Optional[int] = None,
measured_prob: Optional[float] = None,
input_offset: int = 0, output_offset: int = 0):
bits, prob = measure(numpy.asarray(indices, dtype=numpy.int32),
self.n, self.state, self.arena,
measured=measured, measured_prob=measured_prob,
input_offset=input_offset, output_offset=output_offset)
self.state, self.arena = self.arena, self.state
return bits, prob
def reduce_measure(self, indices: Sequence[int], measured: Optional[int] = None,
measured_prob: Optional[float] = None,
input_offset: int = 0, output_offset: int = 0) -> Tuple[int, float]:
# TODO Get an appropriately sized arena
# new_arena_size = 2**(self.n - len(indices))
# if new_arena_size < self.arena.shape[0]:
# self.arena.resize((new_arena_size,))
bits, prob = reduce_measure(numpy.asarray(indices, dtype=numpy.int32),
self.n, self.state, self.arena,
measured=measured, measured_prob=measured_prob,
input_offset=input_offset, output_offset=output_offset)
# self.state.resize(self.arena.shape)
self.state, self.arena = self.arena, self.state
return bits, prob
def soft_measure(self, indices: Sequence[int], measured: Optional[int] = None,
input_offset: int = 0) -> Tuple[int, float]:
return soft_measure(numpy.asarray(indices, dtype=numpy.int32), self.n, self.state,
measured=measured, input_offset=input_offset)
def measure_probabilities(self, indices: Sequence[int],
top_k: int = 0) -> Union[Sequence[float], Tuple[Sequence[int], Sequence[float]]]:
if top_k:
return measure_top_probabilities(numpy.asarray(indices, dtype=numpy.int32), self.n, top_k, self.state)
else:
return measure_probabilities(numpy.asarray(indices, dtype=numpy.int32), self.n, self.state)
def get_state_size(self) -> int:
return len(self.state)
def get_relative_range(self, start: int, end: int) -> Sequence[complex]:
return self.state[start:end]
def overwrite_relative_range(self, start: int, end: int, data: Sequence[complex]):
self.state[start:end] = data
def addto_relative_range(self, start: int, end: int, data: Sequence[complex]):
self.state[start:end] += data
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from foo_containers.djinni
#pragma once // python_cdef_ignore
#include <stdbool.h> // python_cdef_ignore
#include <stdint.h> // python_cdef_ignore
void list_string___delete(struct DjinniObjectHandle *);
void optional_list_string___delete(struct DjinniOptionalObjectHandle *);
void list_string_add_callback___delete(void(* ptr)(struct DjinniObjectHandle * ));
void list_string_add_callback__get_elem(struct DjinniString *( * ptr)(struct DjinniObjectHandle *, size_t));
void list_string_add_callback__get_size(size_t( * ptr)(struct DjinniObjectHandle *));
void list_string_add_callback__python_create(struct DjinniObjectHandle *( * ptr)());
void list_string_add_callback__python_add(void( * ptr)(struct DjinniObjectHandle *, struct DjinniString *));
|
#!/usr/bin/env python
"""This script shows an example of using the PyWavefront module."""
import ctypes
import sys
sys.path.append('..')
import pyglet
from pyglet.gl import *
from pywavefront import visualization
import pywavefront
rotation = 0
meshes = pywavefront.Wavefront('uv_sphere.obj')
window = pyglet.window.Window()
lightfv = ctypes.c_float * 4
@window.event
def on_resize(width, height):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., float(width)/height, 1., 100.)
glMatrixMode(GL_MODELVIEW)
return True
@window.event
def on_draw():
window.clear()
glLoadIdentity()
glLightfv(GL_LIGHT0, GL_POSITION, lightfv(-1.0, 1.0, 1.0, 0.0))
glEnable(GL_LIGHT0)
glTranslated(0.0, 0.0, -3.0)
glRotatef(rotation, 0.0, 1.0, 0.0)
glRotatef(-25.0, 1.0, 0.0, 0.0)
glRotatef(45.0, 0.0, 0.0, 1.0)
glEnable(GL_LIGHTING)
visualization.draw(meshes)
def update(dt):
global rotation
rotation += 90.0 * dt
if rotation > 720.0:
rotation = 0.0
pyglet.clock.schedule(update)
pyglet.app.run()
|
# coding=utf-8
import os
import re
# 将要解析的项目名称
DESPATH = "/Users/wangsuyan/desktop/project/LGSKmart/LGSKmart/Resource/Localizations"
ERROR_DESPATH = "/Users/wangsuyan/Desktop/checkLocalizable.log"
MAIN_LOCALIZABLE_FILE = "/zh-Hans.lproj/Localizable.strings"
_result = {}
def filename(filePath):
return os.path.split(filePath)[1]
def pragram_error(filePath):
if '/Base.lproj/Localizable.strings' in filePath:
return
print(filePath)
f = open(filePath)
isMutliNote = False
fname = filePath.replace(DESPATH, '')
_list = set()
for index, line in enumerate(f):
line = line.strip()
if '/*' in line:
isMutliNote = True
if '*/' in line:
isMutliNote = False
if isMutliNote:
continue
if len(line) == 0 or line == '*/':
continue
if re.findall(r'^/+', line):
continue
regx = r'^"(.*s?)"\s*=\s*".*?";$'
matchs = re.findall(regx, line)
if matchs:
for item in matchs:
_list.add(item)
_result[fname] = _list
def find_from_file(path):
paths = os.listdir(path)
for aCompent in paths:
aPath = os.path.join(path, aCompent)
if os.path.isdir(aPath):
find_from_file(aPath)
elif os.path.isfile(aPath) and os.path.splitext(aPath)[1]=='.strings':
pragram_error(aPath)
def parse_result():
fValues = _result[MAIN_LOCALIZABLE_FILE]
with open(ERROR_DESPATH, 'w') as ef:
for k, v in _result.items():
if k == MAIN_LOCALIZABLE_FILE:
continue
result = fValues - v
ef.write(k + '\n')
for item in result:
ef.write(item + '\n')
ef.write('\n')
if __name__ == '__main__':
find_from_file(DESPATH)
parse_result()
print('已解析完成,结果保存在桌面中的 checkLocalizable.log 文件中')
|
"""
Quantilization functions and related stuff
"""
from functools import partial
import numpy as np
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
ensure_int64, is_categorical_dtype, is_datetime64_dtype,
is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_integer,
is_scalar, is_timedelta64_dtype)
from pandas.core.dtypes.missing import isna
from pandas import (
Categorical, Index, Interval, IntervalIndex, Series, Timedelta, Timestamp,
to_datetime, to_timedelta)
import pandas.core.algorithms as algos
import pandas.core.nanops as nanops
def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
include_lowest=False, duplicates='raise'):
"""
Bin values into discrete intervals.
Use `cut` when you need to segment and sort data values into bins. This
function is also useful for going from a continuous variable to a
categorical variable. For example, `cut` could convert ages to groups of
age ranges. Supports binning into an equal number of bins, or a
pre-specified array of bins.
Parameters
----------
x : array-like
The input array to be binned. Must be 1-dimensional.
bins : int, sequence of scalars, or pandas.IntervalIndex
The criteria to bin by.
* int : Defines the number of equal-width bins in the range of `x`. The
range of `x` is extended by .1% on each side to include the minimum
and maximum values of `x`.
* sequence of scalars : Defines the bin edges allowing for non-uniform
width. No extension of the range of `x` is done.
* IntervalIndex : Defines the exact bins to be used. Note that
IntervalIndex for `bins` must be non-overlapping.
right : bool, default True
Indicates whether `bins` includes the rightmost edge or not. If
``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]``
indicate (1,2], (2,3], (3,4]. This argument is ignored when
`bins` is an IntervalIndex.
labels : array or bool, optional
Specifies the labels for the returned bins. Must be the same length as
the resulting bins. If False, returns only integer indicators of the
bins. This affects the type of the output container (see below).
This argument is ignored when `bins` is an IntervalIndex.
retbins : bool, default False
Whether to return the bins or not. Useful when bins is provided
as a scalar.
precision : int, default 3
The precision at which to store and display the bins labels.
include_lowest : bool, default False
Whether the first interval should be left-inclusive or not.
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
.. versionadded:: 0.23.0
Returns
-------
out : pandas.Categorical, Series, or ndarray
An array-like object representing the respective bin for each value
of `x`. The type depends on the value of `labels`.
* True (default) : returns a Series for Series `x` or a
pandas.Categorical for all other inputs. The values stored within
are Interval dtype.
* sequence of scalars : returns a Series for Series `x` or a
pandas.Categorical for all other inputs. The values stored within
are whatever the type in the sequence is.
* False : returns an ndarray of integers.
bins : numpy.ndarray or IntervalIndex.
The computed or specified bins. Only returned when `retbins=True`.
For scalar or sequence `bins`, this is an ndarray with the computed
bins. If set `duplicates=drop`, `bins` will drop non-unique bin. For
an IntervalIndex `bins`, this is equal to `bins`.
See Also
--------
qcut : Discretize variable into equal-sized buckets based on rank
or based on sample quantiles.
pandas.Categorical : Array type for storing data that come from a
fixed set of values.
Series : One-dimensional array with axis labels (including time series).
pandas.IntervalIndex : Immutable Index implementing an ordered,
sliceable set.
Notes
-----
Any NA values will be NA in the result. Out of bounds values will be NA in
the resulting Series or pandas.Categorical object.
Examples
--------
Discretize into three equal-sized bins.
>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
... # doctest: +ELLIPSIS
[(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...
Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...
>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
... # doctest: +ELLIPSIS
([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], ...
Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] ...
array([0.994, 3. , 5. , 7. ]))
Discovers the same bins, but assign them specific labels. Notice that
the returned Categorical's categories are `labels` and is ordered.
>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),
... 3, labels=["bad", "medium", "good"])
[bad, good, medium, medium, good, bad]
Categories (3, object): [bad < medium < good]
``labels=False`` implies you just want the bins back.
>>> pd.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3])
Passing a Series as an input returns a Series with categorical dtype:
>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),
... index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s, 3)
... # doctest: +ELLIPSIS
a (1.992, 4.667]
b (1.992, 4.667]
c (4.667, 7.333]
d (7.333, 10.0]
e (7.333, 10.0]
dtype: category
Categories (3, interval[float64]): [(1.992, 4.667] < (4.667, ...
Passing a Series as an input returns a Series with mapping value.
It is used to map numerically to intervals based on bins.
>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),
... index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)
... # doctest: +ELLIPSIS
(a 0.0
b 1.0
c 2.0
d 3.0
e 4.0
dtype: float64, array([0, 2, 4, 6, 8]))
Use `drop` optional when bins is not unique
>>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,
... right=False, duplicates='drop')
... # doctest: +ELLIPSIS
(a 0.0
b 1.0
c 2.0
d 3.0
e 3.0
dtype: float64, array([0, 2, 4, 6, 8]))
Passing an IntervalIndex for `bins` results in those categories exactly.
Notice that values not covered by the IntervalIndex are set to NaN. 0
is to the left of the first bin (which is closed on the right), and 1.5
falls between two bins.
>>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
>>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)
[NaN, (0, 1], NaN, (2, 3], (4, 5]]
Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]
"""
# NOTE: this binning code is changed a bit from histogram for var(x) == 0
# for handling the cut for datetime and timedelta objects
x_is_series, series_index, name, x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
if not np.iterable(bins):
if is_scalar(bins) and bins < 1:
raise ValueError("`bins` should be a positive integer.")
try: # for array-like
sz = x.size
except AttributeError:
x = np.asarray(x)
sz = x.size
if sz == 0:
raise ValueError('Cannot cut empty array')
rng = (nanops.nanmin(x), nanops.nanmax(x))
mn, mx = [mi + 0.0 for mi in rng]
if np.isinf(mn) or np.isinf(mx):
# GH 24314
raise ValueError('cannot specify integer `bins` when input data '
'contains infinity')
elif mn == mx: # adjust end points before binning
mn -= .001 * abs(mn) if mn != 0 else .001
mx += .001 * abs(mx) if mx != 0 else .001
bins = np.linspace(mn, mx, bins + 1, endpoint=True)
else: # adjust end points after binning
bins = np.linspace(mn, mx, bins + 1, endpoint=True)
adj = (mx - mn) * 0.001 # 0.1% of the range
if right:
bins[0] -= adj
else:
bins[-1] += adj
elif isinstance(bins, IntervalIndex):
if bins.is_overlapping:
raise ValueError('Overlapping IntervalIndex is not accepted.')
else:
bins = np.asarray(bins)
bins = _convert_bin_to_numeric_type(bins, dtype)
if (np.diff(bins) < 0).any():
raise ValueError('bins must increase monotonically.')
fac, bins = _bins_to_cuts(x, bins, right=right, labels=labels,
precision=precision,
include_lowest=include_lowest,
dtype=dtype,
duplicates=duplicates)
return _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype)
def qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise'):
"""
Quantile-based discretization function. Discretize variable into
equal-sized buckets based on rank or based on sample quantiles. For example
1000 values for 10 quantiles would produce a Categorical object indicating
quantile membership for each data point.
Parameters
----------
x : 1d ndarray or Series
q : integer or array of quantiles
Number of quantiles. 10 for deciles, 4 for quartiles, etc. Alternately
array of quantiles, e.g. [0, .25, .5, .75, 1.] for quartiles
labels : array or boolean, default None
Used as labels for the resulting bins. Must be of the same length as
the resulting bins. If False, return only integer indicators of the
bins.
retbins : bool, optional
Whether to return the (bins, labels) or not. Can be useful if bins
is given as a scalar.
precision : int, optional
The precision at which to store and display the bins labels
duplicates : {default 'raise', 'drop'}, optional
If bin edges are not unique, raise ValueError or drop non-uniques.
.. versionadded:: 0.20.0
Returns
-------
out : Categorical or Series or array of integers if labels is False
The return type (Categorical or Series) depends on the input: a Series
of type category if input is a Series else Categorical. Bins are
represented as categories when categorical data is returned.
bins : ndarray of floats
Returned only if `retbins` is True.
Notes
-----
Out of bounds values will be NA in the resulting Categorical object
Examples
--------
>>> pd.qcut(range(5), 4)
... # doctest: +ELLIPSIS
[(-0.001, 1.0], (-0.001, 1.0], (1.0, 2.0], (2.0, 3.0], (3.0, 4.0]]
Categories (4, interval[float64]): [(-0.001, 1.0] < (1.0, 2.0] ...
>>> pd.qcut(range(5), 3, labels=["good", "medium", "bad"])
... # doctest: +SKIP
[good, good, medium, bad, bad]
Categories (3, object): [good < medium < bad]
>>> pd.qcut(range(5), 4, labels=False)
array([0, 0, 1, 2, 3])
"""
x_is_series, series_index, name, x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
if is_integer(q):
quantiles = np.linspace(0, 1, q + 1)
else:
quantiles = q
bins = algos.quantile(x, quantiles)
fac, bins = _bins_to_cuts(x, bins, labels=labels,
precision=precision, include_lowest=True,
dtype=dtype, duplicates=duplicates)
return _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype)
def _bins_to_cuts(x, bins, right=True, labels=None,
precision=3, include_lowest=False,
dtype=None, duplicates='raise'):
if duplicates not in ['raise', 'drop']:
raise ValueError("invalid value for 'duplicates' parameter, "
"valid options are: raise, drop")
if isinstance(bins, IntervalIndex):
# we have a fast-path here
ids = bins.get_indexer(x)
result = algos.take_nd(bins, ids)
result = Categorical(result, categories=bins, ordered=True)
return result, bins
unique_bins = algos.unique(bins)
if len(unique_bins) < len(bins) and len(bins) != 2:
if duplicates == 'raise':
raise ValueError("Bin edges must be unique: {bins!r}.\nYou "
"can drop duplicate edges by setting "
"the 'duplicates' kwarg".format(bins=bins))
else:
bins = unique_bins
side = 'left' if right else 'right'
ids = ensure_int64(bins.searchsorted(x, side=side))
if include_lowest:
ids[x == bins[0]] = 1
na_mask = isna(x) | (ids == len(bins)) | (ids == 0)
has_nas = na_mask.any()
if labels is not False:
if labels is None:
labels = _format_labels(bins, precision, right=right,
include_lowest=include_lowest,
dtype=dtype)
else:
if len(labels) != len(bins) - 1:
raise ValueError('Bin labels must be one fewer than '
'the number of bin edges')
if not is_categorical_dtype(labels):
labels = Categorical(labels, categories=labels, ordered=True)
np.putmask(ids, na_mask, 0)
result = algos.take_nd(labels, ids - 1)
else:
result = ids - 1
if has_nas:
result = result.astype(np.float64)
np.putmask(result, na_mask, np.nan)
return result, bins
def _trim_zeros(x):
while len(x) > 1 and x[-1] == '0':
x = x[:-1]
if len(x) > 1 and x[-1] == '.':
x = x[:-1]
return x
def _coerce_to_type(x):
"""
if the passed data is of datetime/timedelta type,
this method converts it to numeric so that cut method can
handle it
"""
dtype = None
if is_datetime64tz_dtype(x):
dtype = x.dtype
elif is_datetime64_dtype(x):
x = to_datetime(x)
dtype = np.datetime64
elif is_timedelta64_dtype(x):
x = to_timedelta(x)
dtype = np.timedelta64
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion
x = np.where(x.notna(), x.view(np.int64), np.nan)
return x, dtype
def _convert_bin_to_numeric_type(bins, dtype):
"""
if the passed bin is of datetime/timedelta type,
this method converts it to integer
Parameters
----------
bins : list-like of bins
dtype : dtype of data
Raises
------
ValueError if bins are not of a compat dtype to dtype
"""
bins_dtype = infer_dtype(bins)
if is_timedelta64_dtype(dtype):
if bins_dtype in ['timedelta', 'timedelta64']:
bins = to_timedelta(bins).view(np.int64)
else:
raise ValueError("bins must be of timedelta64 dtype")
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
if bins_dtype in ['datetime', 'datetime64']:
bins = to_datetime(bins).view(np.int64)
else:
raise ValueError("bins must be of datetime64 dtype")
return bins
def _convert_bin_to_datelike_type(bins, dtype):
"""
Convert bins to a DatetimeIndex or TimedeltaIndex if the orginal dtype is
datelike
Parameters
----------
bins : list-like of bins
dtype : dtype of data
Returns
-------
bins : Array-like of bins, DatetimeIndex or TimedeltaIndex if dtype is
datelike
"""
if is_datetime64tz_dtype(dtype) or is_datetime_or_timedelta_dtype(dtype):
bins = Index(bins.astype(np.int64), dtype=dtype)
return bins
def _format_labels(bins, precision, right=True,
include_lowest=False, dtype=None):
""" based on the dtype, return our labels """
closed = 'right' if right else 'left'
if is_datetime64tz_dtype(dtype):
formatter = partial(Timestamp, tz=dtype.tz)
adjust = lambda x: x - Timedelta('1ns')
elif is_datetime64_dtype(dtype):
formatter = Timestamp
adjust = lambda x: x - Timedelta('1ns')
elif is_timedelta64_dtype(dtype):
formatter = Timedelta
adjust = lambda x: x - Timedelta('1ns')
else:
precision = _infer_precision(precision, bins)
formatter = lambda x: _round_frac(x, precision)
adjust = lambda x: x - 10 ** (-precision)
breaks = [formatter(b) for b in bins]
labels = IntervalIndex.from_breaks(breaks, closed=closed)
if right and include_lowest:
# we will adjust the left hand side by precision to
# account that we are all right closed
v = adjust(labels[0].left)
i = IntervalIndex([Interval(v, labels[0].right, closed='right')])
labels = i.append(labels[1:])
return labels
def _preprocess_for_cut(x):
"""
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
separately
"""
x_is_series = isinstance(x, Series)
series_index = None
name = None
if x_is_series:
series_index = x.index
name = x.name
# Check that the passed array is a Pandas or Numpy object
# We don't want to strip away a Pandas data-type here (e.g. datetimetz)
ndim = getattr(x, 'ndim', None)
if ndim is None:
x = np.asarray(x)
if x.ndim != 1:
raise ValueError("Input array must be 1 dimensional")
return x_is_series, series_index, name, x
def _postprocess_for_cut(fac, bins, retbins, x_is_series,
series_index, name, dtype):
"""
handles post processing for the cut method where
we combine the index information if the originally passed
datatype was a series
"""
if x_is_series:
fac = Series(fac, index=series_index, name=name)
if not retbins:
return fac
bins = _convert_bin_to_datelike_type(bins, dtype)
return fac, bins
def _round_frac(x, precision):
"""
Round the fractional part of the given number
"""
if not np.isfinite(x) or x == 0:
return x
else:
frac, whole = np.modf(x)
if whole == 0:
digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
else:
digits = precision
return np.around(x, digits)
def _infer_precision(base_precision, bins):
"""Infer an appropriate precision for _round_frac
"""
for precision in range(base_precision, 20):
levels = [_round_frac(b, precision) for b in bins]
if algos.unique(levels).size == bins.size:
return precision
return base_precision # default
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 24 18:57:55 2014
@author: zhaoyd
"""
import zipunzip
import update_file
import urllib2
import glob
url='https://codeload.github.com/goagent/goagent/legacy.zip/3.0'
f = urllib2.urlopen(url)
outname=f.headers.dict['content-disposition'].split('=')[1]
if glob.glob('.\\'+outname)==[]:
with open(outname, "wb") as code:
code.write(f.read())
print 'backup proxy.ini ..........................\n'
update_file.moveFileto(r'../local/proxy.ini',r'proxybak')
print 'unzip downloaded file ..........................\n'
zipunzip.unzip_file(outname,r'latest','local')
print 'updating file ..........................\n'
update_file.copyFiles(r'./latest/local',r'../local')
print 'recovery proxy.ini ......................\n'
update_file.moveFileto(r'proxybak',r'./local/proxy.ini')
print 'chmod for specific files'
os.system('./change_mod.sh')
else:
print 'goagent is the latest version'
|
"""
Mask R-CNN
Base Configurations class.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import numpy as np
# Base Configuration Class
# Don't use this class directly. Instead, sub-class it and override
# the configurations you need to change.
class Config(object):
"""Base configuration class. For custom configurations, create a
sub-class that inherits from this one and override properties
that need to be changed.
"""
# Name the configurations. For example, 'COCO', 'Experiment 3', ...etc.
# Useful if your code needs to do things differently depending on which
# experiment is running.
NAME = None # Override in sub-classes
# NUMBER OF GPUs to use. When using only a CPU, this needs to be set to 1.
GPU_COUNT = 1
# Number of images to train with on each GPU. A 12GB GPU can typically
# handle 2 images of 1024x1024px.
# Adjust based on your GPU memory and image sizes. Use the highest
# number that your GPU can handle for best performance.
IMAGES_PER_GPU = 10
# Number of training steps per epoch
# This doesn't need to match the size of the training set. Tensorboard
# updates are saved at the end of each epoch, so setting this to a
# smaller number means getting more frequent TensorBoard updates.
# Validation stats are also calculated at each epoch end and they
# might take a while, so don't set this too small to avoid spending
# a lot of time on validation stats.
STEPS_PER_EPOCH = 1000
# Number of validation steps to run at the end of every training epoch.
# A bigger number improves accuracy of validation stats, but slows
# down the training.
VALIDATION_STEPS = 50
# Backbone network architecture
# Supported values are: resnet50, resnet101.
# You can also provide a callable that should have the signature
# of model.resnet_graph. If you do so, you need to supply a callable
# to COMPUTE_BACKBONE_SHAPE as well
BACKBONE = "resnet101"
# Only useful if you supply a callable to BACKBONE. Should compute
# the shape of each layer of the FPN Pyramid.
# See model.compute_backbone_shapes
COMPUTE_BACKBONE_SHAPE = None
# The strides of each layer of the FPN Pyramid. These values
# are based on a Resnet101 backbone.
BACKBONE_STRIDES = [4, 8, 16, 32, 64]
# Size of the fully-connected layers in the classification graph
FPN_CLASSIF_FC_LAYERS_SIZE = 1024
# Size of the top-down layers used to build the feature pyramid
TOP_DOWN_PYRAMID_SIZE = 256
# Number of classification classes (including background)
NUM_CLASSES = 1 # Override in sub-classes
# Length of square anchor side in pixels
RPN_ANCHOR_SCALES = (32, 64, 128, 256, 512)
# Ratios of anchors at each cell (width/height)
# A value of 1 represents a square anchor, and 0.5 is a wide anchor
RPN_ANCHOR_RATIOS = [0.5, 1, 2]
# Anchor stride
# If 1 then anchors are created for each cell in the backbone feature map.
# If 2, then anchors are created for every other cell, and so on.
RPN_ANCHOR_STRIDE = 1
# Non-max suppression threshold to filter RPN proposals.
# You can increase this during training to generate more propsals.
RPN_NMS_THRESHOLD = 0.7
# How many anchors per image to use for RPN training
RPN_TRAIN_ANCHORS_PER_IMAGE = 256
# ROIs kept after tf.nn.top_k and before non-maximum suppression
PRE_NMS_LIMIT = 6000
# ROIs kept after non-maximum suppression (training and inference)
POST_NMS_ROIS_TRAINING = 2000
POST_NMS_ROIS_INFERENCE = 1000
# If enabled, resizes instance masks to a smaller size to reduce
# memory load. Recommended when using high-resolution images.
USE_MINI_MASK = True
MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask
# Input image resizing
# Generally, use the "square" resizing mode for training and predicting
# and it should work well in most cases. In this mode, images are scaled
# up such that the small side is = IMAGE_MIN_DIM, but ensuring that the
# scaling doesn't make the long side > IMAGE_MAX_DIM. Then the image is
# padded with zeros to make it a square so multiple images can be put
# in one batch.
# Available resizing modes:
# none: No resizing or padding. Return the image unchanged.
# square: Resize and pad with zeros to get a square image
# of size [max_dim, max_dim].
# pad64: Pads width and height with zeros to make them multiples of 64.
# If IMAGE_MIN_DIM or IMAGE_MIN_SCALE are not None, then it scales
# up before padding. IMAGE_MAX_DIM is ignored in this mode.
# The multiple of 64 is needed to ensure smooth scaling of feature
# maps up and down the 6 levels of the FPN pyramid (2**6=64).
# crop: Picks random crops from the image. First, scales the image based
# on IMAGE_MIN_DIM and IMAGE_MIN_SCALE, then picks a random crop of
# size IMAGE_MIN_DIM x IMAGE_MIN_DIM. Can be used in training only.
# IMAGE_MAX_DIM is not used in this mode.
IMAGE_RESIZE_MODE = "square"
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 1024
# Minimum scaling ratio. Checked after MIN_IMAGE_DIM and can force further
# up scaling. For example, if set to 2 then images are scaled up to double
# the width and height, or more, even if MIN_IMAGE_DIM doesn't require it.
# However, in 'square' mode, it can be overruled by IMAGE_MAX_DIM.
IMAGE_MIN_SCALE = 0
# Number of color channels per image. RGB = 3, grayscale = 1, RGB-D = 4
# Changing this requires other changes in the code. See the WIKI for more
# details: https://github.com/matterport/Mask_RCNN/wiki
IMAGE_CHANNEL_COUNT = 3
# Image mean (RGB)
MEAN_PIXEL = np.array([123.7, 116.8, 103.9])
# Number of ROIs per image to feed to classifier/mask heads
# The Mask RCNN paper uses 512 but often the RPN doesn't generate
# enough positive proposals to fill this and keep a positive:negative
# ratio of 1:3. You can increase the number of proposals by adjusting
# the RPN NMS threshold.
TRAIN_ROIS_PER_IMAGE = 200
# Percent of positive ROIs used to train classifier/mask heads
ROI_POSITIVE_RATIO = 0.33
# Pooled ROIs
POOL_SIZE = 7
MASK_POOL_SIZE = 14
# Shape of output mask
# To change this you also need to change the neural network mask branch
MASK_SHAPE = [28, 28]
# Maximum number of ground truth instances to use in one image
MAX_GT_INSTANCES = 100
# Bounding box refinement standard deviation for RPN and final detections.
RPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
# Max number of final detections
DETECTION_MAX_INSTANCES = 100
# Minimum probability value to accept a detected instance
# ROIs below this threshold are skipped
DETECTION_MIN_CONFIDENCE = 0.7
# Non-maximum suppression threshold for detection
DETECTION_NMS_THRESHOLD = 0.3
# Learning rate and momentum
# The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes
# weights to explode. Likely due to differences in optimizer
# implementation.
LEARNING_RATE = 0.001
LEARNING_MOMENTUM = 0.9
# Weight decay regularization
WEIGHT_DECAY = 0.0001
# Loss weights for more precise optimization.
# Can be used for R-CNN training setup.
LOSS_WEIGHTS = {
"rpn_class_loss": 1.,
"rpn_bbox_loss": 1.,
"mrcnn_class_loss": 1.,
"mrcnn_bbox_loss": 1.,
"mrcnn_mask_loss": 1.
}
# Use RPN ROIs or externally generated ROIs for training
# Keep this True for most situations. Set to False if you want to train
# the head branches on ROI generated by code rather than the ROIs from
# the RPN. For example, to debug the classifier head without having to
# train the RPN.
USE_RPN_ROIS = True
# Train or freeze batch normalization layers
# None: Train BN layers. This is the normal mode
# False: Freeze BN layers. Good when using a small batch size
# True: (don't use). Set layer in training mode even when predicting
TRAIN_BN = False # Defaulting to False since batch size is often small
# Gradient norm clipping
GRADIENT_CLIP_NORM = 5.0
def __init__(self):
"""Set values of computed attributes."""
# Effective batch size
self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT
# Input image size
if self.IMAGE_RESIZE_MODE == "crop":
self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM,
self.IMAGE_CHANNEL_COUNT])
else:
self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM,
self.IMAGE_CHANNEL_COUNT])
# Image meta data length
# See compose_image_meta() for details
self.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSES
def display(self):
"""Display Configuration values."""
print("\nConfigurations:")
for a in dir(self):
if not a.startswith("__") and not callable(getattr(self, a)):
print("{:30} {}".format(a, getattr(self, a)))
print("\n")
|
from datetime import datetime
import pytest
from freezegun import freeze_time
from flirror.exceptions import FlirrorConfigError
from flirror.modules import FlirrorModule
from flirror.utils import discover_flirror_modules, parse_interval_string, prettydate
@pytest.mark.parametrize(
"interval_string, result",
[
("5m", (5, "m")),
("10s", (10, "s")),
("6483ms", (6483, "ms")),
("7h", (7, "h")),
("5minutes", (5, "minutes")),
("10seconds", (10, "seconds")),
("7hours", (7, "hours")),
],
)
def test_parse_interval_string(interval_string, result):
assert result == parse_interval_string(interval_string)
@pytest.mark.parametrize("interval_string", ["m5", "5000", "ms"])
def test_parse_interval_string_failed(interval_string):
# TODO (felix): These should not match either:
# - "5 hours"
with pytest.raises(FlirrorConfigError) as excinfo:
parse_interval_string(interval_string)
assert "Could not parse interval string" in str(excinfo.value)
@pytest.mark.parametrize(
"date, expected",
[
("2018-09-17 10:14:59", "just now"),
("2018-09-17 10:12:02", "3 minutes ago"),
("2018-09-17 07:12:02", "3 hours ago"),
("2018-09-15 07:12:02", "2 days ago"),
("2018-06-06 10:25:12", "06. Jun 2018"),
("2015-08-14 16:31:07", "14. Aug 2015"),
],
)
def test_prettydate(date, expected):
date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") # .replace(tzinfo=timezone.utc)
with freeze_time("2018-09-17 10:15:04"):
assert expected == prettydate(date)
def test_discover_flirror_modules():
module_1 = FlirrorModule("module_1", __name__)
module_2 = FlirrorModule("module_2", __name__)
module_3 = FlirrorModule("module_3", __name__)
# As we are mainly relying on the functionality of getattr(), we could mock
# a plugin module with a simple class providing the necessary attributes.
class valid_plugin:
FLIRROR_MODULE = module_1
FLIRROR_MODULES = [module_2, module_3]
flirror_modules = discover_flirror_modules({"valid_plugin": valid_plugin})
# We assume that all modules are valid modules because they are all
# instances of FlirrorModule.
assert len(flirror_modules) == 3
assert flirror_modules == [module_1, module_2, module_3]
def test_discover_flirror_modules_missing_variables():
class invalid_plugin:
some_variable = "abc"
NO_FLIRROR_MODULE = 5
flirror_modules = discover_flirror_modules({"invalid_plugin": invalid_plugin})
# As the module does not provide the necessary variables, no modules could
# be loaded.
assert flirror_modules == []
def test_discover_flirror_modules_wrong_values():
module_1 = FlirrorModule("module_1", __name__)
module_2 = FlirrorModule("module_2", __name__)
class invalid_plugin:
FLIRROR_MODULE = [module_1]
FLIRROR_MODULES = [5, module_2, "abc"]
flirror_modules = discover_flirror_modules({"invalid_plugin": invalid_plugin})
# FLIRROR_MODULE cannot be loaded as it does not provide a single element.
# FLIRROR_MODULES contains some invalid module (not instance of
# FlirrorModule). Thus, only module_2 is discovered in the end.
assert flirror_modules == [module_2]
|
#ifndef MATCHBOXDB_PAGE_CACHE_H
#define MATCHBOXDB_PAGE_CACHE_H
#include <cstdint>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include "../storage/streamutils.h"
#include "metadata_page.h"
#include "page.h"
#include "slotted_data_page.h"
namespace page {
class PageDefragger;
}
namespace page_cache {
class PageCache {
public:
static PageCache scan_and_build_page_cache(uint32_t max_size, const std::string &data_path_root);
PageCache(uint32_t max_size, const std::vector<std::string> &tables);
page::Page *get_page_id(page::PageId page_id, const std::string &table_name, page::PageType page_type);
page::SlottedDataPage *get_page_for_data_size(const std::string &table_name, uint32_t data_size);
uint32_t next_row_id_for_table(const std::string &table_name);
page::MetadataPage *metadata_page_for_table(const std::string &table_name);
metadata::Metadata metadata_for_table(const std::string &table_name);
void write_dirty_pages(const std::string &table_name);
std::vector<page::Page *> enumerate_pages(const std::string &table_name, page::PageType page_type);
void mark_page_dirty(const std::string &table_name, page::Page *page, bool add_to_defrag_list);
void add_new_table(const std::string &table_name);
std::vector<std::string> table_names();
void enable_page_defrag(page::PageDefragger *page_defragger);
protected:
void scan_tables();
void scan_table_file(const std::string &table_name, const std::string &file_name);
virtual std::string evict();
std::unique_ptr<page::Page>
load_page_from_disk(page::PageId page_id, const std::string &table_name, page::PageType page_type);
protected:
uint32_t _max_size{};
std::unordered_map<std::string, std::unordered_set<page::Page *>> _dirty_pages{};
std::unordered_map<std::string, std::string> _table_file_names{};
std::unordered_map<std::string, std::vector<page::FreePageInfo>> _free_data_pages{};
std::list<std::pair<std::string, std::unique_ptr<page::Page>>> _page_ids{};
std::unordered_map<std::string, decltype(_page_ids.begin())> _pages{};
std::unordered_map<std::string, std::unordered_map<page::PageType, std::vector<page::PageId>>> _page_directories{};
void scan_free_pages_in_table_stream(const std::string &table_name, std::istream &is, uint32_t n_pages_to_scan);
void handle_missing_cache_entry(unsigned int page_id, const std::string &table_name, page::PageType &page_type,
const std::string &key);
static std::unique_ptr<page::Page>
make_page_from_buffer(const page::PageType &page_type, const stream_utils::ByteBuffer &buffer);
std::optional<page::PageId>
get_page_id_for_size(const std::string &table_name, uint32_t data_size, page::PageType page_type);
std::optional<page::PageDefragger*> _page_defragger{};
};
std::string generate_cache_key(page::PageId page_id, const std::string &table_name, page::PageType page_type);
}
#endif //MATCHBOXDB_PAGE_CACHE_H
|
/**
* This class is the base for `Binding` and `MultiBinding`.
* @private
*/
Ext.define('Ext.app.bind.BaseBinding', {
extend: 'Ext.util.Schedulable',
calls: 0,
kind: 20,
defaultOptions: {},
lastValue: undefined,
/**
* @cfg {Boolean} [single=false]
* This option instructs the binding to call its `destroy` method immediately after
* delivering the initial value.
* @since 5.0.0
*/
constructor: function (owner, callback, scope, options) {
var me = this;
me.options = options;
me.owner = owner;
me.scope = scope;
me.callback = callback;
//<debug>
if (!callback) {
Ext.raise('Callback is required');
}
//</debug>
// If given a string callback name, preserve the late binding:
me.lateBound = Ext.isString(callback);
if (options && options.deep) {
me.deep = true;
}
me.callParent();
},
destroy: function () {
var me = this,
owner = me.owner;
if (owner) {
owner.onBindDestroy(me);
}
me.callParent();
me.scope = me.callback = me.owner = null;
},
isReadOnly: function () {
return true;
},
privates: {
getScheduler: function () {
var owner = this.owner;
return owner && owner.getScheduler();
},
getSession: function () {
var owner = this.owner;
return owner.isSession ? owner : owner.getSession();
},
notify: function (value) {
var me = this,
options = me.options || me.defaultOptions,
previous = me.lastValue;
// We want to deliver if:
// 1) We've never been called
// 2) We're a deep binding, which means that our object reference may not have changed,
// but something under us has changed. For example a link stub or a model field binding
// 3) If the value has changed
// 4) If the value is an array. It's difficult to tell if the underlying data changed
if (!me.calls || me.deep || me.valueChanged(value, previous)) {
++me.calls;
me.lastValue = value;
if (me.lateBound) {
// Interestingly, lateBound-ness may be more efficient since it does
// not use the "call" method.
me.scope[me.callback](value, previous, me);
} else {
me.callback.call(me.scope, value, previous, me);
}
if (options.single) {
me.destroy();
}
}
},
valueChanged: function (value, previous) {
var ret = true;
if (previous !== value) {
if (value && previous && value instanceof Date && previous instanceof Date) {
ret = value.getTime() !== previous.getTime();
}
} else {
ret = Ext.isArray(value);
}
return ret;
}
}
});
|
const {createHash} = require('crypto');
const asyncAuto = require('async/auto');
const {getInvoice} = require('ln-service');
const {returnResult} = require('asyncjs-util');
const {shuffle} = require('lodash');
const swapParameters = require('./swap_parameters');
const {getConfirmationCount} = require('./../chain');
const {getBlockPlacement} = require('./../blocks');
const getDetectedSwaps = require('./../pool/get_detected_swaps');
const getSwapStatus = require('./get_swap_status');
const {lightningDaemon} = require('./../lightning');
const {parsePaymentRequest} = require('./../lightning');
/** Check the status of a swap
This will attempt to execute the swap if it detects a funded swap.
{
cache: <Cache Name String>
invoice: <Lightning Invoice String>
network: <Chain Network Name String>
script: <Redeem Script Hex String>
}
@returns via cbk or Promise
{
[output_index]: <Output Index Of Funding Output Number>
[output_tokens]: <Output Tokens Value For Funding Output Number>
[payment_secret]: <Payment Secret Hex String> // With claim present
transaction_id: <Funding Transaction Id Hex String>
[wait_time_ms]: <Time To Wait Number> // With funding pending
}
*/
module.exports = ({cache, invoice, network, script}, cbk) => {
return new Promise((resolve, reject) => {
return asyncAuto({
// Check arguments
validate: cbk => {
if (!cache) {
return cbk([400, 'ExpectedCacheForSwapDetails']);
}
if (!invoice) {
return cbk([400, 'ExpectedInvoice']);
}
if (!network) {
return cbk([400, 'ExpectedNetwork']);
}
if (!script) {
return cbk([400, 'ExpectedRedeemScript']);
}
return cbk();
},
// Parsed invoice
invoiceInfo: ['validate', ({}, cbk) => {
try {
return cbk(null, parsePaymentRequest({request: invoice}));
} catch (err) {
return cbk([400, 'FailedToParseSwapInvoice', err]);
}
}],
// Invoice id
id: ['invoiceInfo', ({invoiceInfo}, cbk) => cbk(null, invoiceInfo.id)],
// Lnd for invoice
lnd: ['invoiceInfo', ({invoiceInfo}, cbk) => {
try {
return cbk(null, lightningDaemon({network: invoiceInfo.network}));
} catch (err) {
return cbk(null, [500, 'FailedToCreateLndConnection', err]);
}
}],
// Get swap attempt in progress
getSwapAttempt: ['id', 'lnd', ({id, lnd}, cbk) => {
const swapId = Buffer.from(id, 'hex');
const attemptId = createHash('sha256').update(swapId).digest('hex');
return getInvoice({lnd, id: attemptId}, (err, details) => {
if (!!err) {
return cbk();
}
return cbk(null, details.expires_at);
});
}],
// See if the swap is in the swap pool
getSwapFromPool: ['id', ({id}, cbk) => {
return getDetectedSwaps({cache, id}, cbk);
}],
// See if we have a related swap element
swapElement: ['getSwapFromPool', ({getSwapFromPool}, cbk) => {
const elements = getSwapFromPool;
const {attempt} = getSwapFromPool;
const [claim] = elements.claim;
const [funding] = elements.funding.filter(({block}) => !!block);
const [unconfirmed] = elements.funding.filter(({block}) => !block);
if (!!claim) {
return cbk(null, {
payment_secret: claim.preimage,
transaction_id: claim.outpoint.split(':')[0],
});
}
if (!!funding) {
return cbk(null, {
attempts: !attempt ? 0 : attempt.length,
block: funding.block,
output_index: funding.vout,
output_tokens: funding.tokens,
transaction_id: funding.id,
});
}
if (!!unconfirmed) {
return cbk(null, {
attempts: !attempt ? 0 : attempt.length,
output_index: unconfirmed.vout,
output_tokens: unconfirmed.tokens,
transaction_id: unconfirmed.id,
});
}
return cbk();
}],
// Check for swap attempt failure
checkSwapAttempt: [
'getSwapAttempt',
'swapElement',
({getSwapAttempt, swapElement}, cbk) =>
{
if (!getSwapAttempt) {
return cbk();
}
if (!!swapElement && !!swapElement.payment_secret) {
return cbk();
}
return cbk();
}],
// Determine confirmation count
getBlockInfo: ['swapElement', ({swapElement}, cbk) => {
// Exit early when there is no need to look up block details
if (!swapElement || !swapElement.block) {
return cbk();
}
const {block} = swapElement;
return getBlockPlacement({block, cache, network}, cbk);
}],
// Determine wait time still necessary to confirm the swap
remainingConfs: ['getBlockInfo', ({getBlockInfo}, cbk) => {
const blockInfo = getBlockInfo || {};
const confs = blockInfo.current_confirmation_count || 0;
try {
const requiredFundingConfs = swapParameters({network}).funding_confs;
return cbk(null, Math.max(0, requiredFundingConfs - confs));
} catch (err) {
return cbk([500, 'FailedToDetermineWaitConfirmations', {err}]);
}
}],
// Current swap status
getSwapStatus: [
'remainingConfs',
'swapElement',
({remainingConfs, swapElement}, cbk) =>
{
if (!swapElement) {
return cbk([402, 'FundingNotFound']);
}
return cbk(null, {
attempts: swapElement.attempts,
conf_wait_count: !!remainingConfs ? remainingConfs : null,
output_index: swapElement.output_index,
output_tokens: swapElement.output_tokens,
payment_secret: swapElement.payment_secret,
transaction_id: swapElement.transaction_id,
});
}],
},
returnResult({reject, resolve, of: 'getSwapStatus'}, cbk));
});
};
|
'use strict'
const assert = require('assert')
const sinon = require('sinon')
const EventEmitter = require('events')
const { ListenerInterface } = require('../../../lib/listeners')
const LogCommandListener = require('../../../lib/logger/log-command-listener')
describe('log-command-listener', function () {
beforeEach(function () {
this.sandbox = sinon.createSandbox()
this.emitter = new EventEmitter()
this.logCommandListener = new LogCommandListener(this.emitter)
})
afterEach(function () {
this.sandbox.restore()
})
it('should be an instace of ListenerInterface', function () {
assert.ok(this.logCommandListener instanceof ListenerInterface)
})
it('.listen() should attach listener to message emitter', function () {
const reopenFileStreamsSpy = this.sandbox.spy()
const msg = 'logger:reopen-file-streams'
this.logCommandListener.listen(reopenFileStreamsSpy)
this.emitter.emit('message', msg)
assert.ok(reopenFileStreamsSpy.withArgs(msg).calledOnce)
})
})
|
const isDev = process.env.NODE_ENV === "development";
const origin = isDev ? "http://localhost:7778" : "";
const basePath = window.location.pathname.replace(/\/$/, "");
const API_URL = `${origin}${basePath}${isDev ? "" : "/api"}`;
function maybeGetAuthHeader() {
let petioJwt = localStorage.getItem("petio_jwt");
if (petioJwt) {
return { Authorization: `Bearer ${petioJwt}` };
} else {
return {};
}
}
export class HttpError extends Error {
constructor(statusCode) {
super(`API returned status code ${statusCode}`);
this.statusCode = statusCode;
}
}
function parseResponse(response) {
if (response.ok) {
return response
.clone()
.json()
.catch(() => response.text());
}
throw new HttpError(response.status);
}
export function get(path, options = {}) {
const mergedOptions = {
credentials: "include",
...options,
headers: {
...maybeGetAuthHeader(),
...options.headers,
},
};
return fetch(API_URL + path, mergedOptions).then(parseResponse);
}
export function post(path, data, options = {}) {
const mergedOptions = {
credentials: "include",
method: "POST",
...options,
headers: {
"Content-Type": "application/json",
...maybeGetAuthHeader(),
...options.headers,
},
body: JSON.stringify(data),
};
return fetch(API_URL + path, mergedOptions).then(parseResponse);
}
export function put(path, data, options = {}) {
const mergedOptions = {
credentials: "include",
method: "PUT",
...options,
headers: {
"Content-Type": "application/json",
...maybeGetAuthHeader(),
...options.headers,
},
body: JSON.stringify(data),
};
return fetch(API_URL + path, mergedOptions).then(parseResponse);
}
export function del(path, options = {}) {
const mergedOptions = {
credentials: "include",
method: "DELETE",
...options,
headers: {
...maybeGetAuthHeader(),
...options.headers,
},
};
return fetch(API_URL + path, mergedOptions).then(parseResponse);
}
|
import BoundingRectangle from '../Core/BoundingRectangle.js';
import Check from '../Core/Check.js';
import Color from '../Core/Color.js';
import defined from '../Core/defined.js';
import destroyObject from '../Core/destroyObject.js';
import DeveloperError from '../Core/DeveloperError.js';
import PrimitiveType from '../Core/PrimitiveType.js';
import ViewportQuadVS from '../Shaders/ViewportQuadVS.js';
import ClearCommand from './ClearCommand.js';
import DrawCommand from './DrawCommand.js';
import Framebuffer from './Framebuffer.js';
import RenderState from './RenderState.js';
import ShaderProgram from './ShaderProgram.js';
/**
* @private
*/
function ComputeEngine(context) {
this._context = context;
}
var renderStateScratch;
var drawCommandScratch = new DrawCommand({
primitiveType : PrimitiveType.TRIANGLES
});
var clearCommandScratch = new ClearCommand({
color : new Color(0.0, 0.0, 0.0, 0.0)
});
function createFramebuffer(context, outputTexture) {
return new Framebuffer({
context : context,
colorTextures : [outputTexture],
destroyAttachments : false
});
}
function createViewportQuadShader(context, fragmentShaderSource) {
return ShaderProgram.fromCache({
context : context,
vertexShaderSource : ViewportQuadVS,
fragmentShaderSource : fragmentShaderSource,
attributeLocations : {
position : 0,
textureCoordinates : 1
}
});
}
function createRenderState(width, height) {
if ((!defined(renderStateScratch)) ||
(renderStateScratch.viewport.width !== width) ||
(renderStateScratch.viewport.height !== height)) {
renderStateScratch = RenderState.fromCache({
viewport : new BoundingRectangle(0, 0, width, height)
});
}
return renderStateScratch;
}
ComputeEngine.prototype.execute = function(computeCommand) {
//>>includeStart('debug', pragmas.debug);
Check.defined('computeCommand', computeCommand);
//>>includeEnd('debug');
// This may modify the command's resources, so do error checking afterwards
if (defined(computeCommand.preExecute)) {
computeCommand.preExecute(computeCommand);
}
//>>includeStart('debug', pragmas.debug);
if (!defined(computeCommand.fragmentShaderSource) && !defined(computeCommand.shaderProgram)) {
throw new DeveloperError('computeCommand.fragmentShaderSource or computeCommand.shaderProgram is required.');
}
Check.defined('computeCommand.outputTexture', computeCommand.outputTexture);
//>>includeEnd('debug');
var outputTexture = computeCommand.outputTexture;
var width = outputTexture.width;
var height = outputTexture.height;
var context = this._context;
var vertexArray = defined(computeCommand.vertexArray) ? computeCommand.vertexArray : context.getViewportQuadVertexArray();
var shaderProgram = defined(computeCommand.shaderProgram) ? computeCommand.shaderProgram : createViewportQuadShader(context, computeCommand.fragmentShaderSource);
var framebuffer = createFramebuffer(context, outputTexture);
var renderState = createRenderState(width, height);
var uniformMap = computeCommand.uniformMap;
var clearCommand = clearCommandScratch;
clearCommand.framebuffer = framebuffer;
clearCommand.renderState = renderState;
clearCommand.execute(context);
var drawCommand = drawCommandScratch;
drawCommand.vertexArray = vertexArray;
drawCommand.renderState = renderState;
drawCommand.shaderProgram = shaderProgram;
drawCommand.uniformMap = uniformMap;
drawCommand.framebuffer = framebuffer;
drawCommand.execute(context);
framebuffer.destroy();
if (!computeCommand.persists) {
shaderProgram.destroy();
if (defined(computeCommand.vertexArray)) {
vertexArray.destroy();
}
}
if (defined(computeCommand.postExecute)) {
computeCommand.postExecute(outputTexture);
}
};
ComputeEngine.prototype.isDestroyed = function() {
return false;
};
ComputeEngine.prototype.destroy = function() {
return destroyObject(this);
};
export default ComputeEngine;
|
import functools
import itertools
import logging
import os
import signal
import subprocess
import sys
import threading
import time
import traceback
import weakref
from collections import defaultdict
from pathlib import Path
from types import ModuleType
from zipimport import zipimporter
import django
from django.apps import apps
from django.core.signals import request_finished
from django.dispatch import Signal
from django.utils.functional import cached_property
from django.utils.version import get_version_tuple
autoreload_started = Signal()
file_changed = Signal()
DJANGO_AUTORELOAD_ENV = 'RUN_MAIN'
logger = logging.getLogger('django.utils.autoreload')
# If an error is raised while importing a file, it's not placed in sys.modules.
# This means that any future modifications aren't caught. Keep a list of these
# file paths to allow watching them in the future.
_error_files = []
_exception = None
try:
import termios
except ImportError:
termios = None
try:
import pywatchman
except ImportError:
pywatchman = None
def is_django_module(module):
"""Return True if the given module is nested under Django."""
return module.__name__.startswith('django.')
def is_django_path(path):
"""Return True if the given file path is nested under Django."""
return Path(django.__file__).parent in Path(path).parents
def check_errors(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
global _exception
try:
fn(*args, **kwargs)
except Exception:
_exception = sys.exc_info()
et, ev, tb = _exception
if getattr(ev, 'filename', None) is None:
# get the filename from the last item in the stack
filename = traceback.extract_tb(tb)[-1][0]
else:
filename = ev.filename
if filename not in _error_files:
_error_files.append(filename)
raise
return wrapper
def raise_last_exception():
global _exception
if _exception is not None:
raise _exception[1]
def ensure_echo_on():
"""
Ensure that echo mode is enabled. Some tools such as PDB disable
it which causes usability issues after reload.
"""
if not termios or not sys.stdin.isatty():
return
attr_list = termios.tcgetattr(sys.stdin)
if not attr_list[3] & termios.ECHO:
attr_list[3] |= termios.ECHO
if hasattr(signal, 'SIGTTOU'):
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
else:
old_handler = None
termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list)
if old_handler is not None:
signal.signal(signal.SIGTTOU, old_handler)
def iter_all_python_module_files():
# This is a hot path during reloading. Create a stable sorted list of
# modules based on the module name and pass it to iter_modules_and_files().
# This ensures cached results are returned in the usual case that modules
# aren't loaded on the fly.
keys = sorted(sys.modules)
modules = tuple(m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes))
return iter_modules_and_files(modules, frozenset(_error_files))
@functools.lru_cache(maxsize=1)
def iter_modules_and_files(modules, extra_files):
"""Iterate through all modules needed to be watched."""
sys_file_paths = []
for module in modules:
# During debugging (with PyDev) the 'typing.io' and 'typing.re' objects
# are added to sys.modules, however they are types not modules and so
# cause issues here.
if not isinstance(module, ModuleType):
continue
if module.__name__ == '__main__':
# __main__ (usually manage.py) doesn't always have a __spec__ set.
# Handle this by falling back to using __file__, resolved below.
# See https://docs.python.org/reference/import.html#main-spec
# __file__ may not exists, e.g. when running ipdb debugger.
if hasattr(module, '__file__'):
sys_file_paths.append(module.__file__)
continue
if getattr(module, '__spec__', None) is None:
continue
spec = module.__spec__
# Modules could be loaded from places without a concrete location. If
# this is the case, skip them.
if spec.has_location:
origin = spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin
sys_file_paths.append(origin)
results = set()
for filename in itertools.chain(sys_file_paths, extra_files):
if not filename:
continue
path = Path(filename)
try:
resolved_path = path.resolve(strict=True).absolute()
except FileNotFoundError:
# The module could have been removed, don't fail loudly if this
# is the case.
continue
except ValueError as e:
# Network filesystems may return null bytes in file paths.
logger.debug('"%s" raised when resolving path: "%s"', e, path)
continue
results.add(resolved_path)
return frozenset(results)
@functools.lru_cache(maxsize=1)
def common_roots(paths):
"""
Return a tuple of common roots that are shared between the given paths.
File system watchers operate on directories and aren't cheap to create.
Try to find the minimum set of directories to watch that encompass all of
the files that need to be watched.
"""
# Inspired from Werkzeug:
# https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py
# Create a sorted list of the path components, longest first.
path_parts = sorted([x.parts for x in paths], key=len, reverse=True)
tree = {}
for chunks in path_parts:
node = tree
# Add each part of the path to the tree.
for chunk in chunks:
node = node.setdefault(chunk, {})
# Clear the last leaf in the tree.
node.clear()
# Turn the tree into a list of Path instances.
def _walk(node, path):
for prefix, child in node.items():
yield from _walk(child, path + (prefix,))
if not node:
yield Path(*path)
return tuple(_walk(tree, ()))
def sys_path_directories():
"""
Yield absolute directories from sys.path, ignoring entries that don't
exist.
"""
for path in sys.path:
path = Path(path)
try:
resolved_path = path.resolve(strict=True).absolute()
except FileNotFoundError:
continue
# If the path is a file (like a zip file), watch the parent directory.
if resolved_path.is_file():
yield resolved_path.parent
else:
yield resolved_path
def get_child_arguments():
"""
Return the executable. This contains a workaround for Windows if the
executable is reported to not have the .exe extension which can cause bugs
on reloading.
"""
import django.__main__
django_main_path = Path(django.__main__.__file__)
py_script = Path(sys.argv[0])
args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions]
if py_script == django_main_path:
# The server was started with `python -m django runserver`.
args += ['-m', 'django']
args += sys.argv[1:]
elif not py_script.exists():
# sys.argv[0] may not exist for several reasons on Windows.
# It may exist with a .exe extension or have a -script.py suffix.
exe_entrypoint = py_script.with_suffix('.exe')
if exe_entrypoint.exists():
# Should be executed directly, ignoring sys.executable.
return [exe_entrypoint, *sys.argv[1:]]
script_entrypoint = py_script.with_name('%s-script.py' % py_script.name)
if script_entrypoint.exists():
# Should be executed as usual.
return [*args, script_entrypoint, *sys.argv[1:]]
raise RuntimeError('Script %s does not exist.' % py_script)
else:
args += sys.argv
return args
def trigger_reload(filename):
logger.info('%s changed, reloading.', filename)
sys.exit(3)
def restart_with_reloader():
new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: 'true'}
args = get_child_arguments()
while True:
p = subprocess.run(args, env=new_environ, close_fds=False)
if p.returncode != 3:
return p.returncode
class BaseReloader:
def __init__(self):
self.extra_files = set()
self.directory_globs = defaultdict(set)
self._stop_condition = threading.Event()
def watch_dir(self, path, glob):
path = Path(path)
try:
path = path.absolute()
except FileNotFoundError:
logger.debug(
'Unable to watch directory %s as it cannot be resolved.',
path,
exc_info=True,
)
return
logger.debug('Watching dir %s with glob %s.', path, glob)
self.directory_globs[path].add(glob)
def watched_files(self, include_globs=True):
"""
Yield all files that need to be watched, including module files and
files within globs.
"""
yield from iter_all_python_module_files()
yield from self.extra_files
if include_globs:
for directory, patterns in self.directory_globs.items():
for pattern in patterns:
yield from directory.glob(pattern)
def wait_for_apps_ready(self, app_reg, django_main_thread):
"""
Wait until Django reports that the apps have been loaded. If the given
thread has terminated before the apps are ready, then a SyntaxError or
other non-recoverable error has been raised. In that case, stop waiting
for the apps_ready event and continue processing.
Return True if the thread is alive and the ready event has been
triggered, or False if the thread is terminated while waiting for the
event.
"""
while django_main_thread.is_alive():
if app_reg.ready_event.wait(timeout=0.1):
return True
else:
logger.debug('Main Django thread has terminated before apps are ready.')
return False
def run(self, django_main_thread):
logger.debug('Waiting for apps ready_event.')
self.wait_for_apps_ready(apps, django_main_thread)
from django.urls import get_resolver
# Prevent a race condition where URL modules aren't loaded when the
# reloader starts by accessing the urlconf_module property.
try:
get_resolver().urlconf_module
except Exception:
# Loading the urlconf can result in errors during development.
# If this occurs then swallow the error and continue.
pass
logger.debug('Apps ready_event triggered. Sending autoreload_started signal.')
autoreload_started.send(sender=self)
self.run_loop()
def run_loop(self):
ticker = self.tick()
while not self.should_stop:
try:
next(ticker)
except StopIteration:
break
self.stop()
def tick(self):
"""
This generator is called in a loop from run_loop. It's important that
the method takes care of pausing or otherwise waiting for a period of
time. This split between run_loop() and tick() is to improve the
testability of the reloader implementations by decoupling the work they
do from the loop.
"""
raise NotImplementedError('subclasses must implement tick().')
@classmethod
def check_availability(cls):
raise NotImplementedError('subclasses must implement check_availability().')
def notify_file_changed(self, path):
results = file_changed.send(sender=self, file_path=path)
logger.debug('%s notified as changed. Signal results: %s.', path, results)
if not any(res[1] for res in results):
trigger_reload(path)
# These are primarily used for testing.
@property
def should_stop(self):
return self._stop_condition.is_set()
def stop(self):
self._stop_condition.set()
class StatReloader(BaseReloader):
SLEEP_TIME = 1 # Check for changes once per second.
def tick(self):
mtimes = {}
while True:
for filepath, mtime in self.snapshot_files():
old_time = mtimes.get(filepath)
mtimes[filepath] = mtime
if old_time is None:
logger.debug('File %s first seen with mtime %s', filepath, mtime)
continue
elif mtime > old_time:
logger.debug('File %s previous mtime: %s, current mtime: %s', filepath, old_time, mtime)
self.notify_file_changed(filepath)
time.sleep(self.SLEEP_TIME)
yield
def snapshot_files(self):
# watched_files may produce duplicate paths if globs overlap.
seen_files = set()
for file in self.watched_files():
if file in seen_files:
continue
try:
mtime = file.stat().st_mtime
except OSError:
# This is thrown when the file does not exist.
continue
seen_files.add(file)
yield file, mtime
@classmethod
def check_availability(cls):
return True
class WatchmanUnavailable(RuntimeError):
pass
class WatchmanReloader(BaseReloader):
def __init__(self):
self.roots = defaultdict(set)
self.processed_request = threading.Event()
self.client_timeout = int(os.environ.get('DJANGO_WATCHMAN_TIMEOUT', 5))
super().__init__()
@cached_property
def client(self):
return pywatchman.client(timeout=self.client_timeout)
def _watch_root(self, root):
# In practice this shouldn't occur, however, it's possible that a
# directory that doesn't exist yet is being watched. If it's outside of
# sys.path then this will end up a new root. How to handle this isn't
# clear: Not adding the root will likely break when subscribing to the
# changes, however, as this is currently an internal API, no files
# will be being watched outside of sys.path. Fixing this by checking
# inside watch_glob() and watch_dir() is expensive, instead this could
# could fall back to the StatReloader if this case is detected? For
# now, watching its parent, if possible, is sufficient.
if not root.exists():
if not root.parent.exists():
logger.warning('Unable to watch root dir %s as neither it or its parent exist.', root)
return
root = root.parent
result = self.client.query('watch-project', str(root.absolute()))
if 'warning' in result:
logger.warning('Watchman warning: %s', result['warning'])
logger.debug('Watchman watch-project result: %s', result)
return result['watch'], result.get('relative_path')
@functools.lru_cache()
def _get_clock(self, root):
return self.client.query('clock', root)['clock']
def _subscribe(self, directory, name, expression):
root, rel_path = self._watch_root(directory)
# Only receive notifications of files changing, filtering out other types
# like special files: https://facebook.github.io/watchman/docs/type
only_files_expression = [
'allof',
['anyof', ['type', 'f'], ['type', 'l']],
expression
]
query = {
'expression': only_files_expression,
'fields': ['name'],
'since': self._get_clock(root),
'dedup_results': True,
}
if rel_path:
query['relative_root'] = rel_path
logger.debug('Issuing watchman subscription %s, for root %s. Query: %s', name, root, query)
self.client.query('subscribe', root, name, query)
def _subscribe_dir(self, directory, filenames):
if not directory.exists():
if not directory.parent.exists():
logger.warning('Unable to watch directory %s as neither it or its parent exist.', directory)
return
prefix = 'files-parent-%s' % directory.name
filenames = ['%s/%s' % (directory.name, filename) for filename in filenames]
directory = directory.parent
expression = ['name', filenames, 'wholename']
else:
prefix = 'files'
expression = ['name', filenames]
self._subscribe(directory, '%s:%s' % (prefix, directory), expression)
def _watch_glob(self, directory, patterns):
"""
Watch a directory with a specific glob. If the directory doesn't yet
exist, attempt to watch the parent directory and amend the patterns to
include this. It's important this method isn't called more than one per
directory when updating all subscriptions. Subsequent calls will
overwrite the named subscription, so it must include all possible glob
expressions.
"""
prefix = 'glob'
if not directory.exists():
if not directory.parent.exists():
logger.warning('Unable to watch directory %s as neither it or its parent exist.', directory)
return
prefix = 'glob-parent-%s' % directory.name
patterns = ['%s/%s' % (directory.name, pattern) for pattern in patterns]
directory = directory.parent
expression = ['anyof']
for pattern in patterns:
expression.append(['match', pattern, 'wholename'])
self._subscribe(directory, '%s:%s' % (prefix, directory), expression)
def watched_roots(self, watched_files):
extra_directories = self.directory_globs.keys()
watched_file_dirs = [f.parent for f in watched_files]
sys_paths = list(sys_path_directories())
return frozenset((*extra_directories, *watched_file_dirs, *sys_paths))
def _update_watches(self):
watched_files = list(self.watched_files(include_globs=False))
found_roots = common_roots(self.watched_roots(watched_files))
logger.debug('Watching %s files', len(watched_files))
logger.debug('Found common roots: %s', found_roots)
# Setup initial roots for performance, shortest roots first.
for root in sorted(found_roots):
self._watch_root(root)
for directory, patterns in self.directory_globs.items():
self._watch_glob(directory, patterns)
# Group sorted watched_files by their parent directory.
sorted_files = sorted(watched_files, key=lambda p: p.parent)
for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent):
# These paths need to be relative to the parent directory.
self._subscribe_dir(directory, [str(p.relative_to(directory)) for p in group])
def update_watches(self):
try:
self._update_watches()
except Exception as ex:
# If the service is still available, raise the original exception.
if self.check_server_status(ex):
raise
def _check_subscription(self, sub):
subscription = self.client.getSubscription(sub)
if not subscription:
return
logger.debug('Watchman subscription %s has results.', sub)
for result in subscription:
# When using watch-project, it's not simple to get the relative
# directory without storing some specific state. Store the full
# path to the directory in the subscription name, prefixed by its
# type (glob, files).
root_directory = Path(result['subscription'].split(':', 1)[1])
logger.debug('Found root directory %s', root_directory)
for file in result.get('files', []):
self.notify_file_changed(root_directory / file)
def request_processed(self, **kwargs):
logger.debug('Request processed. Setting update_watches event.')
self.processed_request.set()
def tick(self):
request_finished.connect(self.request_processed)
self.update_watches()
while True:
if self.processed_request.is_set():
self.update_watches()
self.processed_request.clear()
try:
self.client.receive()
except pywatchman.SocketTimeout:
pass
except pywatchman.WatchmanError as ex:
logger.debug('Watchman error: %s, checking server status.', ex)
self.check_server_status(ex)
else:
for sub in list(self.client.subs.keys()):
self._check_subscription(sub)
yield
# Protect against busy loops.
time.sleep(0.1)
def stop(self):
self.client.close()
super().stop()
def check_server_status(self, inner_ex=None):
"""Return True if the server is available."""
try:
self.client.query('version')
except Exception:
raise WatchmanUnavailable(str(inner_ex)) from inner_ex
return True
@classmethod
def check_availability(cls):
if not pywatchman:
raise WatchmanUnavailable('pywatchman not installed.')
client = pywatchman.client(timeout=0.1)
try:
result = client.capabilityCheck()
except Exception:
# The service is down?
raise WatchmanUnavailable('Cannot connect to the watchman service.')
version = get_version_tuple(result['version'])
# Watchman 4.9 includes multiple improvements to watching project
# directories as well as case insensitive filesystems.
logger.debug('Watchman version %s', version)
if version < (4, 9):
raise WatchmanUnavailable('Watchman 4.9 or later is required.')
def get_reloader():
"""Return the most suitable reloader for this environment."""
try:
WatchmanReloader.check_availability()
except WatchmanUnavailable:
return StatReloader()
return WatchmanReloader()
def start_django(reloader, main_func, *args, **kwargs):
ensure_echo_on()
main_func = check_errors(main_func)
django_main_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs, name='django-main-thread')
django_main_thread.setDaemon(True)
django_main_thread.start()
while not reloader.should_stop:
try:
reloader.run(django_main_thread)
except WatchmanUnavailable as ex:
# It's possible that the watchman service shuts down or otherwise
# becomes unavailable. In that case, use the StatReloader.
reloader = StatReloader()
logger.error('Error connecting to Watchman: %s', ex)
logger.info('Watching for file changes with %s', reloader.__class__.__name__)
def run_with_reloader(main_func, *args, **kwargs):
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
try:
if os.environ.get(DJANGO_AUTORELOAD_ENV) == 'true':
reloader = get_reloader()
logger.info('Watching for file changes with %s', reloader.__class__.__name__)
start_django(reloader, main_func, *args, **kwargs)
else:
exit_code = restart_with_reloader()
sys.exit(exit_code)
except KeyboardInterrupt:
pass
|
"""
Created on Thu Jan 26 17:04:11 2017
@author: Andre Stochniol, andre@stochniol.com
Fit unet style nodule identifier on Luna databaset using 8-grid scheme
Physical resolution 2x2x2mm
Data aggregated, shuffled; wrap augmentation used (swrap)
"""
import numpy as np
from keras.models import load_model,Model
from keras.layers import MaxPooling3D
from keras.layers import Convolution3D
from keras.layers import Input, merge, UpSampling3D
from keras.optimizers import Adam
from keras import backend as K
#from keras.preprocessing.image import ImageDataGenerator # Keras original
from image_as_mod3d_2dmask import ImageDataGenerator # our modified version
K.set_image_dim_ordering('th')
smooth = 1.
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
DICE_LOW_LIMIT = 0 ## was 0.001
def dice_coef_np(y_true, y_pred):
y_true_f = y_true.flatten()
y_pred_f = y_pred.flatten()
y_pred_f [y_pred_f < DICE_LOW_LIMIT] = 0.
y_pred_f [y_pred_f > 1- DICE_LOW_LIMIT] = 1.
intersection = np.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
def dice_coef_pos_np(y_true, y_pred, pos = 0):
y_true_f = y_true[:,pos].flatten()
y_pred_f = y_pred[:,pos].flatten()
intersection = np.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
def unet_model_xd3_2_6l_grid(nb_filter=48, dim=5, clen=3 , img_rows=224, img_cols=224 ): # NOTE that this procedure is/should be used with img_rows & img_cols as None
# aiming for architecture similar to the http://cs231n.stanford.edu/reports2016/317_Report.pdf
# Our model is six layers deep, consisting of a series of three CONV-RELU-POOL layyers (with 32, 32, and 64 3x3 filters), a CONV-RELU layer (with 128 3x3 filters), three UPSCALE-CONV-RELU lay- ers (with 64, 32, and 32 3x3 filters), and a final 1x1 CONV- SIGMOID layer to output pixel-level predictions. Its struc- ture resembles Figure 2, though with the number of pixels, filters, and levels as described here
## 3D CNN version of a previously developed unet_model_xd_6j
zconv = clen
inputs = Input((1, dim, img_rows, img_cols))
conv1 = Convolution3D(nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(inputs)
conv1 = Convolution3D(nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(conv1)
pool1 = MaxPooling3D(pool_size=(2, 2, 2))(conv1)
conv2 = Convolution3D(2*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(pool1)
conv2 = Convolution3D(2*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(conv2)
pool2 = MaxPooling3D(pool_size=(2, 2, 2))(conv2)
conv4 = Convolution3D(4*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(pool2)
conv4 = Convolution3D(4*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(conv4)
up6 = merge([UpSampling3D(size=(2, 2, 2))(conv4), conv2], mode='concat', concat_axis=1)
conv6 = Convolution3D(2*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(up6)
conv6 = Convolution3D(2*nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(conv6)
up7 = merge([UpSampling3D(size=(2, 2, 2))(conv6), conv1], mode='concat', concat_axis=1) # original - only works for even dim
conv7 = Convolution3D(nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(up7)
conv7 = Convolution3D(nb_filter, zconv, clen, clen, activation='relu', border_mode='same')(conv7)
pool11 = MaxPooling3D(pool_size=(2, 1, 1))(conv7)
conv12 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(pool11)
conv12 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(conv12)
pool12 = MaxPooling3D(pool_size=(2, 1, 1))(conv12)
conv13 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(pool12)
conv13 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(conv13)
pool13 = MaxPooling3D(pool_size=(2, 1, 1))(conv13)
if (dim < 16):
conv8 = Convolution3D(1, 1, 1, 1, activation='sigmoid')(pool13)
else: # need one extra layer to get to 1D x 2D mask ...
conv14 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(pool13)
conv14 = Convolution3D(2*nb_filter, zconv, 1, 1, activation='relu', border_mode='same')(conv14)
pool14 = MaxPooling3D(pool_size=(2, 1, 1))(conv14)
conv8 = Convolution3D(1, 1, 1, 1, activation='sigmoid')(pool14)
model = Model(input=inputs, output=conv8)
model.compile(optimizer=Adam(lr=1e-4), loss=dice_coef_loss, metrics=[dice_coef])
#model.compile(optimizer=Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0), loss=dice_coef_loss, metrics=[dice_coef])
return model
def grid_data(source, grid=32, crop=16, expand=12):
height = source.shape[3] # should be 224 for our data, when used in the initial fix-size mode
width = source.shape[4]
gridheight = (height - 2 * crop) // grid # should be 6 for our data
gridwidth = (width - 2 * crop) // grid
cells = []
for j in range(gridheight):
for i in range (gridwidth):
cell = source[:,:,:, crop+j*grid-expand:crop+(j+1)*grid+expand, crop+i*grid-expand:crop+(i+1)*grid+expand]
cells.append(cell)
cells = np.vstack (cells)
return cells, gridwidth, gridheight
def data_from_grid (cells, gridwidth, gridheight, grid=32):
width = cells.shape[4]
crop = (width - grid ) // 2 ## for simplicity we are assuming the same crop (and grid) in x & y directions
if crop > 0: # do NOT crop with 0 as we get empty cells ...
cells = cells[:,:,:,crop:-crop,crop:-crop]
shape = cells.shape
new_shape_1_dim = shape[0]// (gridwidth * gridheight) # ws // 36 -- Improved on 20170306
new_shape = (gridwidth * gridheight, new_shape_1_dim, ) + tuple([x for x in shape][1:]) # was 36, Improved on 20170306
cells = np.reshape(cells, new_shape)
cells = np.moveaxis(cells, 0, -3)
shape = cells.shape
new_shape2 = tuple([x for x in shape[0:3]]) + (gridheight, gridwidth,) + tuple([x for x in shape[4:]])
cells = np.reshape(cells, new_shape2)
cells = cells.swapaxes(-2, -3)
shape = cells.shape
combine_shape =tuple([x for x in shape[0:3]]) + (shape[-4]*shape[-3], shape[-2]*shape[-1],)
cells = np.reshape(cells, combine_shape)
return cells
def data_from_grid_by_proximity (cells, gridwidth, gridheight, grid=32):
# disperse the sequential dats into layers and then use data_from_grid
shape = cells.shape
new_shape_1_dim = shape[0]// (gridwidth * gridheight) # ws // 36 -- Improved on 20170306
### NOTE tha we invert the order of shapes below to get the required proximity type ordering
new_shape = (new_shape_1_dim, gridwidth * gridheight, ) + tuple([x for x in shape][1:]) # was 36, Improved on 20170306
#new_shape = (gridwidth * gridheight, new_shape_1_dim, ) + tuple([x for x in shape][1:]) # was 36, Improved on 20170306
# swap ordering of axes
cells = np.reshape(cells, new_shape)
cells = cells.swapaxes(0, 1)
cells = np.reshape(cells, shape)
cells = data_from_grid (cells, gridwidth, gridheight, grid)
return cells
def load_aggregate_masks_scans (masks_mnames, grids, upgrid_multis):
scans = []
masks = []
igrid = 0
for masks_names in masks_mnames:
if (len(masks_names) > 0):
grid = grids[igrid]
upgrid_multi = upgrid_multis[igrid]
upgcount = upgrid_multi * upgrid_multi
scans1 = []
masks1 = []
for masks_name in masks_names:
print ("Loading: ", masks_name)
masks0 = np.load(''.join((masks_name, ".npz")))['arr_0']
scans0 = np.load(''.join((masks_name.replace("masks_", "scans_", 1), ".npz")))['arr_0']
masks1.append(masks0)
scans1.append(scans0)
scans1 = np.vstack(scans1)
masks1 = np.vstack(masks1)
if len(masks) > 0:
scans1 = np.vstack([scans1, scans])
masks1 = np.vstack([masks1, masks])
lm = len(masks1) // upgcount * upgcount
scans1 = scans1[0:lm] # cut to multiples of upgcount
masks1 = masks1[0:lm]
index_shuf = np.arange(lm)
np.random.shuffle(index_shuf)
scans1 = scans1[index_shuf]
masks1 = masks1[index_shuf]
scans = data_from_grid_by_proximity(scans1, upgrid_multi, upgrid_multi, grid=grid)
masks = data_from_grid_by_proximity(masks1, upgrid_multi, upgrid_multi, grid=grid)
igrid += 1
return masks, scans
if __name__ == '__main__':
# Key initial parameters
dim = 8
start_from_scratch = False
load_initial_weights = False
if start_from_scratch and load_initial_weights:
model_weights_name_to_start_from = "../luna/models/d8_2x2x2_best_weights.h5" # only used when start_from_scratch is True and load_initial_weights is True
### KEY running parameteres
nb_epoch = 24
model_load_name = '../luna/models/d8g_bre_model_26.h5'
model_save_name = '../luna/models/d8g_bre_model_50.h5' ### MUST include "_model" string as we use this for a substituion for weights file
seed = 26000 # should be varied by steps/stages
set_lr_value = True
new_lr_value = 1e-6 # only used when set_lr_value is True
use_large_validation = True
grids = [10, 20]
upgrid_multis = [2, 8] # we modify only the last one if/as needed
batch_size = 28 # calculated for a 12GB graphics card (such as Tesla K80/AWS P2 system)
masks_mnames = [
[
"../luna/models/masks_d8g1x10ba4_2x2x2_nodules_0_3_4003", # note no npz extension here
"../luna/models/masks_d8g1x10ba4_2x2x2_nodules_4_8_4968",
"../luna/models/masks_d8g1x10ba4_2x2x2_blanks_0_3_64769",
"../luna/models/masks_d8g1x10ba4_2x2x2_blanks_4_8_91485"
],
[
"../luna/models/masks_d8g1x20ba4_2x2x2_nodules_0_3_1211",
"../luna/models/masks_d8g1x20ba4_2x2x2_nodules_4_8_1265",
"../luna/models/masks_d8g1x20ba4_2x2x2_blanks_0_3_64769",
"../luna/models/masks_d8g1x20ba4_2x2x2_blanks_4_8_91485"
],
[
#"../luna/model_data/masks_d16g1x40ba8_2x1x1_nodules_0_3_6897"
]]
masks_val_mnames = [
[
"../luna/models/masks_d8g1x10ba4_2x2x2_nodules_9_9_864" # note no npz extension here
],
[
"../luna/models/masks_d8g1x20ba4_2x2x2_nodules_9_9_255"
],
[
# "../luna/model_data/masks_d16g1x40ba8_2x1x1_blanks_8_9_35056"
]]
masks_val_large_mnames = [
[
"../luna/models/masks_d8g1x10ba4_2x2x2_nodules_9_9_864", # note no npz extension here
"../luna/models/masks_d8g1x10ba4_2x2x2_blanks_9_9_18642"
],
[
"../luna/models/masks_d8g1x20ba4_2x2x2_nodules_9_9_255",
"../luna/models/masks_d8g1x20ba4_2x2x2_blanks_9_9_18642"
],
[
#, "../luna/model_data/masks_d16g1x40ba8_2x1x1_blanks_8_9_35056"
]]
np.random.seed(seed)
masks, scans = load_aggregate_masks_scans (masks_mnames, grids, upgrid_multis)
print ("Masks and Scans shapes: ", masks.shape, scans.shape)
masks[masks < 0] = 0 # just in case (eliminate the blanks's marking)
if masks.shape[2] > 1:
masks = masks[:,:,masks.shape[2] // 2] ## select the central value as this one contains still all data
masks = masks[:, np.newaxis]
print ("Masks shape after 2D mapping: ", masks.shape)
#np.random.seed(121) # you may wish to keep this seed constant for validation purposes
masks_val, scans_val = load_aggregate_masks_scans (masks_val_mnames, grids, upgrid_multis)
print ("Val Masks and Scans shapes: ", masks_val.shape, scans_val.shape)
masks_val[masks_val < 0] = 0
if masks_val.shape[2] > 1:
masks_val = masks_val[:,:,masks_val.shape[2] // 2] ## select the central value as this one contains still all data
masks_val = masks_val[:, np.newaxis]
print ("Masks_val shape after 2D mapping: ", masks_val.shape)
masks_val_large, scans_val_large = load_aggregate_masks_scans (masks_val_large_mnames, grids, upgrid_multis)
print ("Large Val Masks and Scans shapes: ", masks_val_large.shape, scans_val_large.shape)
masks_val_large[masks_val_large < 0] = 0
if masks_val_large.shape[2] > 1:
masks_val_large = masks_val_large[:,:,masks_val_large.shape[2] // 2] ## select the central value as this one contains still all data
masks_val_large = masks_val_large[:, np.newaxis]
print ("Large Val Masks shape after 2D mapping: ", masks_val_large.shape)
if start_from_scratch:
model = unet_model_xd3_2_6l_grid(nb_filter=20, dim=dim, clen=3, img_rows=None , img_cols=None )
print(model.summary())
if load_initial_weights:
model_weights_name = model_weights_name_to_start_from ### could potentially load best weights
model.load_weights(model_weights_name)
print("Weights and output models: ", model_weights_name, model_save_name)
else:
print("Start from scratch (no weights),output models: ", model_save_name)
else:
## load_previous_model
print ("Loading model: ", model_load_name)
model = load_model(model_load_name, #3
custom_objects={'dice_coef_loss': dice_coef_loss,
'dice_coef': dice_coef
}
)
#print(model.summary())
print("Load and output models: ", model_load_name, model_save_name)
## set the data ...
masks = masks.astype(np.int16)
final_couple_of_iterations = False
if final_couple_of_iterations:
masks = np.concatenate((masks, masks_val))
scans = np.concatenate((scans, scans_val))
data_gen_args = dict(featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=0,
width_shift_range=0.5,
height_shift_range=0.5,
horizontal_flip=True,
vertical_flip=False,
fill_mode= "wrap",
zoom_range=0
)
image_datagen = ImageDataGenerator(**data_gen_args)
mask_datagen = ImageDataGenerator(**data_gen_args)
# Provide the same seed and keyword arguments to the fit and flow methods
shuffle = True # default
image_datagen.fit(scans, augment=True, seed=seed)
mask_datagen.fit(masks, augment=True, seed=seed)
image_generator = image_datagen.flow(scans,
batch_size = batch_size,
#shuffle = shuffle,
seed=seed)
mask_generator = mask_datagen.flow(masks,
batch_size = batch_size,
#shuffle = shuffle,
seed=seed)
# combine generators into one which yields image and masks
train_generator = zip(image_generator, mask_generator)
if set_lr_value:
print("Model learning rate (old): ", model.optimizer.lr.get_value()) # was 1e-4
model.optimizer.lr.set_value(new_lr_value)
print("Model learning rate(new): ", model.optimizer.lr.get_value())
samples_per_epoch = masks.shape[0]
model.fit_generator(
train_generator,
samples_per_epoch= samples_per_epoch,
nb_epoch = nb_epoch,
validation_data = ( scans_val, masks_val),
verbose=1)
model.save(model_save_name)
model.save_weights(model_save_name.replace("_model", "_weights", 1))
masks_pred = model.predict(scans_val, verbose=1)
dice_check = dice_coef_np(masks_val, masks_pred)
print ("dice_check: ", dice_check)
if use_large_validation:
masks_pred_large = model.predict(scans_val_large, batch_size =1, verbose=1)
dice_check = dice_coef_np(masks_val_large, masks_pred_large)
print ("Full dice_check: ", dice_check)
print("Model learning rate: ", model.optimizer.lr.get_value())
|
"""Classes for describing work and results.
"""
import enum
import json
import pathlib
class StrEnum(str, enum.Enum):
"An Enum subclass with str values."
class WorkerOutcome(StrEnum):
"""Possible outcomes for a worker.
"""
NORMAL = 'normal' # The worker exited normally, producing valid output
EXCEPTION = 'exception' # The worker exited with an exception
ABNORMAL = 'abnormal' # The worker did not exit normally or with an exception (e.g. a segfault)
NO_TEST = 'no-test' # The worker had no test to run
SKIPPED = 'skipped' # The job was skipped (worker was not executed)
class TestOutcome(StrEnum):
"""A enum of the possible outcomes for any mutant test run.
"""
SURVIVED = 'survived'
KILLED = 'killed'
INCOMPETENT = 'incompetent'
class WorkResult:
"""The result of a single mutation and test run.
"""
def __init__(self,
worker_outcome,
output=None,
test_outcome=None,
diff=None):
if worker_outcome is None:
raise ValueError('Worker outcome must always have a value.')
self._output = output
self._test_outcome = test_outcome
self._worker_outcome = worker_outcome
self._diff = diff
@property
def worker_outcome(self):
"A `WorkerOutcome` indicating how the worker finished."
return self._worker_outcome
@property
def test_outcome(self):
"A `TestOutcome` indicating how the test runner finished. Possibly `None`."
return self._test_outcome
@property
def output(self):
"Any output returned by the test command. Possibly `None`."
return self._output
@property
def diff(self):
"A sequence of strings containing the diff generated by the mutation. Possibly `None`."
return self._diff
def as_dict(self):
"Get the WorkResult as a dict."
return {
'output': self.output,
'test_outcome': self.test_outcome,
'worker_outcome': self.worker_outcome,
'diff': self.diff,
}
@property
def is_killed(self):
"Whether the mutation should be considered 'killed'"
return self.test_outcome != TestOutcome.SURVIVED
def __eq__(self, rhs):
return self.as_dict() == rhs.as_dict()
def __neq__(self, rhs):
return not self == rhs
class WorkItem:
"""Description of the work for a single mutation and test run.
"""
# pylint: disable=R0913
def __init__(self,
module_path=None,
operator_name=None,
occurrence=None,
start_pos=None,
end_pos=None,
job_id=None):
if start_pos[0] > end_pos[0]:
raise ValueError('Start line must not be after end line')
if start_pos[0] == end_pos[0]:
if start_pos[1] >= end_pos[1]:
raise ValueError(
'End position must come after start position.')
self._module_path = pathlib.Path(module_path)
self._operator_name = operator_name
self.occurrence = occurrence
self._start_pos = start_pos
self._end_pos = end_pos
self._job_id = job_id
@property
def module_path(self):
"pathlib.Path to module being mutated."
return self._module_path
@property
def operator_name(self):
"The name of the operator (i.e. as defined by the provider)"
return self._operator_name
@property
def start_pos(self):
"Start of the mutation location as a `(line, column)` tuple."
return self._start_pos
@property
def end_pos(self):
"""End of the mutation location as a `(line, column)` tuple.
Note that this represents the offset *one past* the end of the mutated
segment. If the mutated segment is at the end of a file, this offset
will be past the end of the file.
"""
return self._end_pos
@property
def job_id(self):
"The unique ID of the job"
return self._job_id
def as_dict(self):
"""Get fields as a dict.
"""
return {
'module_path': str(self.module_path),
'operator_name': self.operator_name,
'occurrence': self.occurrence,
'start_pos': self.start_pos,
'end_pos': self.end_pos,
'job_id': self.job_id,
}
def __eq__(self, rhs):
return self.as_dict() == rhs.as_dict()
def __neq__(self, rhs):
return not self == rhs
class WorkItemJsonEncoder(json.JSONEncoder):
"Custom JSON encoder for workitems and workresults."
def default(self, o): # pylint: disable=E0202
if isinstance(o, WorkItem):
return {"_type": "WorkItem", "values": o.as_dict()}
if isinstance(o, WorkResult):
return {"_type": "WorkResult", "values": o.as_dict()}
return super().default(o)
class WorkItemJsonDecoder(json.JSONDecoder):
"Custom JSON decoder for WorkItems and WorkResults."
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self._decode_work_items)
@staticmethod
def _decode_work_items(obj):
if (obj.get('_type') == 'WorkItem') and ('values' in obj):
values = obj['values']
return WorkItem(**values)
if (obj.get('_type') == 'WorkResult') and ('values' in obj):
values = obj['values']
return WorkResult(**values)
return obj
|
from dbt.api import APIObject
from dbt.utils import deep_merge
from dbt.node_types import NodeType
from dbt.exceptions import raise_duplicate_resource_name, \
raise_patch_targets_not_found
import dbt.clients.jinja
from dbt.contracts.graph.unparsed import UNPARSED_NODE_CONTRACT, \
UNPARSED_MACRO_CONTRACT, UNPARSED_DOCUMENTATION_FILE_CONTRACT, \
UNPARSED_BASE_CONTRACT, FRESHNESS_CONTRACT
from dbt.logger import GLOBAL_LOGGER as logger # noqa
# TODO: which of these do we _really_ support? or is it both?
HOOK_CONTRACT = {
'anyOf': [
{
'type': 'object',
'additionalProperties': False,
'properties': {
'sql': {
'type': 'string',
},
'transaction': {
'type': 'boolean',
},
'index': {
'type': 'integer',
}
},
'required': ['sql', 'transaction'],
},
{
'type': 'string',
},
],
}
CONFIG_CONTRACT = {
'type': 'object',
'additionalProperties': True,
'properties': {
'enabled': {
'type': 'boolean',
},
'materialized': {
'type': 'string',
},
'post-hook': {
'type': 'array',
'items': HOOK_CONTRACT,
},
'pre-hook': {
'type': 'array',
'items': HOOK_CONTRACT,
},
'vars': {
'type': 'object',
'additionalProperties': True,
},
'quoting': {
'type': 'object',
'additionalProperties': True,
},
'column_types': {
'type': 'object',
'additionalProperties': True,
},
'tags': {
'anyOf': [
{
'type': 'array',
'items': {
'type': 'string'
},
},
{
'type': 'string'
}
]
},
},
'required': [
'enabled', 'materialized', 'post-hook', 'pre-hook', 'vars',
'quoting', 'column_types', 'tags'
]
}
# Note that description must be present, but may be empty.
COLUMN_INFO_CONTRACT = {
'type': 'object',
'additionalProperties': False,
'description': 'Information about a single column in a model',
'properties': {
'name': {
'type': 'string',
'description': 'The column name',
},
'description': {
'type': 'string',
'description': 'A description of the column',
},
},
'required': ['name', 'description'],
}
# Docrefs are not quite like regular references, as they indicate what they
# apply to as well as what they are referring to (so the doc package + doc
# name, but also the column name if relevant). This is because column
# descriptions are rendered separately from their models.
DOCREF_CONTRACT = {
'type': 'object',
'properties': {
'documentation_name': {
'type': 'string',
'description': 'The name of the documentation block referred to',
},
'documentation_package': {
'type': 'string',
'description': (
'If provided, the documentation package name referred to'
),
},
'column_name': {
'type': 'string',
'description': (
'If the documentation refers to a column instead of the '
'model, the column name should be set'
),
},
},
'required': ['documentation_name', 'documentation_package']
}
HAS_FQN_CONTRACT = {
'properties': {
'fqn': {
'type': 'array',
'items': {
'type': 'string',
}
},
},
'required': ['fqn'],
}
HAS_UNIQUE_ID_CONTRACT = {
'properties': {
'unique_id': {
'type': 'string',
'minLength': 1,
},
},
'required': ['unique_id'],
}
CAN_REF_CONTRACT = {
'properties': {
'refs': {
'type': 'array',
'items': {
'type': 'array',
'description': (
'The list of arguments passed to a single ref call.'
),
},
'description': (
'The list of call arguments, one list of arguments per '
'call.'
)
},
'sources': {
'type': 'array',
'items': {
'type': 'array',
'description': (
'The list of arguments passed to a single source call.'
),
},
'description': (
'The list of call arguments, one list of arguments per '
'call.'
)
},
'depends_on': {
'type': 'object',
'additionalProperties': False,
'properties': {
'nodes': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1,
'description': (
'A node unique ID that this depends on.'
)
}
},
'macros': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1,
'description': (
'A macro unique ID that this depends on.'
)
}
},
},
'description': (
'A list of unique IDs for nodes and macros that this '
'node depends upon.'
),
'required': ['nodes', 'macros'],
},
},
'required': ['refs', 'sources', 'depends_on'],
}
HAS_DOCREFS_CONTRACT = {
'properties': {
'docrefs': {
'type': 'array',
'items': DOCREF_CONTRACT,
},
},
}
HAS_DESCRIPTION_CONTRACT = {
'properties': {
'description': {
'type': 'string',
'description': 'A user-supplied description of the model',
},
'columns': {
'type': 'object',
'properties': {
'.*': COLUMN_INFO_CONTRACT,
},
},
},
'required': ['description', 'columns'],
}
# does this belong inside another contract?
HAS_CONFIG_CONTRACT = {
'properties': {
'config': CONFIG_CONTRACT,
},
'required': ['config'],
}
COLUMN_TEST_CONTRACT = {
'properties': {
'column_name': {
'type': 'string',
'description': (
'In tests parsed from a v2 schema, the column the test is '
'associated with (if there is one)'
)
},
}
}
PARSED_NODE_CONTRACT = deep_merge(
UNPARSED_NODE_CONTRACT,
HAS_UNIQUE_ID_CONTRACT,
HAS_FQN_CONTRACT,
CAN_REF_CONTRACT,
HAS_DOCREFS_CONTRACT,
HAS_DESCRIPTION_CONTRACT,
HAS_CONFIG_CONTRACT,
COLUMN_TEST_CONTRACT,
{
'properties': {
# these next 3 make sense as a contract
'database': {
'type': 'string',
'description': (
'The actual database string that this will build into.'
)
},
'schema': {
'type': 'string',
'description': (
'The actual schema string that this will build into.'
)
},
'alias': {
'type': 'string',
'description': (
'The name of the relation that this will build into'
)
},
# TODO: move this into a class property.
'empty': {
'type': 'boolean',
'description': 'True if the SQL is empty',
},
'tags': {
'type': 'array',
'items': {
'type': 'string',
}
},
# this is really nodes-only
'patch_path': {
'type': 'string',
'description': (
'The path to the patch source if the node was patched'
),
},
'build_path': {
'type': 'string',
'description': (
'In seeds, the path to the source file used during build.'
),
},
},
'required': ['database', 'schema', 'empty', 'tags', 'alias'],
}
)
class ParsedNode(APIObject):
SCHEMA = PARSED_NODE_CONTRACT
def __init__(self, agate_table=None, **kwargs):
self.agate_table = agate_table
kwargs.setdefault('columns', {})
kwargs.setdefault('description', '')
super(ParsedNode, self).__init__(**kwargs)
@property
def depends_on_nodes(self):
"""Return the list of node IDs that this node depends on."""
return self.depends_on['nodes']
def to_dict(self):
"""Similar to 'serialize', but tacks the agate_table attribute in too.
Why we need this:
- networkx demands that the attr_dict it gets (the node) be a dict
or subclass and does not respect the abstract Mapping class
- many jinja things access the agate_table attribute (member) of
the node dict.
- the nodes are passed around between those two contexts in a way
that I don't quite have clear enough yet.
"""
ret = self.serialize()
# note: not a copy/deep copy.
ret['agate_table'] = self.agate_table
return ret
def to_shallow_dict(self):
ret = self._contents.copy()
ret['agate_table'] = self.agate_table
return ret
def patch(self, patch):
"""Given a ParsedNodePatch, add the new information to the node."""
# explicitly pick out the parts to update so we don't inadvertently
# step on the model name or anything
self._contents.update({
'patch_path': patch.original_file_path,
'description': patch.description,
'columns': patch.columns,
'docrefs': patch.docrefs,
})
# patches always trigger re-validation
self.validate()
def get_materialization(self):
return self.config.get('materialized')
@property
def build_path(self):
return self._contents.get('build_path')
@build_path.setter
def build_path(self, value):
self._contents['build_path'] = value
@property
def database(self):
return self._contents['database']
@database.setter
def database(self, value):
self._contents['database'] = value
@property
def schema(self):
return self._contents['schema']
@schema.setter
def schema(self, value):
self._contents['schema'] = value
@property
def alias(self):
return self._contents['alias']
@alias.setter
def alias(self, value):
self._contents['alias'] = value
@property
def config(self):
return self._contents['config']
@config.setter
def config(self, value):
self._contents['config'] = value
# The parsed node update is only the 'patch', not the test. The test became a
# regular parsed node. Note that description and columns must be present, but
# may be empty.
PARSED_NODE_PATCH_CONTRACT = {
'type': 'object',
'additionalProperties': False,
'description': 'A collection of values that can be set on a node',
'properties': {
'name': {
'type': 'string',
'description': 'The name of the node this modifies',
},
'description': {
'type': 'string',
'description': 'The description of the node to add',
},
'original_file_path': {
'type': 'string',
'description': (
'Relative path to the originating file path for the patch '
'from the project root'
),
},
'columns': {
'type': 'object',
'properties': {
'.*': COLUMN_INFO_CONTRACT,
}
},
'docrefs': {
'type': 'array',
'items': DOCREF_CONTRACT,
}
},
'required': [
'name', 'original_file_path', 'description', 'columns', 'docrefs'
],
}
class ParsedNodePatch(APIObject):
SCHEMA = PARSED_NODE_PATCH_CONTRACT
PARSED_MACRO_CONTRACT = deep_merge(
UNPARSED_MACRO_CONTRACT,
{
# This is required for the 'generator' field to work.
# TODO: fix before release
'additionalProperties': True,
'properties': {
'name': {
'type': 'string',
'description': (
'Name of this node. For models, this is used as the '
'identifier in the database.'),
'minLength': 1,
'maxLength': 127,
},
'resource_type': {
'enum': [
NodeType.Macro,
],
},
'unique_id': {
'type': 'string',
'minLength': 1,
'maxLength': 255,
},
'tags': {
'description': (
'An array of arbitrary strings to use as tags.'
),
'type': 'array',
'items': {
'type': 'string',
},
},
'depends_on': {
'type': 'object',
'additionalProperties': False,
'properties': {
'macros': {
'type': 'array',
'items': {
'type': 'string',
'minLength': 1,
'maxLength': 255,
'description': 'A single macro unique ID.'
}
}
},
'description': 'A list of all macros this macro depends on.',
'required': ['macros'],
},
},
'required': [
'resource_type', 'unique_id', 'tags', 'depends_on', 'name',
]
}
)
class ParsedMacro(APIObject):
SCHEMA = PARSED_MACRO_CONTRACT
@property
def generator(self):
"""
Returns a function that can be called to render the macro results.
"""
# TODO: we can generate self.template from the other properties
# available in this class. should we just generate this here?
return dbt.clients.jinja.macro_generator(self._contents)
# This is just the file + its ID
PARSED_DOCUMENTATION_CONTRACT = deep_merge(
UNPARSED_DOCUMENTATION_FILE_CONTRACT,
{
'properties': {
'name': {
'type': 'string',
'description': (
'Name of this node, as referred to by doc() references'
),
},
'unique_id': {
'type': 'string',
'minLength': 1,
'maxLength': 255,
'description': (
'The unique ID of this node as stored in the manifest'
),
},
'block_contents': {
'type': 'string',
'description': 'The contents of just the docs block',
},
},
'required': ['name', 'unique_id', 'block_contents'],
}
)
NODE_EDGE_MAP = {
'type': 'object',
'additionalProperties': False,
'description': 'A map of node relationships',
'patternProperties': {
'.*': {
'type': 'array',
'items': {
'type': 'string',
'description': 'A node name',
}
}
}
}
class ParsedDocumentation(APIObject):
SCHEMA = PARSED_DOCUMENTATION_CONTRACT
class Hook(APIObject):
SCHEMA = HOOK_CONTRACT
PARSED_SOURCE_DEFINITION_CONTRACT = deep_merge(
UNPARSED_BASE_CONTRACT,
FRESHNESS_CONTRACT,
HAS_DESCRIPTION_CONTRACT,
HAS_UNIQUE_ID_CONTRACT,
HAS_DOCREFS_CONTRACT,
{
'description': (
'A source table definition, as parsed from the one provided in the'
'"tables" subsection of the "sources" section of schema.yml'
),
'properties': {
'name': {
'type': 'string',
'description': (
'The name of this node, which is the name of the model it'
'refers to'
),
'minLength': 1,
},
'source_name': {
'type': 'string',
'description': 'The reference name of the source definition',
'minLength': 1,
},
'source_description': {
'type': 'string',
'description': 'The user-supplied description of the source',
},
'loader': {
'type': 'string',
'description': 'The user-defined loader for this source',
},
'sql_table_name': {
'type': 'string',
'description': 'The exact identifier for the source table',
'minLength': 1,
},
# the manifest search stuff really requires this, sadly
'resource_type': {
'enum': [NodeType.Source],
}
},
# note that while required, loaded_at_field and freshness may be null
# (and either of freshness's members may be null as well!)
'required': [
'source_name', 'source_description', 'loaded_at_field', 'loader',
'freshness', 'description', 'columns', 'docrefs', 'sql_table_name',
],
}
)
class ParsedSourceDefinition(APIObject):
SCHEMA = PARSED_SOURCE_DEFINITION_CONTRACT
def to_shallow_dict(self):
return self._contents.copy()
# provide some emtpy/meaningless properties so these look more like
# ParsedNodes
@property
def depends_on_nodes(self):
return []
@property
def refs(self):
return []
@property
def sources(self):
return []
|
const { arduino } = require('../Setup')
module.exports = {
startSerialCommunication(req, res) {
arduino.startSerial()
return res.send(true)
},
closeSerialCommunication(req, res) {
arduino.closeSerial()
return res.send(true)
},
sendMessage(req, res) {
const { message } = req.query
arduino.sendMessage(message)
return res.send(true)
},
getMessage(req, res) {
return res.send(arduino.message)
},
getMeasures(req, res) {
let voltage = arduino.voltage
let current = arduino.current
let capacity = arduino.capacity
let battery = arduino.battery
let BATTERY_CAPACITY = arduino.BATTERY_CAPACITY
return res.send({ voltage, current, capacity, battery, BATTERY_CAPACITY })
},
}
|
/**
Extending \b PNWhereNowResponseParser class with properties which can be used internally by \b PubNub client.
@author Sergey Mamontov
@version 3.6.0
@copyright © 2009-13 PubNub Inc.
*/
#import "PNWhereNowResponseParser.h"
#pragma mark - Class forward
@class PNWhereNow;
#pragma mark - Private interface declaration
@interface PNWhereNowResponseParser ()
#pragma mark - Properties
/**
Stores parsed information for participant channels response.
*/
@property (nonatomic, strong) PNWhereNow *whereNow;
#pragma mark -
@end
|
import unittest
from colorexlib.colorexlib.readers.FileInputReader import FileInputReader
class TestInit(unittest.TestCase):
def test___init__A(self):
FileInputReader("C:\\users\\lronald\\desktop\\myfile.txt")
FileInputReader("some string parameter")
def test___init__B(self):
self.assertRaises(TypeError,
FileInputReader)
self.assertRaises(TypeError,
FileInputReader,
8972)
self.assertRaises(TypeError,
FileInputReader,
0x901)
self.assertRaises(TypeError,
FileInputReader,
-1009)
class TestFilePathSetterGetter(unittest.TestCase):
def setUp(self):
self.filepath1 = "C:\\a_file"
self.filepath2 = "C:\\Users\\lronald\\Desktop\\b_file"
self.filepath3 = "C:\\Users\\lronald\\Documents\\c_file"
self.fileInputReaderA = FileInputReader(self.filepath1)
self.fileInputReaderB = FileInputReader(self.filepath2)
self.fileInputReaderC = FileInputReader(self.filepath3)
def test_filepath_A(self):
self.assertEqual(self.fileInputReaderA.filepath,
self.filepath1)
self.fileInputReaderA.filepath = "new_file_path"
self.assertNotEqual(self.fileInputReaderA.filepath,
self.filepath1)
self.assertEqual(self.fileInputReaderB.filepath,
self.filepath2)
self.fileInputReaderB.filepath = "new_file_path"
self.assertNotEqual(self.fileInputReaderB.filepath,
self.filepath2)
self.assertEqual(self.fileInputReaderC.filepath,
self.filepath3)
self.fileInputReaderC.filepath = "new_file_path"
self.assertNotEqual(self.fileInputReaderC.filepath,
self.filepath3)
class TestDataSetterGetter(unittest.TestCase):
def setUp(self):
self.filepath1 = "C:\\a_file"
self.filepath2 = "C:\\Users\\lronald\\Desktop\\b_file"
self.filepath3 = "C:\\Users\\lronald\\Documents\\c_file"
self.fileInputReaderA = FileInputReader(self.filepath1)
self.fileInputReaderB = FileInputReader(self.filepath2)
self.fileInputReaderC = FileInputReader(self.filepath3)
self.data1 = [1,4,5,6]
self.data2 = [9,1,56,3,-4]
self.data3 = [10,5,6,4]
def test_data_A(self):
self.fileInputReaderA.data = self.data1
self.assertEqual(self.fileInputReaderA.data,
self.data1)
self.fileInputReaderB.data = self.data2
self.assertEqual(self.fileInputReaderB.data,
self.data2)
self.fileInputReaderC.data = self.data3
self.assertEqual(self.fileInputReaderC.data,
self.data3)
@unittest.skip("Method implemented by child class.")
class TestRead(unittest.TestCase):
pass
@unittest.skip("Method implemented by child class.")
class TestGenerateDataGrid(unittest.TestCase):
pass
|
from yaost import scad, Vector
from yaost.path import Path
inf = 1000
tol = 0.005
class Nut(object):
_config = {
'M3': (2.75, 6.3, 2.6, 5.5),
'M4': (3.4, 8.0, 3.5, 6.9),
'M5': (4.34, 8.9, 3.82, 7.83),
}
def __init__(self, class_):
if class_ not in self._config:
raise Exception('Unknonw nut {}'.format(class_))
self._class = class_
self.internal_diameter, self.external_diameter, self.height, self.width = self._config[class_]
@property
def screw(self):
return Screw(self._class)
@property
def model(self):
result = scad.cylinder(d=self.external_diameter, h=self.height, fn=6)
result -= scad.cylinder(d=self.internal_diameter, h=self.height + tol * 2).tz(-tol)
return result
def hole(self, h=inf):
result = scad.cylinder(d=self.external_diameter, h=h, fn=6)
return result
class Screw(object):
_config = {
'M3': (3.0, 6.0, 2.0),
'M4': (4.0, 8.0, 3.0),
'M5': (5.0, 9.9, 4.0),
}
def __init__(self, class_, length=inf):
if class_ not in self._config:
raise Exception('Unknonw nut {}'.format(class_))
self.diameter, self.cap_diameter, self.cap_depth = self._config[class_]
self.length = length
self.class_ = class_
@property
def nut(self):
return Nut(self.class_)
@property
def model(self):
result = scad.cylinder(d1=self.cap_diameter, d2=self.diameter, h=self.cap_depth)
result += scad.cylinder(d=self.diameter, h=self.length)
return result
def hole(self, h=inf, inf_cap=False, no_cap=False, cap_type='hidden', clearance=0):
if no_cap:
return scad.cylinder(d=self.diameter, h=h).tz(-tol)
if inf_cap:
result = scad.cylinder(d=self.cap_diameter, h=inf).mz().tz(tol)
else:
result = scad.cylinder(d=self.cap_diameter, h=tol * 2).tz(-tol)
if cap_type == 'hidden':
result += scad.cylinder(d1=self.cap_diameter, d2=self.diameter, h=self.cap_depth)
elif cap_type == 'cylinder':
result += scad.cylinder(d=self.cap_diameter, h=self.cap_depth)
result += scad.cylinder(d=self.diameter + clearance, h=h)
return result
class Nema(object):
def __init__(self, class_=17):
if class_ == 17:
self.width = 42.3
self.ledge_diameter = 22
self.ledge_height = 2.0
self.axel_diameter = 5
self.axel_length = 25
self.axel_chamfer = 0.5
self.hole_spacing = 31
self.screw = Screw('M3')
else:
raise Exception('{} class not supported'.format(class_))
def holes(self, no_cap=False):
result = scad.cylinder(d=self.ledge_diameter, h=inf).tz(-tol)
result += self.screw.hole(no_cap=no_cap).t(
self.hole_spacing / 2,
self.hole_spacing / 2
).mx(clone=True).my(clone=True)
return result
@property
def model(self):
result = rounded_box(
self.width, self.width, self.height, r=(self.width - self.hole_spacing) / 2
).t('c', 'c', -self.height)
result += scad.cylinder(d=self.ledge_diameter, h=self.ledge_height + tol).tz(-tol)
result += (
scad.cylinder(d=self.axel_diameter, h=self.axel_length)
- scad.cube(inf, inf, inf).t(
'c',
self.axel_diameter / 2 - self.axel_chamfer,
'c'
)
)
result -= scad.cylinder(d=self.screw.diameter, h=self.inf).t(
self.hole_spacing / 2,
self.hole_spacing / 2,
-self.height / 2
).mx(clone=True).my(clone=True)
return result.module_name('nema17')
class ExtrusionProfile(object):
def __init__(self, class_='2020'):
if class_ == '2020':
self.width = 20
self.insert_p2 = 9.55
self.insert_p3 = 6.2
self.insert_p3_y = 1.8
self.screw = Screw('M4')
else:
raise Exception('class `{}` not found'.format(class_))
def insert(self, height, length):
p0 = Vector(self.width / 2, 0)
p1 = Vector(self.width / 2, height)
p2 = Vector(self.insert_p2 / 2, p1.y)
p3 = Vector(self.insert_p3 / 2, p1.y + self.insert_p3_y)
points = [p0, p1, p2, p3]
points += [p.mx() for p in reversed(points)]
result = scad.polygon(points).extrude(length).rx(90).t(
self.width / 2,
length
)
result.com = scad.cube(self.width, length, height).com
return result
# def simple_insert(height, length):
# p0 = Vector(width / 2, 0)
# p1 = Vector(width / 2, height)
# p2 = Vector(6.0 / 2, p1.y)
# p3 = Vector(6.0 / 2, p1.y + 1.8)
# points = [p0, p1, p2, p3]
# points += [p.mx() for p in reversed(points)]
# result = Path(points).extrude(length)
# return result
|
"""
Train different CNN models on frames
"""
import datetime
import os
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard
from src.config import MODEL_CHECKPOINTS_DIR
from src.data import DataSet
from src.data_generator import DataGenerator
from src.models import ResearchModels
def get_generators(model_name):
def get_main_params(train_test):
dataset = DataSet()
list_IDs, targets = dataset.get_partition(train_test, balanced=True)
return list_IDs, targets, train_test
params = {'dim': (96, 96),
'batch_size': 128,
'n_channels': 1,
'shuffle': True}
# Generators
train_generator = DataGenerator(*get_main_params("train"), **params)
valid_generator = DataGenerator(*get_main_params("test"), **params)
return train_generator, valid_generator
def train_model(research_model, nb_epoch, generators, callbacks=[]):
train_generator, validation_generator = generators
research_model.model.fit_generator(
train_generator,
# workers=4,
steps_per_epoch=1000,
# use_multiprocessing=True,
validation_data=validation_generator,
epochs=nb_epoch,
callbacks=callbacks)
def main():
model_name = 'simple_cnn_ccc_loss'
if not os.path.exists(MODEL_CHECKPOINTS_DIR):
os.makedirs(MODEL_CHECKPOINTS_DIR)
checkpointer = ModelCheckpoint(
filepath=os.path.join(MODEL_CHECKPOINTS_DIR, model_name + '.{epoch:04d}-{val_loss:.4f}.hdf5'),
verbose=1,
save_best_only=True,
period=1)
logdir = os.path.join("data/logs", model_name + '-' + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
tensorboard_callback = TensorBoard(log_dir=logdir, profile_batch=0)
# saved_model_path='/home/rangulov/EmotionRecognition/data/checkpoints/vggface_ccc_loss.0002-0.9685.hdf5'
saved_model_path = None
research_model = ResearchModels(model_name, saved_model=saved_model_path)
generators = get_generators('simple-cnn')
train_model(research_model, 100, generators, [checkpointer, tensorboard_callback])
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ng_opcserver documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import ng_opcserver
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'ng_opcserver'
copyright = u"2019, Yossi Mosbacher"
author = u"Yossi Mosbacher"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = ng_opcserver.__version__
# The full version, including alpha/beta/rc tags.
release = ng_opcserver.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'ng_opcserverdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'ng_opcserver.tex',
u'ng_opcserver Documentation',
u'Yossi Mosbacher', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'ng_opcserver',
u'ng_opcserver Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'ng_opcserver',
u'ng_opcserver Documentation',
author,
'ng_opcserver',
'One line description of project.',
'Miscellaneous'),
]
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:53:42 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/ActionKit.framework/ActionKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <WorkflowKit/WFAccessResource.h>
@interface WFContactAccessResource : WFAccessResource
+(BOOL)isSystemResource;
-(unsigned long long)globalLevelStatus;
-(id)associatedAppIdentifier;
-(id)protectedResourceDescription;
-(void)makeAvailableAtGlobalLevelWithUserInterface:(id)arg1 completionHandler:(/*^block*/id)arg2 ;
@end
|
/**
*
* DangerZone
*
*/
import Container from './styles/Container';
const DangerZone = Container;
export default DangerZone;
|
import 'plugins/markdown_vis/markdown_vis.less';
import { MarkdownVisWrapper } from './markdown_vis_controller';
import { VisFactoryProvider } from 'ui/vis/vis_factory';
import { CATEGORY } from 'ui/vis/vis_category';
import markdownVisParamsTemplate from 'plugins/markdown_vis/markdown_vis_params.html';
import { VisTypesRegistryProvider } from 'ui/registry/vis_types';
import image from './images/icon-markdown.svg';
import { DefaultEditorSize } from 'ui/vis/editor_size';
// we need to load the css ourselves
// we also need to load the controller and used by the template
// register the provider with the visTypes registry so that other know it exists
VisTypesRegistryProvider.register(MarkdownVisProvider);
function MarkdownVisProvider(Private) {
const VisFactory = Private(VisFactoryProvider);
// return the visType object, which kibana will use to display and configure new
// Vis object of this type.
return VisFactory.createReactVisualization({
name: 'markdown',
title: 'Markdown',
isAccessible: true,
image,
description: 'Create a document using markdown syntax',
category: CATEGORY.OTHER,
visConfig: {
component: MarkdownVisWrapper,
defaults: {
fontSize: 12
}
},
editorConfig: {
optionsTemplate: markdownVisParamsTemplate,
enableAutoApply: true,
defaultSize: DefaultEditorSize.LARGE,
},
options: {
showTimePicker: false,
},
requestHandler: 'none',
responseHandler: 'none',
});
}
// export the provider so that the visType can be required with Private()
export default MarkdownVisProvider;
|
// SPDX-License-Identifier: BSD-2-Clause-Patent
/*
* shim - trivial UEFI first-stage bootloader
*
* Copyright Red Hat, Inc
* Author: Matthew Garrett
*
* Significant portions of this code are derived from Tianocore
* (http://tianocore.sf.net) and are Copyright 2009-2012 Intel
* Corporation.
*/
#include "shim.h"
#if defined(ENABLE_SHIM_CERT)
#include "shim_cert.h"
#endif /* defined(ENABLE_SHIM_CERT) */
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/ocsp.h>
#include <openssl/pkcs12.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/rsa.h>
#include <openssl/dso.h>
#include <Library/BaseCryptLib.h>
#include <stdint.h>
#define OID_EKU_MODSIGN "1.3.6.1.4.1.2312.16.1.2"
static EFI_SYSTEM_TABLE *systab;
static EFI_HANDLE global_image_handle;
static EFI_LOADED_IMAGE *shim_li;
static EFI_LOADED_IMAGE shim_li_bak;
list_t sbat_var;
/*
* The vendor certificate used for validating the second stage loader
*/
extern struct {
UINT32 vendor_authorized_size;
UINT32 vendor_deauthorized_size;
UINT32 vendor_authorized_offset;
UINT32 vendor_deauthorized_offset;
} cert_table;
#define EFI_IMAGE_SECURITY_DATABASE_GUID { 0xd719b2cb, 0x3d3a, 0x4596, { 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f }}
typedef enum {
DATA_FOUND,
DATA_NOT_FOUND,
VAR_NOT_FOUND
} CHECK_STATUS;
typedef struct {
UINT32 MokSize;
UINT8 *Mok;
} MokListNode;
static void
drain_openssl_errors(void)
{
unsigned long err = -1;
while (err != 0)
err = ERR_get_error();
}
static BOOLEAN verify_x509(UINT8 *Cert, UINTN CertSize)
{
UINTN length;
if (!Cert || CertSize < 4)
return FALSE;
/*
* A DER encoding x509 certificate starts with SEQUENCE(0x30),
* the number of length bytes, and the number of value bytes.
* The size of a x509 certificate is usually between 127 bytes
* and 64KB. For convenience, assume the number of value bytes
* is 2, i.e. the second byte is 0x82.
*/
if (Cert[0] != 0x30 || Cert[1] != 0x82) {
dprint(L"cert[0:1] is [%02x%02x], should be [%02x%02x]\n",
Cert[0], Cert[1], 0x30, 0x82);
return FALSE;
}
length = Cert[2]<<8 | Cert[3];
if (length != (CertSize - 4)) {
dprint(L"Cert length is %ld, expecting %ld\n",
length, CertSize);
return FALSE;
}
return TRUE;
}
static BOOLEAN verify_eku(UINT8 *Cert, UINTN CertSize)
{
X509 *x509;
CONST UINT8 *Temp = Cert;
EXTENDED_KEY_USAGE *eku;
ASN1_OBJECT *module_signing;
module_signing = OBJ_nid2obj(OBJ_create(OID_EKU_MODSIGN,
"modsign-eku",
"modsign-eku"));
x509 = d2i_X509 (NULL, &Temp, (long) CertSize);
if (x509 != NULL) {
eku = X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL);
if (eku) {
int i = 0;
for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
ASN1_OBJECT *key_usage = sk_ASN1_OBJECT_value(eku, i);
if (OBJ_cmp(module_signing, key_usage) == 0)
return FALSE;
}
EXTENDED_KEY_USAGE_free(eku);
}
X509_free(x509);
}
OBJ_cleanup();
return TRUE;
}
static CHECK_STATUS check_db_cert_in_ram(EFI_SIGNATURE_LIST *CertList,
UINTN dbsize,
WIN_CERTIFICATE_EFI_PKCS *data,
UINT8 *hash, CHAR16 *dbname,
EFI_GUID guid)
{
EFI_SIGNATURE_DATA *Cert;
UINTN CertSize;
BOOLEAN IsFound = FALSE;
int i = 0;
while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
if (CompareGuid (&CertList->SignatureType, &EFI_CERT_TYPE_X509_GUID) == 0) {
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
CertSize = CertList->SignatureSize - sizeof(EFI_GUID);
dprint(L"trying to verify cert %d (%s)\n", i++, dbname);
if (verify_x509(Cert->SignatureData, CertSize)) {
if (verify_eku(Cert->SignatureData, CertSize)) {
drain_openssl_errors();
IsFound = AuthenticodeVerify (data->CertData,
data->Hdr.dwLength - sizeof(data->Hdr),
Cert->SignatureData,
CertSize,
hash, SHA256_DIGEST_SIZE);
if (IsFound) {
dprint(L"AuthenticodeVerify() succeeded: %d\n", IsFound);
tpm_measure_variable(dbname, guid, CertList->SignatureSize, Cert);
drain_openssl_errors();
return DATA_FOUND;
} else {
LogError(L"AuthenticodeVerify(): %d\n", IsFound);
}
}
} else if (verbose) {
console_print(L"Not a DER encoded x.509 Certificate");
dprint(L"cert:\n");
dhexdumpat(Cert->SignatureData, CertSize, 0);
}
}
dbsize -= CertList->SignatureListSize;
CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
}
return DATA_NOT_FOUND;
}
static CHECK_STATUS check_db_cert(CHAR16 *dbname, EFI_GUID guid,
WIN_CERTIFICATE_EFI_PKCS *data, UINT8 *hash)
{
CHECK_STATUS rc;
EFI_STATUS efi_status;
EFI_SIGNATURE_LIST *CertList;
UINTN dbsize = 0;
UINT8 *db;
efi_status = get_variable(dbname, &db, &dbsize, guid);
if (EFI_ERROR(efi_status))
return VAR_NOT_FOUND;
CertList = (EFI_SIGNATURE_LIST *)db;
rc = check_db_cert_in_ram(CertList, dbsize, data, hash, dbname, guid);
FreePool(db);
return rc;
}
/*
* Check a hash against an EFI_SIGNATURE_LIST in a buffer
*/
static CHECK_STATUS check_db_hash_in_ram(EFI_SIGNATURE_LIST *CertList,
UINTN dbsize, UINT8 *data,
int SignatureSize, EFI_GUID CertType,
CHAR16 *dbname, EFI_GUID guid)
{
EFI_SIGNATURE_DATA *Cert;
UINTN CertCount, Index;
BOOLEAN IsFound = FALSE;
while ((dbsize > 0) && (dbsize >= CertList->SignatureListSize)) {
CertCount = (CertList->SignatureListSize -sizeof (EFI_SIGNATURE_LIST) - CertList->SignatureHeaderSize) / CertList->SignatureSize;
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) CertList + sizeof (EFI_SIGNATURE_LIST) + CertList->SignatureHeaderSize);
if (CompareGuid(&CertList->SignatureType, &CertType) == 0) {
for (Index = 0; Index < CertCount; Index++) {
if (CompareMem (Cert->SignatureData, data, SignatureSize) == 0) {
//
// Find the signature in database.
//
IsFound = TRUE;
tpm_measure_variable(dbname, guid, CertList->SignatureSize, Cert);
break;
}
Cert = (EFI_SIGNATURE_DATA *) ((UINT8 *) Cert + CertList->SignatureSize);
}
if (IsFound) {
break;
}
}
dbsize -= CertList->SignatureListSize;
CertList = (EFI_SIGNATURE_LIST *) ((UINT8 *) CertList + CertList->SignatureListSize);
}
if (IsFound)
return DATA_FOUND;
return DATA_NOT_FOUND;
}
/*
* Check a hash against an EFI_SIGNATURE_LIST in a UEFI variable
*/
static CHECK_STATUS check_db_hash(CHAR16 *dbname, EFI_GUID guid, UINT8 *data,
int SignatureSize, EFI_GUID CertType)
{
EFI_STATUS efi_status;
EFI_SIGNATURE_LIST *CertList;
UINTN dbsize = 0;
UINT8 *db;
efi_status = get_variable(dbname, &db, &dbsize, guid);
if (EFI_ERROR(efi_status)) {
return VAR_NOT_FOUND;
}
CertList = (EFI_SIGNATURE_LIST *)db;
CHECK_STATUS rc = check_db_hash_in_ram(CertList, dbsize, data,
SignatureSize, CertType,
dbname, guid);
FreePool(db);
return rc;
}
/*
* Check whether the binary signature or hash are present in dbx or the
* built-in denylist
*/
static EFI_STATUS check_denylist (WIN_CERTIFICATE_EFI_PKCS *cert,
UINT8 *sha256hash, UINT8 *sha1hash)
{
EFI_SIGNATURE_LIST *dbx = (EFI_SIGNATURE_LIST *)vendor_deauthorized;
if (check_db_hash_in_ram(dbx, vendor_deauthorized_size, sha256hash,
SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID, L"dbx",
EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
LogError(L"binary sha256hash found in vendor dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (check_db_hash_in_ram(dbx, vendor_deauthorized_size, sha1hash,
SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID, L"dbx",
EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
LogError(L"binary sha1hash found in vendor dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (cert &&
check_db_cert_in_ram(dbx, vendor_deauthorized_size, cert, sha256hash, L"dbx",
EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
LogError(L"cert sha256hash found in vendor dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha256hash,
SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
LogError(L"binary sha256hash found in system dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (check_db_hash(L"dbx", EFI_SECURE_BOOT_DB_GUID, sha1hash,
SHA1_DIGEST_SIZE, EFI_CERT_SHA1_GUID) == DATA_FOUND) {
LogError(L"binary sha1hash found in system dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (cert &&
check_db_cert(L"dbx", EFI_SECURE_BOOT_DB_GUID,
cert, sha256hash) == DATA_FOUND) {
LogError(L"cert sha256hash found in system dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (check_db_hash(L"MokListX", SHIM_LOCK_GUID, sha256hash,
SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID) == DATA_FOUND) {
LogError(L"binary sha256hash found in Mok dbx\n");
return EFI_SECURITY_VIOLATION;
}
if (cert &&
check_db_cert(L"MokListX", SHIM_LOCK_GUID,
cert, sha256hash) == DATA_FOUND) {
LogError(L"cert sha256hash found in Mok dbx\n");
return EFI_SECURITY_VIOLATION;
}
drain_openssl_errors();
return EFI_SUCCESS;
}
static void update_verification_method(verification_method_t method)
{
if (verification_method == VERIFIED_BY_NOTHING)
verification_method = method;
}
/*
* Check whether the binary signature or hash are present in db or MokList
*/
static EFI_STATUS check_allowlist (WIN_CERTIFICATE_EFI_PKCS *cert,
UINT8 *sha256hash, UINT8 *sha1hash)
{
if (!ignore_db) {
if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha256hash, SHA256_DIGEST_SIZE,
EFI_CERT_SHA256_GUID) == DATA_FOUND) {
update_verification_method(VERIFIED_BY_HASH);
return EFI_SUCCESS;
} else {
LogError(L"check_db_hash(db, sha256hash) != DATA_FOUND\n");
}
if (check_db_hash(L"db", EFI_SECURE_BOOT_DB_GUID, sha1hash, SHA1_DIGEST_SIZE,
EFI_CERT_SHA1_GUID) == DATA_FOUND) {
verification_method = VERIFIED_BY_HASH;
update_verification_method(VERIFIED_BY_HASH);
return EFI_SUCCESS;
} else {
LogError(L"check_db_hash(db, sha1hash) != DATA_FOUND\n");
}
if (cert && check_db_cert(L"db", EFI_SECURE_BOOT_DB_GUID, cert, sha256hash)
== DATA_FOUND) {
verification_method = VERIFIED_BY_CERT;
update_verification_method(VERIFIED_BY_CERT);
return EFI_SUCCESS;
} else if (cert) {
LogError(L"check_db_cert(db, sha256hash) != DATA_FOUND\n");
}
}
#if defined(VENDOR_DB_FILE)
EFI_SIGNATURE_LIST *db = (EFI_SIGNATURE_LIST *)vendor_db;
if (check_db_hash_in_ram(db, vendor_db_size,
sha256hash, SHA256_DIGEST_SIZE,
EFI_CERT_SHA256_GUID, L"vendor_db",
EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
verification_method = VERIFIED_BY_HASH;
update_verification_method(VERIFIED_BY_HASH);
return EFI_SUCCESS;
} else {
LogError(L"check_db_hash(vendor_db, sha256hash) != DATA_FOUND\n");
}
if (cert &&
check_db_cert_in_ram(db, vendor_db_size,
cert, sha256hash, L"vendor_db",
EFI_SECURE_BOOT_DB_GUID) == DATA_FOUND) {
verification_method = VERIFIED_BY_CERT;
update_verification_method(VERIFIED_BY_CERT);
return EFI_SUCCESS;
} else if (cert) {
LogError(L"check_db_cert(vendor_db, sha256hash) != DATA_FOUND\n");
}
#endif
if (check_db_hash(L"MokList", SHIM_LOCK_GUID, sha256hash,
SHA256_DIGEST_SIZE, EFI_CERT_SHA256_GUID)
== DATA_FOUND) {
verification_method = VERIFIED_BY_HASH;
update_verification_method(VERIFIED_BY_HASH);
return EFI_SUCCESS;
} else {
LogError(L"check_db_hash(MokList, sha256hash) != DATA_FOUND\n");
}
if (cert && check_db_cert(L"MokList", SHIM_LOCK_GUID, cert, sha256hash)
== DATA_FOUND) {
verification_method = VERIFIED_BY_CERT;
update_verification_method(VERIFIED_BY_CERT);
return EFI_SUCCESS;
} else if (cert) {
LogError(L"check_db_cert(MokList, sha256hash) != DATA_FOUND\n");
}
update_verification_method(VERIFIED_BY_NOTHING);
return EFI_NOT_FOUND;
}
/*
* Check whether we're in Secure Boot and user mode
*/
BOOLEAN secure_mode (void)
{
static int first = 1;
if (user_insecure_mode)
return FALSE;
if (variable_is_secureboot() != 1) {
if (verbose && !in_protocol && first)
console_notify(L"Secure boot not enabled");
first = 0;
return FALSE;
}
/* If we /do/ have "SecureBoot", but /don't/ have "SetupMode",
* then the implementation is bad, but we assume that secure boot is
* enabled according to the status of "SecureBoot". If we have both
* of them, then "SetupMode" may tell us additional data, and we need
* to consider it.
*/
if (variable_is_setupmode(0) == 1) {
if (verbose && !in_protocol && first)
console_notify(L"Platform is in setup mode");
first = 0;
return FALSE;
}
first = 0;
return TRUE;
}
static EFI_STATUS
verify_one_signature(WIN_CERTIFICATE_EFI_PKCS *sig,
UINT8 *sha256hash, UINT8 *sha1hash)
{
EFI_STATUS efi_status;
/*
* Ensure that the binary isn't forbidden
*/
drain_openssl_errors();
efi_status = check_denylist(sig, sha256hash, sha1hash);
if (EFI_ERROR(efi_status)) {
perror(L"Binary is forbidden: %r\n", efi_status);
PrintErrors();
ClearErrors();
crypterr(efi_status);
return efi_status;
}
/*
* Check whether the binary is authorized in any of the firmware
* databases
*/
drain_openssl_errors();
efi_status = check_allowlist(sig, sha256hash, sha1hash);
if (EFI_ERROR(efi_status)) {
if (efi_status != EFI_NOT_FOUND) {
dprint(L"check_allowlist(): %r\n", efi_status);
PrintErrors();
ClearErrors();
crypterr(efi_status);
}
} else {
drain_openssl_errors();
return efi_status;
}
efi_status = EFI_NOT_FOUND;
#if defined(ENABLE_SHIM_CERT)
/*
* Check against the shim build key
*/
drain_openssl_errors();
if (build_cert && build_cert_size) {
dprint("verifying against shim cert\n");
}
if (build_cert && build_cert_size &&
AuthenticodeVerify(sig->CertData,
sig->Hdr.dwLength - sizeof(sig->Hdr),
build_cert, build_cert_size, sha256hash,
SHA256_DIGEST_SIZE)) {
dprint(L"AuthenticodeVerify(shim_cert) succeeded\n");
update_verification_method(VERIFIED_BY_CERT);
tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
build_cert_size, build_cert);
efi_status = EFI_SUCCESS;
drain_openssl_errors();
return efi_status;
} else {
dprint(L"AuthenticodeVerify(shim_cert) failed\n");
PrintErrors();
ClearErrors();
crypterr(EFI_NOT_FOUND);
}
#endif /* defined(ENABLE_SHIM_CERT) */
#if defined(VENDOR_CERT_FILE)
/*
* And finally, check against shim's built-in key
*/
drain_openssl_errors();
if (vendor_cert_size) {
dprint("verifying against vendor_cert\n");
}
if (vendor_cert_size &&
AuthenticodeVerify(sig->CertData,
sig->Hdr.dwLength - sizeof(sig->Hdr),
vendor_cert, vendor_cert_size,
sha256hash, SHA256_DIGEST_SIZE)) {
dprint(L"AuthenticodeVerify(vendor_cert) succeeded\n");
update_verification_method(VERIFIED_BY_CERT);
tpm_measure_variable(L"Shim", SHIM_LOCK_GUID,
vendor_cert_size, vendor_cert);
efi_status = EFI_SUCCESS;
drain_openssl_errors();
return efi_status;
} else {
dprint(L"AuthenticodeVerify(vendor_cert) failed\n");
PrintErrors();
ClearErrors();
crypterr(EFI_NOT_FOUND);
}
#endif /* defined(VENDOR_CERT_FILE) */
return efi_status;
}
/*
* Check that the signature is valid and matches the binary
*/
EFI_STATUS
verify_buffer (char *data, int datasize,
PE_COFF_LOADER_IMAGE_CONTEXT *context,
UINT8 *sha256hash, UINT8 *sha1hash)
{
EFI_STATUS ret_efi_status;
size_t size = datasize;
size_t offset = 0;
unsigned int i = 0;
if (datasize < 0)
return EFI_INVALID_PARAMETER;
/*
* Clear OpenSSL's error log, because we get some DSO unimplemented
* errors during its intialization, and we don't want those to look
* like they're the reason for validation failures.
*/
drain_openssl_errors();
ret_efi_status = generate_hash(data, datasize, context, sha256hash, sha1hash);
if (EFI_ERROR(ret_efi_status)) {
dprint(L"generate_hash: %r\n", ret_efi_status);
PrintErrors();
ClearErrors();
crypterr(ret_efi_status);
return ret_efi_status;
}
/*
* Ensure that the binary isn't forbidden by hash
*/
drain_openssl_errors();
ret_efi_status = check_denylist(NULL, sha256hash, sha1hash);
if (EFI_ERROR(ret_efi_status)) {
// perror(L"Binary is forbidden\n");
// dprint(L"Binary is forbidden: %r\n", ret_efi_status);
PrintErrors();
ClearErrors();
crypterr(ret_efi_status);
return ret_efi_status;
}
/*
* Check whether the binary is authorized by hash in any of the
* firmware databases
*/
drain_openssl_errors();
ret_efi_status = check_allowlist(NULL, sha256hash, sha1hash);
if (EFI_ERROR(ret_efi_status)) {
LogError(L"check_allowlist(): %r\n", ret_efi_status);
dprint(L"check_allowlist: %r\n", ret_efi_status);
if (ret_efi_status != EFI_NOT_FOUND) {
dprint(L"check_allowlist(): %r\n", ret_efi_status);
PrintErrors();
ClearErrors();
crypterr(ret_efi_status);
return ret_efi_status;
}
} else {
drain_openssl_errors();
return ret_efi_status;
}
if (context->SecDir->Size == 0) {
dprint(L"No signatures found\n");
return EFI_SECURITY_VIOLATION;
}
if (context->SecDir->Size >= size) {
perror(L"Certificate Database size is too large\n");
return EFI_INVALID_PARAMETER;
}
ret_efi_status = EFI_NOT_FOUND;
do {
WIN_CERTIFICATE_EFI_PKCS *sig = NULL;
size_t sz;
sig = ImageAddress(data, size,
context->SecDir->VirtualAddress + offset);
if (!sig)
break;
sz = offset + offsetof(WIN_CERTIFICATE_EFI_PKCS, Hdr.dwLength)
+ sizeof(sig->Hdr.dwLength);
if (sz > context->SecDir->Size) {
perror(L"Certificate size is too large for secruity database");
return EFI_INVALID_PARAMETER;
}
sz = sig->Hdr.dwLength;
if (sz > context->SecDir->Size - offset) {
perror(L"Certificate size is too large for secruity database");
return EFI_INVALID_PARAMETER;
}
if (sz < sizeof(sig->Hdr)) {
perror(L"Certificate size is too small for certificate data");
return EFI_INVALID_PARAMETER;
}
if (sig->Hdr.wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
EFI_STATUS efi_status;
dprint(L"Attempting to verify signature %d:\n", i++);
efi_status = verify_one_signature(sig, sha256hash, sha1hash);
/*
* If we didn't get EFI_SECURITY_VIOLATION from
* checking the hashes above, then any dbx entries are
* for a certificate, not this individual binary.
*
* So don't clobber successes with security violation
* here; that just means it isn't a success.
*/
if (ret_efi_status != EFI_SUCCESS)
ret_efi_status = efi_status;
} else {
perror(L"Unsupported certificate type %x\n",
sig->Hdr.wCertificateType);
}
offset = ALIGN_VALUE(offset + sz, 8);
} while (offset < context->SecDir->Size);
if (ret_efi_status != EFI_SUCCESS) {
dprint(L"Binary is not authorized\n");
PrintErrors();
ClearErrors();
crypterr(EFI_SECURITY_VIOLATION);
ret_efi_status = EFI_SECURITY_VIOLATION;
}
drain_openssl_errors();
return ret_efi_status;
}
static int
should_use_fallback(EFI_HANDLE image_handle)
{
EFI_LOADED_IMAGE *li;
unsigned int pathlen = 0;
CHAR16 *bootpath = NULL;
EFI_FILE_IO_INTERFACE *fio = NULL;
EFI_FILE *vh = NULL;
EFI_FILE *fh = NULL;
EFI_STATUS efi_status;
int ret = 0;
efi_status = BS->HandleProtocol(image_handle, &EFI_LOADED_IMAGE_GUID,
(void **)&li);
if (EFI_ERROR(efi_status)) {
perror(L"Could not get image for boot" EFI_ARCH L".efi: %r\n",
efi_status);
return 0;
}
bootpath = DevicePathToStr(li->FilePath);
/* Check the beginning of the string and the end, to avoid
* caring about which arch this is. */
/* I really don't know why, but sometimes bootpath gives us
* L"\\EFI\\BOOT\\/BOOTX64.EFI". So just handle that here...
*/
if (StrnCaseCmp(bootpath, L"\\EFI\\BOOT\\BOOT", 14) &&
StrnCaseCmp(bootpath, L"\\EFI\\BOOT\\/BOOT", 15) &&
StrnCaseCmp(bootpath, L"EFI\\BOOT\\BOOT", 13) &&
StrnCaseCmp(bootpath, L"EFI\\BOOT\\/BOOT", 14))
goto error;
pathlen = StrLen(bootpath);
if (pathlen < 5 || StrCaseCmp(bootpath + pathlen - 4, L".EFI"))
goto error;
efi_status = BS->HandleProtocol(li->DeviceHandle, &FileSystemProtocol,
(void **) &fio);
if (EFI_ERROR(efi_status)) {
perror(L"Could not get fio for li->DeviceHandle: %r\n",
efi_status);
goto error;
}
efi_status = fio->OpenVolume(fio, &vh);
if (EFI_ERROR(efi_status)) {
perror(L"Could not open fio volume: %r\n", efi_status);
goto error;
}
efi_status = vh->Open(vh, &fh, L"\\EFI\\BOOT" FALLBACK,
EFI_FILE_MODE_READ, 0);
if (EFI_ERROR(efi_status)) {
/* Do not print the error here - this is an acceptable case
* for removable media, where we genuinely don't want
* fallback.efi to exist.
* Print(L"Could not open \"\\EFI\\BOOT%s\": %r\n", FALLBACK,
* efi_status);
*/
goto error;
}
ret = 1;
error:
if (fh)
fh->Close(fh);
if (vh)
vh->Close(vh);
if (bootpath)
FreePool(bootpath);
return ret;
}
/*
* Open the second stage bootloader and read it into a buffer
*/
static EFI_STATUS load_image (EFI_LOADED_IMAGE *li, void **data,
int *datasize, CHAR16 *PathName)
{
EFI_STATUS efi_status;
EFI_HANDLE device;
EFI_FILE_INFO *fileinfo = NULL;
EFI_FILE_IO_INTERFACE *drive;
EFI_FILE *root, *grub;
UINTN buffersize = sizeof(EFI_FILE_INFO);
device = li->DeviceHandle;
dprint(L"attempting to load %s\n", PathName);
/*
* Open the device
*/
efi_status = BS->HandleProtocol(device, &EFI_SIMPLE_FILE_SYSTEM_GUID,
(void **) &drive);
if (EFI_ERROR(efi_status)) {
perror(L"Failed to find fs: %r\n", efi_status);
goto error;
}
efi_status = drive->OpenVolume(drive, &root);
if (EFI_ERROR(efi_status)) {
perror(L"Failed to open fs: %r\n", efi_status);
goto error;
}
/*
* And then open the file
*/
efi_status = root->Open(root, &grub, PathName, EFI_FILE_MODE_READ, 0);
if (EFI_ERROR(efi_status)) {
perror(L"Failed to open %s - %r\n", PathName, efi_status);
goto error;
}
fileinfo = AllocatePool(buffersize);
if (!fileinfo) {
perror(L"Unable to allocate file info buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
/*
* Find out how big the file is in order to allocate the storage
* buffer
*/
efi_status = grub->GetInfo(grub, &EFI_FILE_INFO_GUID, &buffersize,
fileinfo);
if (efi_status == EFI_BUFFER_TOO_SMALL) {
FreePool(fileinfo);
fileinfo = AllocatePool(buffersize);
if (!fileinfo) {
perror(L"Unable to allocate file info buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
efi_status = grub->GetInfo(grub, &EFI_FILE_INFO_GUID,
&buffersize, fileinfo);
}
if (EFI_ERROR(efi_status)) {
perror(L"Unable to get file info: %r\n", efi_status);
goto error;
}
buffersize = fileinfo->FileSize;
*data = AllocatePool(buffersize);
if (!*data) {
perror(L"Unable to allocate file buffer\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto error;
}
/*
* Perform the actual read
*/
efi_status = grub->Read(grub, &buffersize, *data);
if (efi_status == EFI_BUFFER_TOO_SMALL) {
FreePool(*data);
*data = AllocatePool(buffersize);
efi_status = grub->Read(grub, &buffersize, *data);
}
if (EFI_ERROR(efi_status)) {
perror(L"Unexpected return from initial read: %r, buffersize %x\n",
efi_status, buffersize);
goto error;
}
*datasize = buffersize;
FreePool(fileinfo);
return EFI_SUCCESS;
error:
if (*data) {
FreePool(*data);
*data = NULL;
}
if (fileinfo)
FreePool(fileinfo);
return efi_status;
}
/*
* Protocol entry point. If secure boot is enabled, verify that the provided
* buffer is signed with a trusted key.
*/
EFI_STATUS shim_verify (void *buffer, UINT32 size)
{
EFI_STATUS efi_status = EFI_SUCCESS;
PE_COFF_LOADER_IMAGE_CONTEXT context;
UINT8 sha1hash[SHA1_DIGEST_SIZE];
UINT8 sha256hash[SHA256_DIGEST_SIZE];
if ((INT32)size < 0)
return EFI_INVALID_PARAMETER;
loader_is_participating = 1;
in_protocol = 1;
efi_status = read_header(buffer, size, &context);
if (EFI_ERROR(efi_status))
goto done;
efi_status = generate_hash(buffer, size, &context,
sha256hash, sha1hash);
if (EFI_ERROR(efi_status))
goto done;
/* Measure the binary into the TPM */
#ifdef REQUIRE_TPM
efi_status =
#endif
tpm_log_pe((EFI_PHYSICAL_ADDRESS)(UINTN)buffer, size, 0, NULL,
sha1hash, 4);
#ifdef REQUIRE_TPM
if (EFI_ERROR(efi_status))
goto done;
#endif
if (!secure_mode()) {
efi_status = EFI_SUCCESS;
goto done;
}
efi_status = verify_buffer(buffer, size,
&context, sha256hash, sha1hash);
done:
in_protocol = 0;
return efi_status;
}
static EFI_STATUS shim_hash (char *data, int datasize,
PE_COFF_LOADER_IMAGE_CONTEXT *context,
UINT8 *sha256hash, UINT8 *sha1hash)
{
EFI_STATUS efi_status;
if (datasize < 0)
return EFI_INVALID_PARAMETER;
in_protocol = 1;
efi_status = generate_hash(data, datasize, context,
sha256hash, sha1hash);
in_protocol = 0;
return efi_status;
}
static EFI_STATUS shim_read_header(void *data, unsigned int datasize,
PE_COFF_LOADER_IMAGE_CONTEXT *context)
{
EFI_STATUS efi_status;
in_protocol = 1;
efi_status = read_header(data, datasize, context);
in_protocol = 0;
return efi_status;
}
VOID
restore_loaded_image(VOID)
{
if (shim_li->FilePath)
FreePool(shim_li->FilePath);
/*
* Restore our original loaded image values
*/
CopyMem(shim_li, &shim_li_bak, sizeof(shim_li_bak));
}
/*
* Load and run an EFI executable
*/
EFI_STATUS start_image(EFI_HANDLE image_handle, CHAR16 *ImagePath)
{
EFI_STATUS efi_status;
EFI_IMAGE_ENTRY_POINT entry_point;
EFI_PHYSICAL_ADDRESS alloc_address;
UINTN alloc_pages;
CHAR16 *PathName = NULL;
void *sourcebuffer = NULL;
UINT64 sourcesize = 0;
void *data = NULL;
int datasize = 0;
/*
* We need to refer to the loaded image protocol on the running
* binary in order to find our path
*/
efi_status = BS->HandleProtocol(image_handle, &EFI_LOADED_IMAGE_GUID,
(void **)&shim_li);
if (EFI_ERROR(efi_status)) {
perror(L"Unable to init protocol\n");
return efi_status;
}
/*
* Build a new path from the existing one plus the executable name
*/
efi_status = generate_path_from_image_path(shim_li, ImagePath, &PathName);
if (EFI_ERROR(efi_status)) {
perror(L"Unable to generate path %s: %r\n", ImagePath,
efi_status);
goto done;
}
if (findNetboot(shim_li->DeviceHandle)) {
efi_status = parseNetbootinfo(image_handle);
if (EFI_ERROR(efi_status)) {
perror(L"Netboot parsing failed: %r\n", efi_status);
return EFI_PROTOCOL_ERROR;
}
efi_status = FetchNetbootimage(image_handle, &sourcebuffer,
&sourcesize);
if (EFI_ERROR(efi_status)) {
perror(L"Unable to fetch TFTP image: %r\n",
efi_status);
return efi_status;
}
data = sourcebuffer;
datasize = sourcesize;
} else if (find_httpboot(shim_li->DeviceHandle)) {
efi_status = httpboot_fetch_buffer (image_handle,
&sourcebuffer,
&sourcesize);
if (EFI_ERROR(efi_status)) {
perror(L"Unable to fetch HTTP image: %r\n",
efi_status);
return efi_status;
}
data = sourcebuffer;
datasize = sourcesize;
} else {
/*
* Read the new executable off disk
*/
efi_status = load_image(shim_li, &data, &datasize, PathName);
if (EFI_ERROR(efi_status)) {
perror(L"Failed to load image %s: %r\n",
PathName, efi_status);
PrintErrors();
ClearErrors();
goto done;
}
}
if (datasize < 0) {
efi_status = EFI_INVALID_PARAMETER;
goto done;
}
/*
* We need to modify the loaded image protocol entry before running
* the new binary, so back it up
*/
CopyMem(&shim_li_bak, shim_li, sizeof(shim_li_bak));
/*
* Update the loaded image with the second stage loader file path
*/
shim_li->FilePath = FileDevicePath(NULL, PathName);
if (!shim_li->FilePath) {
perror(L"Unable to update loaded image file path\n");
efi_status = EFI_OUT_OF_RESOURCES;
goto restore;
}
/*
* Verify and, if appropriate, relocate and execute the executable
*/
efi_status = handle_image(data, datasize, shim_li, &entry_point,
&alloc_address, &alloc_pages);
if (EFI_ERROR(efi_status)) {
perror(L"Failed to load image: %r\n", efi_status);
PrintErrors();
ClearErrors();
goto restore;
}
loader_is_participating = 0;
/*
* The binary is trusted and relocated. Run it
*/
efi_status = entry_point(image_handle, systab);
restore:
restore_loaded_image();
done:
if (PathName)
FreePool(PathName);
if (data)
FreePool(data);
return efi_status;
}
/*
* Load and run grub. If that fails because grub isn't trusted, load and
* run MokManager.
*/
EFI_STATUS init_grub(EFI_HANDLE image_handle)
{
EFI_STATUS efi_status;
int use_fb = should_use_fallback(image_handle);
efi_status = start_image(image_handle, use_fb ? FALLBACK :second_stage);
if (efi_status == EFI_SECURITY_VIOLATION ||
efi_status == EFI_ACCESS_DENIED) {
efi_status = start_image(image_handle, MOK_MANAGER);
if (EFI_ERROR(efi_status)) {
console_print(L"start_image() returned %r\n", efi_status);
msleep(2000000);
return efi_status;
}
efi_status = start_image(image_handle,
use_fb ? FALLBACK : second_stage);
}
if (EFI_ERROR(efi_status)) {
console_print(L"start_image() returned %r\n", efi_status);
msleep(2000000);
}
return efi_status;
}
/*
* Check the load options to specify the second stage loader
*/
EFI_STATUS set_second_stage (EFI_HANDLE image_handle)
{
EFI_STATUS efi_status;
EFI_LOADED_IMAGE *li = NULL;
second_stage = DEFAULT_LOADER;
load_options = NULL;
load_options_size = 0;
efi_status = BS->HandleProtocol(image_handle, &LoadedImageProtocol,
(void **) &li);
if (EFI_ERROR(efi_status)) {
perror (L"Failed to get load options: %r\n", efi_status);
return efi_status;
}
efi_status = parse_load_options(li);
if (EFI_ERROR(efi_status)) {
perror (L"Failed to get load options: %r\n", efi_status);
return efi_status;
}
return EFI_SUCCESS;
}
static void *
ossl_malloc(size_t num)
{
return AllocatePool(num);
}
static void
ossl_free(void *addr)
{
FreePool(addr);
}
static void
init_openssl(void)
{
CRYPTO_set_mem_functions(ossl_malloc, NULL, ossl_free);
OPENSSL_init();
CRYPTO_set_mem_functions(ossl_malloc, NULL, ossl_free);
ERR_load_ERR_strings();
ERR_load_BN_strings();
ERR_load_RSA_strings();
ERR_load_DH_strings();
ERR_load_EVP_strings();
ERR_load_BUF_strings();
ERR_load_OBJ_strings();
ERR_load_PEM_strings();
ERR_load_X509_strings();
ERR_load_ASN1_strings();
ERR_load_CONF_strings();
ERR_load_CRYPTO_strings();
ERR_load_COMP_strings();
ERR_load_BIO_strings();
ERR_load_PKCS7_strings();
ERR_load_X509V3_strings();
ERR_load_PKCS12_strings();
ERR_load_RAND_strings();
ERR_load_DSO_strings();
ERR_load_OCSP_strings();
}
static SHIM_LOCK shim_lock_interface;
static EFI_HANDLE shim_lock_handle;
EFI_STATUS
install_shim_protocols(void)
{
SHIM_LOCK *shim_lock;
EFI_STATUS efi_status;
/*
* Did another instance of shim earlier already install the
* protocol? If so, get rid of it.
*
* We have to uninstall shim's protocol here, because if we're
* On the fallback.efi path, then our call pathway is:
*
* shim->fallback->shim->grub
* ^ ^ ^
* | | \- gets protocol #0
* | \- installs its protocol (#1)
* \- installs its protocol (#0)
* and if we haven't removed this, then grub will get the *first*
* shim's protocol, but it'll get the second shim's systab
* replacements. So even though it will participate and verify
* the kernel, the systab never finds out.
*/
efi_status = LibLocateProtocol(&SHIM_LOCK_GUID, (VOID **)&shim_lock);
if (!EFI_ERROR(efi_status))
uninstall_shim_protocols();
/*
* Install the protocol
*/
efi_status = BS->InstallProtocolInterface(&shim_lock_handle,
&SHIM_LOCK_GUID,
EFI_NATIVE_INTERFACE,
&shim_lock_interface);
if (EFI_ERROR(efi_status)) {
console_error(L"Could not install security protocol",
efi_status);
return efi_status;
}
if (!secure_mode())
return EFI_SUCCESS;
#if defined(OVERRIDE_SECURITY_POLICY)
/*
* Install the security protocol hook
*/
security_policy_install(shim_verify);
#endif
return EFI_SUCCESS;
}
void
uninstall_shim_protocols(void)
{
/*
* If we're back here then clean everything up before exiting
*/
BS->UninstallProtocolInterface(shim_lock_handle, &SHIM_LOCK_GUID,
&shim_lock_interface);
if (!secure_mode())
return;
#if defined(OVERRIDE_SECURITY_POLICY)
/*
* Clean up the security protocol hook
*/
security_policy_uninstall();
#endif
}
EFI_STATUS
shim_init(void)
{
EFI_STATUS efi_status;
dprint(L"%a", shim_version);
/* Set the second stage loader */
efi_status = set_second_stage(global_image_handle);
if (EFI_ERROR(efi_status)) {
perror(L"set_second_stage() failed: %r\n", efi_status);
return efi_status;
}
if (secure_mode()) {
if (vendor_authorized_size || vendor_deauthorized_size) {
/*
* If shim includes its own certificates then ensure
* that anything it boots has performed some
* validation of the next image.
*/
hook_system_services(systab);
loader_is_participating = 0;
}
}
hook_exit(systab);
efi_status = install_shim_protocols();
if (EFI_ERROR(efi_status))
perror(L"install_shim_protocols() failed: %r\n", efi_status);
return efi_status;
}
void
shim_fini(void)
{
if (secure_mode())
cleanup_sbat_var(&sbat_var);
/*
* Remove our protocols
*/
uninstall_shim_protocols();
if (secure_mode()) {
/*
* Remove our hooks from system services.
*/
unhook_system_services();
}
unhook_exit();
console_fini();
}
extern EFI_STATUS
efi_main(EFI_HANDLE passed_image_handle, EFI_SYSTEM_TABLE *passed_systab);
static void
__attribute__((__optimize__("0")))
debug_hook(void)
{
UINT8 *data = NULL;
UINTN dataSize = 0;
EFI_STATUS efi_status;
register volatile UINTN x = 0;
extern char _text, _data;
const CHAR16 * const debug_var_name =
#ifdef ENABLE_SHIM_DEVEL
L"SHIM_DEVEL_DEBUG";
#else
L"SHIM_DEBUG";
#endif
if (x)
return;
efi_status = get_variable(debug_var_name, &data, &dataSize,
SHIM_LOCK_GUID);
if (EFI_ERROR(efi_status)) {
return;
}
FreePool(data);
console_print(L"add-symbol-file "DEBUGDIR
L"shim" EFI_ARCH L".efi.debug 0x%08x -s .data 0x%08x\n",
&_text, &_data);
console_print(L"Pausing for debugger attachment.\n");
console_print(L"To disable this, remove the EFI variable %s-%g .\n",
debug_var_name, &SHIM_LOCK_GUID);
x = 1;
while (x++) {
/* Make this so it can't /totally/ DoS us. */
#if defined(__x86_64__) || defined(__i386__) || defined(__i686__)
if (x > 4294967294ULL)
break;
#elif defined(__aarch64__)
if (x > 1000)
break;
#else
if (x > 12000)
break;
#endif
wait_for_debug();
}
x = 1;
}
typedef enum {
COLD_RESET,
EXIT_FAILURE,
EXIT_SUCCESS, // keep this one last
} devel_egress_action;
void
devel_egress(devel_egress_action action UNUSED)
{
#ifdef ENABLE_SHIM_DEVEL
char *reasons[] = {
[COLD_RESET] = "reset",
[EXIT_FAILURE] = "exit",
};
if (action == EXIT_SUCCESS)
return;
console_print(L"Waiting to %a...", reasons[action]);
for (size_t sleepcount = 0; sleepcount < 10; sleepcount++) {
console_print(L"%d...", 10 - sleepcount);
msleep(1000000);
}
console_print(L"\ndoing %a\n", action);
if (action == COLD_RESET)
RT->ResetSystem(EfiResetCold, EFI_SECURITY_VIOLATION, 0, NULL);
#endif
}
EFI_STATUS
efi_main (EFI_HANDLE passed_image_handle, EFI_SYSTEM_TABLE *passed_systab)
{
EFI_STATUS efi_status;
EFI_HANDLE image_handle;
verification_method = VERIFIED_BY_NOTHING;
vendor_authorized_size = cert_table.vendor_authorized_size;
vendor_authorized = (UINT8 *)&cert_table + cert_table.vendor_authorized_offset;
vendor_deauthorized_size = cert_table.vendor_deauthorized_size;
vendor_deauthorized = (UINT8 *)&cert_table + cert_table.vendor_deauthorized_offset;
#if defined(ENABLE_SHIM_CERT)
build_cert_size = sizeof(shim_cert);
build_cert = shim_cert;
#endif /* defined(ENABLE_SHIM_CERT) */
CHAR16 *msgs[] = {
L"import_mok_state() failed",
L"shim_init() failed",
L"import of SBAT data failed",
L"SBAT self-check failed",
SBAT_VAR_NAME L" UEFI variable setting failed",
NULL
};
enum {
IMPORT_MOK_STATE,
SHIM_INIT,
IMPORT_SBAT,
SBAT_SELF_CHECK,
SET_SBAT,
} msg = IMPORT_MOK_STATE;
/*
* Set up the shim lock protocol so that grub and MokManager can
* call back in and use shim functions
*/
shim_lock_interface.Verify = shim_verify;
shim_lock_interface.Hash = shim_hash;
shim_lock_interface.Context = shim_read_header;
systab = passed_systab;
image_handle = global_image_handle = passed_image_handle;
/*
* Ensure that gnu-efi functions are available
*/
InitializeLib(image_handle, systab);
setup_verbosity();
dprint(L"vendor_authorized:0x%08lx vendor_authorized_size:%lu\n",
vendor_authorized, vendor_authorized_size);
dprint(L"vendor_deauthorized:0x%08lx vendor_deauthorized_size:%lu\n",
vendor_deauthorized, vendor_deauthorized_size);
/*
* if SHIM_DEBUG is set, wait for a debugger to attach.
*/
debug_hook();
efi_status = set_sbat_uefi_variable();
if (EFI_ERROR(efi_status) && secure_mode()) {
perror(L"%s variable initialization failed\n", SBAT_VAR_NAME);
msg = SET_SBAT;
goto die;
} else if (EFI_ERROR(efi_status)) {
dprint(L"%s variable initialization failed: %r\n",
SBAT_VAR_NAME, efi_status);
}
if (secure_mode()) {
char *sbat_start = (char *)&_sbat;
char *sbat_end = (char *)&_esbat;
INIT_LIST_HEAD(&sbat_var);
efi_status = parse_sbat_var(&sbat_var);
if (EFI_ERROR(efi_status)) {
perror(L"Parsing %s variable failed: %r\n",
SBAT_VAR_NAME, efi_status);
msg = IMPORT_SBAT;
goto die;
}
efi_status = handle_sbat(sbat_start, sbat_end - sbat_start - 1);
if (EFI_ERROR(efi_status)) {
perror(L"Verifiying shim SBAT data failed: %r\n",
efi_status);
msg = SBAT_SELF_CHECK;
goto die;
}
dprint(L"SBAT self-check succeeded\n");
}
init_openssl();
/*
* Before we do anything else, validate our non-volatile,
* boot-services-only state variables are what we think they are.
*/
efi_status = import_mok_state(image_handle);
if (!secure_mode() &&
(efi_status == EFI_INVALID_PARAMETER ||
efi_status == EFI_OUT_OF_RESOURCES)) {
/*
* Make copy failures fatal only if secure_mode is enabled, or
* the error was anything else than EFI_INVALID_PARAMETER or
* EFI_OUT_OF_RESOURCES.
* There are non-secureboot firmware implementations that don't
* reserve enough EFI variable memory to fit the variable.
*/
console_print(L"Importing MOK states has failed: %s: %r\n",
msgs[msg], efi_status);
console_print(L"Continuing boot since secure mode is disabled");
} else if (EFI_ERROR(efi_status)) {
die:
console_print(L"Something has gone seriously wrong: %s: %r\n",
msgs[msg], efi_status);
#if defined(ENABLE_SHIM_DEVEL)
devel_egress(COLD_RESET);
#else
msleep(5000000);
RT->ResetSystem(EfiResetShutdown, EFI_SECURITY_VIOLATION,
0, NULL);
#endif
}
efi_status = shim_init();
if (EFI_ERROR(efi_status)) {
msg = SHIM_INIT;
goto die;
}
/*
* Tell the user that we're in insecure mode if necessary
*/
if (user_insecure_mode) {
console_print(L"Booting in insecure mode\n");
msleep(2000000);
}
/*
* Hand over control to the second stage bootloader
*/
efi_status = init_grub(image_handle);
shim_fini();
devel_egress(EFI_ERROR(efi_status) ? EXIT_FAILURE : EXIT_SUCCESS);
return efi_status;
}
|
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Binary for training Tensorflow models on the YouTube-8M dataset."""
import json
import os
import time
import eval_util
import export_model
import losses
import frame_level_models
import video_level_models
import readers
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow import app
from tensorflow import flags
from tensorflow import gfile
from tensorflow import logging
from tensorflow.python.client import device_lib
import utils
FLAGS = flags.FLAGS
if __name__ == "__main__":
# Dataset flags.
flags.DEFINE_string("train_dir", "/tmp/yt8m_model/",
"The directory to save the model files in.")
flags.DEFINE_string(
"train_data_pattern", "",
"File glob for the training dataset. If the files refer to Frame Level "
"features (i.e. tensorflow.SequenceExample), then set --reader_type "
"format. The (Sequence)Examples are expected to have 'rgb' byte array "
"sequence feature as well as a 'labels' int64 context feature.")
flags.DEFINE_string("feature_names", "mean_rgb", "Name of the feature "
"to use for training.")
flags.DEFINE_string("feature_sizes", "1024", "Length of the feature vectors.")
# Model flags.
flags.DEFINE_bool(
"frame_features", False,
"If set, then --train_data_pattern must be frame-level features. "
"Otherwise, --train_data_pattern must be aggregated video-level "
"features. The model must also be set appropriately (i.e. to read 3D "
"batches VS 4D batches.")
flags.DEFINE_string(
"model", "LogisticModel",
"Which architecture to use for the model. Models are defined "
"in models.py.")
flags.DEFINE_bool(
"start_new_model", False,
"If set, this will not resume from a checkpoint and will instead create a"
" new model instance.")
# Training flags.
flags.DEFINE_integer("num_gpu", 1,
"The maximum number of GPU devices to use for training. "
"Flag only applies if GPUs are installed")
flags.DEFINE_integer("batch_size", 1024,
"How many examples to process per batch for training.")
flags.DEFINE_string("label_loss", "CrossEntropyLoss",
"Which loss function to use for training the model.")
flags.DEFINE_float(
"regularization_penalty", 1.0,
"How much weight to give to the regularization loss (the label loss has "
"a weight of 1).")
flags.DEFINE_float("base_learning_rate", 0.0001,
"Which learning rate to start with.")
flags.DEFINE_float("learning_rate_decay", 0.9,
"Learning rate decay factor to be applied every "
"learning_rate_decay_examples.")
flags.DEFINE_float("learning_rate_decay_examples", 4000000,
"Multiply current learning rate by learning_rate_decay "
"every learning_rate_decay_examples.")
flags.DEFINE_integer("num_epochs", 5,
"How many passes to make over the dataset before "
"halting training.")
flags.DEFINE_integer("max_steps", None,
"The maximum number of iterations of the training loop.")
flags.DEFINE_integer("export_model_steps", 10000,
"The period, in number of steps, with which the model "
"is exported for batch prediction.")
# Other flags.
flags.DEFINE_integer("num_readers", 8,
"How many threads to use for reading input files.")
flags.DEFINE_string("optimizer", "AdamOptimizer",
"What optimizer class to use.")
flags.DEFINE_float("clip_gradient_norm", 1.0, "Norm to clip gradients to.")
flags.DEFINE_bool(
"log_device_placement", False,
"Whether to write the device on which every op will run into the "
"logs on startup.")
flags.DEFINE_integer("seed", 2018,
"seed.")
tf.set_random_seed(FLAGS.seed)
def validate_class_name(flag_value, category, modules, expected_superclass):
"""Checks that the given string matches a class of the expected type.
Args:
flag_value: A string naming the class to instantiate.
category: A string used further describe the class in error messages
(e.g. 'model', 'reader', 'loss').
modules: A list of modules to search for the given class.
expected_superclass: A class that the given class should inherit from.
Raises:
FlagsError: If the given class could not be found or if the first class
found with that name doesn't inherit from the expected superclass.
Returns:
True if a class was found that matches the given constraints.
"""
candidates = [getattr(module, flag_value, None) for module in modules]
for candidate in candidates:
if not candidate:
continue
if not issubclass(candidate, expected_superclass):
raise flags.FlagsError("%s '%s' doesn't inherit from %s." %
(category, flag_value,
expected_superclass.__name__))
return True
raise flags.FlagsError("Unable to find %s '%s'." % (category, flag_value))
def get_input_data_tensors(reader,
data_pattern,
batch_size=1000,
num_epochs=None,
num_readers=1):
"""Creates the section of the graph which reads the training data.
Args:
reader: A class which parses the training data.
data_pattern: A 'glob' style path to the data files.
batch_size: How many examples to process at a time.
num_epochs: How many passes to make over the training data. Set to 'None'
to run indefinitely.
num_readers: How many I/O threads to use.
Returns:
A tuple containing the features tensor, labels tensor, and optionally a
tensor containing the number of frames per video. The exact dimensions
depend on the reader being used.
Raises:
IOError: If no files matching the given pattern were found.
"""
logging.info("Using batch size of " + str(batch_size) + " for training.")
with tf.name_scope("train_input"):
files = gfile.Glob(data_pattern)
if not files:
raise IOError("Unable to find training files. data_pattern='" +
data_pattern + "'.")
logging.info("Number of training files: %s.", str(len(files)))
filename_queue = tf.train.string_input_producer(
files, num_epochs=num_epochs, shuffle=True)
training_data = [
reader.prepare_reader(filename_queue) for _ in range(num_readers)
]
return tf.train.shuffle_batch_join(
training_data,
batch_size=batch_size,
capacity=batch_size * 5,
min_after_dequeue=batch_size,
allow_smaller_final_batch=True,
enqueue_many=True)
def find_class_by_name(name, modules):
"""Searches the provided modules for the named class and returns it."""
modules = [getattr(module, name, None) for module in modules]
return next(a for a in modules if a)
def build_graph(reader,
model,
train_data_pattern,
label_loss_fn=losses.CrossEntropyLoss(),
batch_size=1000,
base_learning_rate=0.01,
learning_rate_decay_examples=1000000,
learning_rate_decay=0.95,
optimizer_class=tf.train.AdamOptimizer,
clip_gradient_norm=1.0,
regularization_penalty=1,
num_readers=1,
num_epochs=None):
"""Creates the Tensorflow graph.
This will only be called once in the life of
a training model, because after the graph is created the model will be
restored from a meta graph file rather than being recreated.
Args:
reader: The data file reader. It should inherit from BaseReader.
model: The core model (e.g. logistic or neural net). It should inherit
from BaseModel.
train_data_pattern: glob path to the training data files.
label_loss_fn: What kind of loss to apply to the model. It should inherit
from BaseLoss.
batch_size: How many examples to process at a time.
base_learning_rate: What learning rate to initialize the optimizer with.
optimizer_class: Which optimization algorithm to use.
clip_gradient_norm: Magnitude of the gradient to clip to.
regularization_penalty: How much weight to give the regularization loss
compared to the label loss.
num_readers: How many threads to use for I/O operations.
num_epochs: How many passes to make over the data. 'None' means an
unlimited number of passes.
"""
global_step = tf.Variable(0, trainable=False, name="global_step")
local_device_protos = device_lib.list_local_devices()
gpus = [x.name for x in local_device_protos if x.device_type == 'GPU']
gpus = gpus[:FLAGS.num_gpu]
num_gpus = len(gpus)
if num_gpus > 0:
logging.info("Using the following GPUs to train: " + str(gpus))
num_towers = num_gpus
device_string = '/gpu:%d'
else:
logging.info("No GPUs found. Training on CPU.")
num_towers = 1
device_string = '/cpu:%d'
learning_rate = tf.train.exponential_decay(
base_learning_rate,
global_step * batch_size * num_towers,
learning_rate_decay_examples,
learning_rate_decay,
staircase=True)
tf.summary.scalar('learning_rate', learning_rate)
optimizer = optimizer_class(learning_rate)
unused_video_id, model_input_raw, labels_batch, num_frames = (
get_input_data_tensors(
reader,
train_data_pattern,
batch_size=batch_size * num_towers,
num_readers=num_readers,
num_epochs=num_epochs))
tf.summary.histogram("model/input_raw", model_input_raw)
feature_dim = len(model_input_raw.get_shape()) - 1
model_input = tf.nn.l2_normalize(model_input_raw, feature_dim)
tower_inputs = tf.split(model_input, num_towers)
tower_labels = tf.split(labels_batch, num_towers)
tower_num_frames = tf.split(num_frames, num_towers)
tower_gradients = []
tower_predictions = []
tower_label_losses = []
tower_reg_losses = []
for i in range(num_towers):
# For some reason these 'with' statements can't be combined onto the same
# line. They have to be nested.
with tf.device(device_string % i):
with (tf.variable_scope(("tower"), reuse=True if i > 0 else None)):
with (slim.arg_scope([slim.model_variable, slim.variable], device="/cpu:0" if num_gpus != 1 else "/gpu:0")):
result = model.create_model(
tower_inputs[i],
num_frames=tower_num_frames[i],
vocab_size=reader.num_classes,
labels=tower_labels[i])
for variable in slim.get_model_variables():
tf.summary.histogram(variable.op.name, variable)
predictions = result["predictions"]
tower_predictions.append(predictions)
if "loss" in result.keys():
label_loss = result["loss"]
else:
label_loss = label_loss_fn.calculate_loss(predictions, tower_labels[i])
if "regularization_loss" in result.keys():
reg_loss = result["regularization_loss"]
else:
reg_loss = tf.constant(0.0)
reg_losses = tf.losses.get_regularization_losses()
if reg_losses:
reg_loss += tf.add_n(reg_losses)
tower_reg_losses.append(reg_loss)
# Adds update_ops (e.g., moving average updates in batch normalization) as
# a dependency to the train_op.
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
if "update_ops" in result.keys():
update_ops += result["update_ops"]
if update_ops:
with tf.control_dependencies(update_ops):
barrier = tf.no_op(name="gradient_barrier")
with tf.control_dependencies([barrier]):
label_loss = tf.identity(label_loss)
tower_label_losses.append(label_loss)
# Incorporate the L2 weight penalties etc.
final_loss = regularization_penalty * reg_loss + label_loss
gradients = optimizer.compute_gradients(final_loss,
colocate_gradients_with_ops=False)
tower_gradients.append(gradients)
label_loss = tf.reduce_mean(tf.stack(tower_label_losses))
tf.summary.scalar("label_loss", label_loss)
if regularization_penalty != 0:
reg_loss = tf.reduce_mean(tf.stack(tower_reg_losses))
tf.summary.scalar("reg_loss", reg_loss)
merged_gradients = utils.combine_gradients(tower_gradients)
if clip_gradient_norm > 0:
with tf.name_scope('clip_grads'):
merged_gradients = utils.clip_gradient_norms(merged_gradients, clip_gradient_norm)
train_op = optimizer.apply_gradients(merged_gradients, global_step=global_step)
tf.add_to_collection("global_step", global_step)
tf.add_to_collection("loss", label_loss)
tf.add_to_collection("predictions", tf.concat(tower_predictions, 0))
tf.add_to_collection("input_batch_raw", model_input_raw)
tf.add_to_collection("input_batch", model_input)
tf.add_to_collection("num_frames", num_frames)
tf.add_to_collection("labels", tf.cast(labels_batch, tf.float32))
tf.add_to_collection("train_op", train_op)
class Trainer(object):
"""A Trainer to train a Tensorflow graph."""
def __init__(self, cluster, task, train_dir, model, reader, model_exporter,
log_device_placement=True, max_steps=None,
export_model_steps=1000):
""""Creates a Trainer.
Args:
cluster: A tf.train.ClusterSpec if the execution is distributed.
None otherwise.
task: A TaskSpec describing the job type and the task index.
"""
self.cluster = cluster
self.task = task
self.is_master = (task.type == "master" and task.index == 0)
self.train_dir = train_dir
# gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)
self.config = tf.ConfigProto(
allow_soft_placement=True, log_device_placement=log_device_placement)
# self.config.gpu_options.allow_growth = True
self.model = model
self.reader = reader
self.model_exporter = model_exporter
self.max_steps = max_steps
self.max_steps_reached = False
self.export_model_steps = export_model_steps
self.last_model_export_step = 0
# if self.is_master and self.task.index > 0:
# raise StandardError("%s: Only one replica of master expected",
# task_as_string(self.task))
def run(self, start_new_model=False):
"""Performs training on the currently defined Tensorflow graph.
Returns:
A tuple of the training Hit@1 and the training PERR.
"""
if self.is_master and start_new_model:
self.remove_training_directory(self.train_dir)
if not os.path.exists(self.train_dir):
os.makedirs(self.train_dir)
model_flags_dict = {
"model": FLAGS.model,
"feature_sizes": FLAGS.feature_sizes,
"feature_names": FLAGS.feature_names,
"frame_features": FLAGS.frame_features,
"label_loss": FLAGS.label_loss,
}
flags_json_path = os.path.join(FLAGS.train_dir, "model_flags.json")
if os.path.exists(flags_json_path):
existing_flags = json.load(open(flags_json_path))
if existing_flags != model_flags_dict:
logging.error("Model flags do not match existing file %s. Please "
"delete the file, change --train_dir, or pass flag "
"--start_new_model",
flags_json_path)
logging.error("Ran model with flags: %s", str(model_flags_dict))
logging.error("Previously ran with flags: %s", str(existing_flags))
exit(1)
else:
# Write the file.
with open(flags_json_path, "w") as fout:
fout.write(json.dumps(model_flags_dict))
target, device_fn = self.start_server_if_distributed()
meta_filename = self.get_meta_filename(start_new_model, self.train_dir)
with tf.Graph().as_default() as graph:
if meta_filename:
saver = self.recover_model(meta_filename)
with tf.device(device_fn):
if not meta_filename:
saver = self.build_model(self.model, self.reader)
# saver = self.build_model(self.model, self.reader)
global_step = tf.get_collection("global_step")[0]
loss = tf.get_collection("loss")[0]
predictions = tf.get_collection("predictions")[0]
labels = tf.get_collection("labels")[0]
train_op = tf.get_collection("train_op")[0]
init_op = tf.global_variables_initializer()
sv = tf.train.Supervisor(
graph,
logdir=self.train_dir,
init_op=init_op,
is_chief=self.is_master,
global_step=global_step,
save_model_secs=0,
save_summaries_secs=120,
saver=saver)
logging.info("%s: Starting managed session.", task_as_string(self.task))
with sv.managed_session(target, config=self.config) as sess:
try:
logging.info("%s: Entering training loop.", task_as_string(self.task))
while (not sv.should_stop()) and (not self.max_steps_reached):
batch_start_time = time.time()
_, global_step_val, loss_val, predictions_val, labels_val = sess.run(
[train_op, global_step, loss, predictions, labels])
seconds_per_batch = time.time() - batch_start_time
examples_per_second = labels_val.shape[0] / seconds_per_batch
if self.max_steps and self.max_steps <= global_step_val:
self.max_steps_reached = True
if self.is_master and global_step_val % 10 == 0 and self.train_dir:
eval_start_time = time.time()
hit_at_one = eval_util.calculate_hit_at_one(predictions_val, labels_val)
perr = eval_util.calculate_precision_at_equal_recall_rate(predictions_val,
labels_val)
gap = eval_util.calculate_gap(predictions_val, labels_val)
eval_end_time = time.time()
eval_time = eval_end_time - eval_start_time
logging.info("training step " + str(global_step_val) + " | Loss: " + ("%.2f" % loss_val) +
" Examples/sec: " + ("%.2f" % examples_per_second) + " | Hit@1: " +
("%.2f" % hit_at_one) + " PERR: " + ("%.2f" % perr) +
" GAP: " + ("%.2f" % gap))
sv.summary_writer.add_summary(
utils.MakeSummary("model/Training_Hit@1", hit_at_one),
global_step_val)
sv.summary_writer.add_summary(
utils.MakeSummary("model/Training_Perr", perr), global_step_val)
sv.summary_writer.add_summary(
utils.MakeSummary("model/Training_GAP", gap), global_step_val)
sv.summary_writer.add_summary(
utils.MakeSummary("global_step/Examples/Second",
examples_per_second), global_step_val)
sv.summary_writer.flush()
# Exporting the model every x steps
time_to_export = ((self.last_model_export_step == 0) or
(global_step_val - self.last_model_export_step
>= self.export_model_steps))
if self.is_master and time_to_export:
self.export_model(global_step_val, sv.saver, sv.save_path, sess)
self.last_model_export_step = global_step_val
else:
logging.info("training step " + str(global_step_val) + " | Loss: " +
("%.2f" % loss_val) + " Examples/sec: " + ("%.2f" % examples_per_second))
except tf.errors.OutOfRangeError:
logging.info("%s: Done training -- epoch limit reached.",
task_as_string(self.task))
logging.info("%s: Exited training loop.", task_as_string(self.task))
sv.Stop()
def export_model(self, global_step_val, saver, save_path, session):
# If the model has already been exported at this step, return.
if global_step_val == self.last_model_export_step:
return
last_checkpoint = saver.save(session, save_path, global_step_val)
model_dir = "{0}/export/step_{1}".format(self.train_dir, global_step_val)
logging.info("%s: Exporting the model at step %s to %s.",
task_as_string(self.task), global_step_val, model_dir)
self.model_exporter.export_model(
model_dir=model_dir,
global_step_val=global_step_val,
last_checkpoint=last_checkpoint)
def start_server_if_distributed(self):
"""Starts a server if the execution is distributed."""
if self.cluster:
logging.info("%s: Starting trainer within cluster %s.",
task_as_string(self.task), self.cluster.as_dict())
server = start_server(self.cluster, self.task)
target = server.target
device_fn = tf.train.replica_device_setter(
ps_device="/job:ps",
worker_device="/job:%s/task:%d" % (self.task.type, self.task.index),
cluster=self.cluster)
else:
target = ""
device_fn = ""
return (target, device_fn)
def remove_training_directory(self, train_dir):
"""Removes the training directory."""
try:
logging.info(
"%s: Removing existing train directory.",
task_as_string(self.task))
gfile.DeleteRecursively(train_dir)
except:
logging.error(
"%s: Failed to delete directory " + train_dir +
" when starting a new model. Please delete it manually and" +
" try again.", task_as_string(self.task))
def get_meta_filename(self, start_new_model, train_dir):
if start_new_model:
logging.info("%s: Flag 'start_new_model' is set. Building a new model.",
task_as_string(self.task))
return None
latest_checkpoint = tf.train.latest_checkpoint(train_dir)
if not latest_checkpoint:
logging.info("%s: No checkpoint file found. Building a new model.",
task_as_string(self.task))
return None
meta_filename = latest_checkpoint + ".meta"
if not gfile.Exists(meta_filename):
logging.info("%s: No meta graph file found. Building a new model.",
task_as_string(self.task))
return None
else:
return meta_filename
def recover_model(self, meta_filename):
logging.info("%s: Restoring from meta graph file %s",
task_as_string(self.task), meta_filename)
return tf.train.import_meta_graph(meta_filename)
def build_model(self, model, reader):
"""Find the model and build the graph."""
label_loss_fn = find_class_by_name(FLAGS.label_loss, [losses])()
optimizer_class = find_class_by_name(FLAGS.optimizer, [tf.train])
build_graph(reader=reader,
model=model,
optimizer_class=optimizer_class,
clip_gradient_norm=FLAGS.clip_gradient_norm,
train_data_pattern=FLAGS.train_data_pattern,
label_loss_fn=label_loss_fn,
base_learning_rate=FLAGS.base_learning_rate,
learning_rate_decay=FLAGS.learning_rate_decay,
learning_rate_decay_examples=FLAGS.learning_rate_decay_examples,
regularization_penalty=FLAGS.regularization_penalty,
num_readers=FLAGS.num_readers,
batch_size=FLAGS.batch_size,
num_epochs=FLAGS.num_epochs)
return tf.train.Saver(max_to_keep=10, keep_checkpoint_every_n_hours=1.0)
def get_reader():
# Convert feature_names and feature_sizes to lists of values.
feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes(
FLAGS.feature_names, FLAGS.feature_sizes)
if FLAGS.frame_features:
reader = readers.YT8MFrameFeatureReader(
feature_names=feature_names, feature_sizes=feature_sizes)
else:
reader = readers.YT8MAggregatedFeatureReader(
feature_names=feature_names, feature_sizes=feature_sizes)
return reader
class ParameterServer(object):
"""A parameter server to serve variables in a distributed execution."""
def __init__(self, cluster, task):
"""Creates a ParameterServer.
Args:
cluster: A tf.train.ClusterSpec if the execution is distributed.
None otherwise.
task: A TaskSpec describing the job type and the task index.
"""
self.cluster = cluster
self.task = task
def run(self):
"""Starts the parameter server."""
logging.info("%s: Starting parameter server within cluster %s.",
task_as_string(self.task), self.cluster.as_dict())
server = start_server(self.cluster, self.task)
server.join()
def start_server(cluster, task):
"""Creates a Server.
Args:
cluster: A tf.train.ClusterSpec if the execution is distributed.
None otherwise.
task: A TaskSpec describing the job type and the task index.
"""
if not task.type:
raise ValueError("%s: The task type must be specified." %
task_as_string(task))
if task.index is None:
raise ValueError("%s: The task index must be specified." %
task_as_string(task))
# Create and start a server.
return tf.train.Server(
tf.train.ClusterSpec(cluster),
protocol="grpc",
job_name=task.type,
task_index=task.index)
def task_as_string(task):
return "/job:%s/task:%s" % (task.type, task.index)
def main(unused_argv):
# Load the environment.
env = json.loads(os.environ.get("TF_CONFIG", "{}"))
# Load the cluster data from the environment.
cluster_data = env.get("cluster", None)
cluster = tf.train.ClusterSpec(cluster_data) if cluster_data else None
# Load the task data from the environment.
task_data = env.get("task", None) or {"type": "master", "index": 0}
task = type("TaskSpec", (object,), task_data)
# Logging the version.
logging.set_verbosity(tf.logging.INFO)
logging.info("%s: Tensorflow version: %s.",
task_as_string(task), tf.__version__)
# Dispatch to a master, a worker, or a parameter server.
if not cluster or task.type == "master" or task.type == "worker":
model = find_class_by_name(FLAGS.model,
[frame_level_models, video_level_models])()
reader = get_reader()
model_exporter = export_model.ModelExporter(
frame_features=FLAGS.frame_features,
model=model,
reader=reader)
Trainer(cluster, task, FLAGS.train_dir, model, reader, model_exporter,
FLAGS.log_device_placement, FLAGS.max_steps,
FLAGS.export_model_steps).run(start_new_model=FLAGS.start_new_model)
elif task.type == "ps":
ParameterServer(cluster, task).run()
else:
raise ValueError("%s: Invalid task_type: %s." %
(task_as_string(task), task.type))
if __name__ == "__main__":
app.run()
|
# Copyright 2019-2021 Simon Zigelli
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django import template
from django.urls import translate_url as django_translate_url
register = template.Library()
@register.simple_tag(takes_context=True)
def translate_url(context, lang_code):
path = context.get('request').get_full_path()
return django_translate_url(path, lang_code)
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:26:56 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class PXContentFilterState, NSString;
@protocol PXContentFilterController <NSObject>
@property (nonatomic,copy) PXContentFilterState * filterState;
@property (nonatomic,readonly) BOOL filteringIsActive;
@property (nonatomic,readonly) NSString * filteringLocalizedCaption;
@property (nonatomic,readonly) NSString * filteringLocalizedTitle;
@optional
-(void)showContentFilterUIFromRect:(CGRect)arg1 inView:(id)arg2;
@required
-(id)initWithIdentifier:(id)arg1 delegate:(id)arg2;
-(void)setFilterState:(id)arg1;
-(PXContentFilterState *)filterState;
-(BOOL)filteringIsActive;
-(NSString *)filteringLocalizedCaption;
-(NSString *)filteringLocalizedTitle;
@end
|
import time
import unittest
import random
import threading
import sys
import traceback
import stackimpact
from stackimpact.runtime import min_version
class ErrorReporterTestCase(unittest.TestCase):
def test_add_exception(self):
stackimpact._agent = None
agent = stackimpact.start(
dashboard_address = 'http://localhost:5001',
agent_key = 'key1',
app_name = 'TestPythonApp',
debug = True
)
agent.error_reporter.start()
try:
raise ValueError('test_exc_1')
except:
traceback.print_exc()
time.sleep(1.1)
profile_handled_exc = agent.error_reporter.profile
#print(profile_handled_exc)
self.assertTrue('ValueError: test_exc_1' in str(profile_handled_exc))
self.assertTrue('test_add_exception' in str(profile_handled_exc))
agent.destroy()
if __name__ == '__main__':
unittest.main()
|
import numpy as np
import backend_full_cuda_internals as backend_cuda
import faulthandler
def load_mnist(image_file, label_file, dtype=np.float64):
imgs = np.fromfile(image_file, dtype=np.uint8)
imgs = imgs[16:]
# imgs = np.reshape(imgs, [-1, 28, 28])
imgs = np.reshape(imgs, [-1, 28 * 28])
imgs = imgs.astype(dtype)
imgs /= 255.0
l = np.fromfile(label_file, dtype=np.uint8)
l = l[8:]
labels = np.zeros([l.shape[0], 10]).astype(dtype)
labels[np.arange(l.shape[0]), l] = 1.0
return imgs, labels
backend_cuda.initialize()
# faulthandler.enable()
training_images, training_labels = load_mnist(
"/tmp/train-images-idx3-ubyte", "/tmp/train-labels-idx1-ubyte", np.float32)
testing_images, testing_labels = load_mnist(
"/tmp/t10k-images-idx3-ubyte", "/tmp/t10k-labels-idx1-ubyte", np.float32)
net = backend_cuda.PyNetwork_float32()
net.add_plastic_layer(28 * 28, 30, 100)
net.add_dense_layer(3000, 1, 10)
net.initiate_training(training_images, training_labels)
net.train_layer(128, 0, 15)
net.train_layer(128, 1, 25)
print(net.evaluate(testing_images, testing_labels))
|
/*+-----------------------------------------------------------------**
** OpenScop Library **
**-----------------------------------------------------------------**
** generic.c **
**-----------------------------------------------------------------**
** First version: 26/11/2010 **
**-----------------------------------------------------------------**
*****************************************************************************
* OpenScop: Structures and formats for polyhedral tools to talk together *
*****************************************************************************
* ,___,,_,__,,__,,__,,__,,_,__,,_,__,,__,,___,_,__,,_,__, *
* / / / // // // // / / / // // / / // / /|,_, *
* / / / // // // // / / / // // / / // / / / /\ *
* |~~~|~|~~~|~~~|~~~|~~~|~|~~~|~|~~~|~~~|~~~|~|~~~|~|~~~|/_/ \ *
* | G |C| P | = | L | P |=| = |C| = | = | = |=| = |=| C |\ \ /\ *
* | R |l| o | = | e | l |=| = |a| = | = | = |=| = |=| L | \# \ /\ *
* | A |a| l | = | t | u |=| = |n| = | = | = |=| = |=| o | |\# \ \ *
* | P |n| l | = | s | t |=| = |d| = | = | = | | |=| o | | \# \ \ *
* | H | | y | | e | o | | = |l| | | = | | | | G | | \ \ \ *
* | I | | | | e | | | | | | | | | | | | | \ \ \ *
* | T | | | | | | | | | | | | | | | | | \ \ \ *
* | E | | | | | | | | | | | | | | | | | \ \ \ *
* | * |*| * | * | * | * |*| * |*| * | * | * |*| * |*| * | / \* \ \ *
* | O |p| e | n | S | c |o| p |-| L | i | b |r| a |r| y |/ \ \ / *
* '---'-'---'---'---'---'-'---'-'---'---'---'-'---'-'---' '--' *
* *
* Copyright (C) 2008 University Paris-Sud 11 and INRIA *
* *
* (3-clause BSD license) *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. The name of the author may not be used to endorse or promote products *
* derived from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR *
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES *
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. *
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT *
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF *
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
* *
* OpenScop Library, a library to manipulate OpenScop formats and data *
* structures. Written by: *
* Cedric Bastoul <Cedric.Bastoul@u-psud.fr> and *
* Louis-Noel Pouchet <Louis-Noel.pouchet@inria.fr> *
* *
*****************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <osl/macros.h>
#include <osl/util.h>
#include <osl/interface.h>
#include <osl/generic.h>
#include <osl/extensions/arrays.h>
/*+***************************************************************************
* Structure display function *
*****************************************************************************/
/**
* osl_generic_idump function:
* this function displays an osl_generic_t structure (*generic) into
* a file (file, possibly stdout) in a way that trends to be understandable.
* It includes an indentation level (level) in order to work with others
* idump functions.
* \param[in] file File where informations are printed.
* \param[in] generic The generic whose information has to be printed.
* \param[in] level Number of spaces before printing, for each line.
*/
void osl_generic_idump(FILE * file, osl_generic_p generic, int level) {
int j, first = 1;
// Go to the right level.
for (j = 0; j < level; j++)
fprintf(file,"|\t");
if (generic != NULL)
fprintf(file, "+-- osl_generic_t\n");
else
fprintf(file, "+-- NULL generic\n");
while (generic != NULL) {
if (!first) {
// Go to the right level.
for (j = 0; j < level; j++)
fprintf(file, "|\t");
fprintf(file, "| osl_generic_t\n");
} else {
first = 0;
}
// A blank line
for(j = 0; j <= level + 1; j++)
fprintf(file, "|\t");
fprintf(file, "\n");
osl_interface_idump(file, generic->interface, level + 1);
if (generic->interface != NULL)
generic->interface->idump(file, generic->data, level + 1);
generic = generic->next;
// Next line.
if (generic != NULL) {
for (j = 0; j <= level; j++)
fprintf(file, "|\t");
fprintf(file, "V\n");
}
}
// The last line.
for (j = 0; j <= level; j++)
fprintf(file, "|\t");
fprintf(file, "\n");
}
/**
* osl_generic_dump function:
* this function prints the content of an osl_generic_t structure
* (*generic) into a file (file, possibly stdout).
* \param[in] file File where the information has to be printed.
* \param[in] generic The generic structure to print.
*/
void osl_generic_dump(FILE * file, osl_generic_p generic) {
osl_generic_idump(file, generic, 0);
}
/**
* osl_generic_sprint function:
* this function prints the content of an osl_generic_t structure
* (*strings) into a string (returned) in the OpenScop textual format.
* \param[in] generic The generic structure which has to be printed.
* \return A string containing the OpenScop dump of the generic structure.
*/
char * osl_generic_sprint(osl_generic_p generic) {
size_t high_water_mark = OSL_MAX_STRING;
char * string = NULL, * content;
char buffer[OSL_MAX_STRING];
OSL_malloc(string, char *, high_water_mark * sizeof(char));
string[0] = '\0';
while (generic != NULL) {
if (generic->interface != NULL) {
content = generic->interface->sprint(generic->data);
if (content != NULL) {
sprintf(buffer, "<%s>\n", generic->interface->URI);
osl_util_safe_strcat(&string, buffer, &high_water_mark);
osl_util_safe_strcat(&string, content, &high_water_mark);
free(content);
sprintf(buffer, "</%s>\n", generic->interface->URI);
osl_util_safe_strcat(&string, buffer, &high_water_mark);
}
}
generic = generic->next;
if (generic != NULL) {
sprintf(buffer, "\n");
osl_util_safe_strcat(&string, buffer, &high_water_mark);
}
}
return string;
}
/**
* osl_generic_print function:
* this function prints the content of an osl_generic_t structure
* (*generic) into a string (returned) in the OpenScop format.
* \param[in] file File where the information has to be printed.
* \param[in] generic The generic structure to print.
*/
void osl_generic_print(FILE * file, osl_generic_p generic) {
char * string;
string = osl_generic_sprint(generic);
if (string != NULL) {
fprintf(file, "%s", string);
free(string);
}
}
/**
* osl_generic_print_options_scoplib function:
* this function prints the options sections (only arrays in the
* SCoPLib format)
* \param[in] file File where the information has to be printed.
* \param[in] generic The generic structure to print.
*/
void osl_generic_print_options_scoplib(FILE * file, osl_generic_p generic) {
char * string;
osl_generic_p arrays = osl_generic_lookup(generic, OSL_URI_ARRAYS);
string = osl_arrays_sprint((osl_arrays_p) arrays);
if (string != NULL) {
fprintf(file, "<arrays>\n%s</arrays>\n", string);
free(string);
}
}
/*****************************************************************************
* Reading function *
*****************************************************************************/
/**
* osl_generic_sread function:
* this function reads a list of generic structure from a string complying to
* the OpenScop textual format and returns a pointer to this generic structure.
* The input parameter is updated to the position in the input string this
* function reach right after reading the generic structure.
* \param[in,out] input The input string where to find a list of generic.
* Updated to the position after what has been read.
* \param[in] registry The list of known interfaces (others are ignored).
* \return A pointer to the generic information list that has been read.
*/
osl_generic_p osl_generic_sread(char ** input, osl_interface_p registry) {
osl_generic_p generic = NULL, new;
while (**input != '\0') {
new = osl_generic_sread_one(input, registry);
osl_generic_add(&generic, new);
}
return generic;
}
/**
* osl_generic_sread_one function:
* this function reads one generic structure from a string complying to the
* OpenScop textual format and returns a pointer to this generic structure.
* The input parameter is updated to the position in the input string this
* function reach right after reading the generic structure.
* \param[in,out] input The input string where to find a generic.
* Updated to the position after what has been read.
* \param[in] registry The list of known interfaces (others are ignored).
* \return A pointer to the generic structure that has been read.
*/
osl_generic_p osl_generic_sread_one(char ** input, osl_interface_p registry) {
char * tag;
char * content, * temp;
osl_generic_p generic = NULL;
osl_interface_p interface;
tag = osl_util_read_tag(NULL, input);
if ((tag == NULL) || (strlen(tag) < 1) || (tag[0] == '/')) {
OSL_debug("empty tag name or closing tag instead of an opening one");
return NULL;
}
content = osl_util_read_uptoendtag(NULL, input, tag);
interface = osl_interface_lookup(registry, tag);
temp = content;
if (interface == NULL) {
OSL_warning("unsupported generic");
fprintf(stderr, "[osl] Warning: unknown URI \"%s\".\n", tag);
} else {
generic = osl_generic_malloc();
generic->interface = osl_interface_nclone(interface, 1);
generic->data = interface->sread(&temp);
}
free(content);
free(tag);
return generic;
}
/**
* osl_generic_read_one function:
* this function reads one generic from a file (possibly stdin)
* complying to the OpenScop textual format and a list of known interfaces.
* It returns a pointer to the corresponding generic structure. If no
* tag is found, an error is reported, in the case of an empty or closing tag
* name the function returns the NULL pointer.
* \param[in] file The input file where to read a list of data.
* \param[in] registry The list of known interfaces (others are ignored).
* \return A pointer to the generic that has been read.
*/
osl_generic_p osl_generic_read_one(FILE * file, osl_interface_p registry) {
char * tag;
char * content, * temp;
osl_generic_p generic = NULL;
osl_interface_p interface;
tag = osl_util_read_tag(file, NULL);
if ((tag == NULL) || (strlen(tag) < 1) || (tag[0] == '/')) {
OSL_debug("empty tag name or closing tag instead of an opening one");
return NULL;
}
content = osl_util_read_uptoendtag(file, NULL, tag);
interface = osl_interface_lookup(registry, tag);
temp = content;
if (interface == NULL) {
OSL_warning("unsupported generic");
fprintf(stderr, "[osl] Warning: unknown URI \"%s\".\n", tag);
} else {
generic = osl_generic_malloc();
generic->interface = osl_interface_nclone(interface, 1);
generic->data = interface->sread(&temp);
}
free(content);
free(tag);
return generic;
}
/**
* osl_generic_read function:
* this function reads a list of generics from a file (possibly stdin)
* complying to the OpenScop textual format and a list of known interfaces.
* It returns a pointer to the list of corresponding generic structures.
* \param[in] file The input file where to read a list of data.
* \param[in] registry The list of known interfaces (others are ignored).
* \return A pointer to the generic information list that has been read.
*/
osl_generic_p osl_generic_read(FILE * file, osl_interface_p registry) {
char * generic_string, * temp;
osl_generic_p generic_list;
generic_string = osl_util_read_uptoendtag(file, NULL, OSL_URI_SCOP);
temp = generic_string;
generic_list = osl_generic_sread(&temp, registry);
free(generic_string);
return generic_list;
}
/*+***************************************************************************
* Memory allocation/deallocation function *
*****************************************************************************/
/**
* osl_generic_add function:
* this function adds a generic node (it may be a list as well) to a list
* of generics provided as parameter (list). The new node is inserted at
* the end of the list.
* \param[in] list The list of generics to add a node (NULL if empty).
* \param[in] generic The generic list to add to the initial list.
*/
void osl_generic_add(osl_generic_p * list, osl_generic_p generic) {
osl_generic_p tmp = *list, check;
if (generic != NULL) {
// First, check that the generic list is OK.
check = generic;
while (check != NULL) {
if ((check->interface == NULL) || (check->interface->URI == NULL))
OSL_error("no interface or URI in a generic to add to a list");
// TODO: move this to the integrity check.
if (osl_generic_lookup(*list, check->interface->URI) != NULL)
OSL_error("only one generic with a given URI is allowed");
check = check->next;
}
if (*list != NULL) {
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = generic;
} else {
*list = generic;
}
}
}
/**
* osl_generic_remove_node function:
* this functions removes a given generic from a generic list
* \param[in] list Address of a generic list
* \param[in] generic Pointer to the generic to be removed
* Assumes a single node is to be removed.
*/
void osl_generic_remove_node(osl_generic_p * list, osl_generic_p generic) {
osl_generic_p tmp = NULL;
if (generic != NULL) {
if (*list != NULL) {
//target is the first element of list
if(*list==generic) {
*list = generic->next;
generic->next=NULL; //free below removes the whole list!
osl_generic_free(generic);
return;
}
//find target
tmp = *list;
while (tmp->next!=generic && tmp->next != NULL)
tmp = tmp->next;
if(tmp->next==generic) {
tmp->next = generic->next;
generic->next=NULL; //free below removes the whole list!
osl_generic_free(generic);
} else //target not found
OSL_warning("generic not found in the list\n");
}
}
}
/**
* osl_generic_remove function:
* given a URI, this function removes that generic from the list
* \param[in] list Address of a generic list
* \param[in] URI Pointer to the URI string
*/
void osl_generic_remove(osl_generic_p *list, char * URI) {
osl_generic_p tmp = *list;
while(tmp != NULL) {
if(osl_generic_has_URI(tmp, URI))
break;
tmp = tmp->next;
}
if(tmp!=NULL) {
osl_generic_remove_node(list, tmp);
}
}
/**
* osl_generic_malloc function:
* This function allocates the memory space for an osl_generic_t
* structure and sets its fields with default values. Then it returns a
* pointer to the allocated space.
* \return A pointer to an empty generic structure with fields set to
* default values.
*/
osl_generic_p osl_generic_malloc(void) {
osl_generic_p generic;
OSL_malloc(generic, osl_generic_p, sizeof(osl_generic_t));
generic->interface = NULL;
generic->data = NULL;
generic->next = NULL;
return generic;
}
/**
* osl_generic_free function:
* This function frees the allocated memory for a generic structure.
* \param[in] generic The pointer to the generic structure we want to free.
*/
void osl_generic_free(osl_generic_p generic) {
osl_generic_p next;
while (generic != NULL) {
next = generic->next;
if (generic->interface != NULL) {
generic->interface->free(generic->data);
osl_interface_free(generic->interface);
} else {
if (generic->data != NULL) {
OSL_warning("unregistered interface, memory leaks are possible");
free(generic->data);
}
}
free(generic);
generic = next;
}
}
/*+***************************************************************************
* Processing functions *
*****************************************************************************/
/**
* osl_generic_number function:
* this function returns the number of statements in the generic list
* provided as parameter.
* \param[in] generic The first element of the generic list.
* \return The number of statements in the generic list.
*/
int osl_generic_number(osl_generic_p generic) {
int number = 0;
while (generic != NULL) {
number++;
generic = generic->next;
}
return number;
}
/**
* osl_generic_clone function:
* This function builds and returns a "hard copy" (not a pointer copy) of an
* osl_generic_t data structure.
* \param[in] generic The pointer to the generic structure we want to clone.
* \return A pointer to the clone of the input generic structure.
*/
osl_generic_p osl_generic_clone(osl_generic_p generic) {
return osl_generic_nclone(generic, -1);
}
/**
* \brief This function builds and returns a "hard copy" (not a pointer copy)
* of the n first elements of an osl_generic_t list.
*
* \param generic The pointer to the generic structure we want to clone.
* \param n The number of nodes we want to copy (n<0 for infinity).
* \return The clone of the n first nodes of the generic list.
*/
osl_generic_p osl_generic_nclone(osl_generic_p generic, int n) {
osl_generic_p clone = NULL, new;
osl_interface_p interface;
void * x;
if (n < 0) {
n = osl_generic_count(generic);
}
while ((generic != NULL) && (n > 0)) {
if (generic->interface != NULL) {
x = generic->interface->clone(generic->data);
interface = osl_interface_clone(generic->interface);
new = osl_generic_malloc();
new->interface = interface;
new->data = x;
osl_generic_add(&clone, new);
} else {
OSL_warning("unregistered interface, cloning ignored");
}
generic = generic->next;
n--;
}
return clone;
}
/**
* osl_generic_count function:
* this function counts the number of elements in the generic list provided
* as parameter (x) and returns this number.
* \param[in] x The list of generics.
* \return The number of elements in the list.
*/
int osl_generic_count(osl_generic_p x) {
int generic_number = 0;
while (x != NULL) {
generic_number++;
x = x->next;
}
return generic_number;
}
/**
* osl_generic_equal function:
* this function returns true if the two generic structures are the same,
* false otherwise. This functions considers two generic structures as equal
* independently of the order of the nodes.
* \param[in] x1 The first generic structure.
* \param[in] x2 The second generic structure.
* \return 1 if x1 and x2 are the same (content-wise), 0 otherwise.
*/
int osl_generic_equal(osl_generic_p x1, osl_generic_p x2) {
int x1_generic_number, x2_generic_number;
int found, equal;
osl_generic_p backup_x2 = x2;
if (x1 == x2)
return 1;
// Check whether the number of generics is the same or not.
x1_generic_number = osl_generic_count(x1);
x2_generic_number = osl_generic_count(x2);
if (x1_generic_number != x2_generic_number)
return 0;
// Check that for each generic in x1 a similar generic is in x2.
while (x1 != NULL) {
x2 = backup_x2;
found = 0;
while ((x2 != NULL) && (found != 1)) {
if (osl_interface_equal(x1->interface, x2->interface)) {
if (x1->interface != NULL) {
equal = x1->interface->equal(x1->data, x2->data);
} else {
OSL_warning("unregistered generic, "
"cannot state generic equality");
equal = 0;
}
if (equal == 0)
return 0;
else
found = 1;
}
x2 = x2->next;
}
if (found != 1)
return 0;
x1 = x1->next;
}
return 1;
}
/**
* osl_generic_has_URI function:
* this function returns 1 if the generic provided as parameter has
* a given URI, 0 other wise.
* \param[in] x The generic structure to test.
* \param[in] URI The URI value to test.
* \return 1 if x has the provided URI, 0 otherwise.
*/
int osl_generic_has_URI(osl_const_generic_const_p x, char const * const URI) {
if ((x == NULL) ||
(x->interface == NULL) ||
(x->interface->URI == NULL) ||
(strcmp(x->interface->URI, URI)))
return 0;
return 1;
}
/**
* osl_generic_lookup function:
* this function returns the first generic with a given URI in the
* generic list provided as parameter and NULL if it doesn't find such
* a generic.
* \param[in] x The generic list where to search a given generic URI.
* \param[in] URI The URI of the generic we are looking for.
* \return The first generic of the requested URI in the list.
*/
void * osl_generic_lookup(osl_generic_p x, char const * const URI) {
while (x != NULL) {
if (osl_generic_has_URI(x, URI))
return x->data;
x = x->next;
}
return NULL;
}
/**
* osl_generic_shell function:
* this function creates and returns a generic structure "shell" which
* embed the data and interface provided as parameters.
* \param[in] data Data to put in the generic shell.
* \param[in] interface Interface to put in the generic shell.
* \return A new generic structure containing the data and interface.
*/
osl_generic_p osl_generic_shell(void * data, osl_interface_p interface) {
osl_generic_p generic = NULL;
if ((data == NULL) || (interface == NULL))
OSL_warning("shell created with some empty elements inside");
generic = osl_generic_malloc();
generic->data = data;
generic->interface = interface;
return generic;
}
|
/*
* @Description: 图片轮播组件
* @Author: wangyifan
* @LastEditors: lidikang
* @Date: 2019-03-05 16:38:56
* @LastEditTime: 2019-05-07 16:28:41
*/
import React from 'react'
import Base from '../../Base'
import PropTypes from 'prop-types'
import styles from './index.less'
export default Base(
class SwiperPreview extends React.PureComponent {
constructor(props) {
super(props)
this.state = {
left: 0,
speed: 2,
transition: 'all 1.5s'
}
}
static defaultProps = {
width: 328,
height: 180,
fileList: []
}
static propTypes = {
compid: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
fileList: PropTypes.array,
speed: PropTypes.number,
onClick: PropTypes.func
}
timer = null
count = 0
setimgeFn() {
this.timer = setTimeout(() => {
this.setImageScrollFn()
})
}
setImageScrollFn() {
if (this.timer) clearTimeout(this.timer)
this.timer = setTimeout(() => {
let { width, fileList, speed } = this.props
speed = speed > 1.5 ? speed : 1.5
const imageNum = fileList.length
if (imageNum <= 1) return
setTimeout(() => {
if (this.timer) clearTimeout(this.timer)
this.setImageScrollFn()
}, speed * 1000)
const { left } = this.state
let transition = 'all 1.5s'
let endleft = left - width
this.setState({ left: endleft, transition, speed })
this.count++
if (this.count >= imageNum) {
endleft = 0
this.count = 0
transition = ''
setTimeout(() => {
this.setState({ left: endleft, transition })
}, 1500)
}
}, this.state.speed * 1000)
}
componentDidMount() {
this.setImageScrollFn()
}
componentWillUnmount() {
// 当删除组件时,卸载定时器
if (this.timer) clearInterval(this.timer)
}
getImageListFn() {
const { width, height, fileList } = this.props
const imageList = []
const size = fileList ? fileList.length : 0
// 没有图片就显示默认一张图片
if (size === 0) {
let imageSrc = '/images/preview/image-black.png'
imageList.push(
<li key={0} className={styles['scroll-li']}>
<img src={imageSrc} width={width} height={height} />
</li>
)
} else {
for (let i = 0; i <= size; i++) {
let index = i
if (index === size) {
if (size <= 1) continue
index = 0
}
const image = fileList[index] || {}
let imageSrc = ''
if (typeof image === 'string') {
imageSrc = image
} else {
let { url, thumbUrl } = image
imageSrc = url || thumbUrl
}
imageList.push(
<li key={i} className={styles['scroll-li']}>
<img src={imageSrc} width={width} height={height} />
</li>
)
}
}
return imageList
}
render() {
const { compid, fileList, onClick = null } = this.props
let { left, transition } = this.state
const size = fileList ? fileList.length : 0
const imageList = this.getImageListFn()
if (size > 1) {
this.setImageScrollFn()
} else {
left = 0
transition = ''
}
let width = 100 * size + '%'
return (
<div className={styles.main} id={compid} onClick={onClick}>
<ul className={styles['scroll-ul']} style={{ width, left, transition }}>
{imageList}
</ul>
</div>
)
}
}
)
|
from proteus import *
from proteus.default_p import *
from dambreak import *
from proteus.mprans import MCorr
LevelModelType = MCorr.LevelModel
coefficients = MCorr.Coefficients(LSModel_index=2,V_model=0,me_model=4,VOFModel_index=1,
applyCorrection=applyCorrection,nd=nd,checkMass=False,useMetrics=useMetrics,
epsFactHeaviside=epsFact_consrv_heaviside,
epsFactDirac=epsFact_consrv_dirac,
epsFactDiffusion=epsFact_consrv_diffusion)
class zero_phi:
def __init__(self):
pass
def uOfX(self,X):
return 0.0
def uOfXT(self,X,t):
return 0.0
initialConditions = {0:zero_phi()}
|
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PM4Py is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PM4Py. If not, see <https://www.gnu.org/licenses/>.
'''
from pm4py.objects.log.importer.xes import variants, importer
|
import {
CallButton,
EndButton,
MuteButton,
StartVideoButton,
StopVideoButton,
UnmuteButton,
} from "./CallButtons";
import { InputWithCopyIcon } from "./Info";
import DeviceSettings from "./DeviceSettings";
import MediaContent from "./MediaContent";
import { RoomInfo } from "./RoomCreated";
import { useState } from "react";
import styled, { css } from "styled-components";
import { demi, heavy, heading2text1, midBig, normal, small } from "./fonts";
const Wrapper = styled.div`
width: 100vw;
height: 100vh;
background-color: black;
color: white;
display: flex;
`;
const Main = styled.div`
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
justify-content: space-between;
`;
const Header = styled.div`
display: flex;
flex: 0;
height: 64px;
padding: 22px 24px;
background-color: black;
${heading2text1};
${demi};
color: white;
z-index: 10;
`;
const ChevronRight = styled.div`
width: 20px;
height: 20px;
background-image: url(/icons/ic-chevron-right.svg);
background-repeat: no-repeat;
background-position: center;
margin-left: 6px;
`;
const Footer = styled.div`
height: 88px;
padding: 0 48px;
background-color: black;
display: flex;
justify-content: space-between;
z-index: 10;
`;
const Button = styled.div`
width: 80px;
padding: 20px 14px;
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
${normal};
${heavy}: letter-spacing: -0.1px;
color: var(--white);
`;
const ButtonIcon = styled.div`
background-image: ${(props) => css`url(${props.src})`};
background-repeat: no-repeat;
background-position: center;
width: 24px;
height: 24px;
`;
const UtilityButtons = styled.div`
height: 100%;
display: flex;
align-items: center;
${CallButton} {
width: 48px;
height: 48px;
background-size: 24px 24px;
padding: 12px;
}
`;
const Side = styled.div`
display: flex;
flex-direction: column;
min-width: 376px;
width: 376px;
background-color: white;
color: black;
${(props) =>
props.show
? css``
: css`
margin-right: -376px;
`};
`;
const SideTitle = styled.div`
${midBig};
${demi};
display: flex;
justify-content: space-between;
align-items: center;
width: 95%;
height: 63px;
padding: 20px 24px;
border-bottom: 1px solid black;
`;
const SideClose = styled.div`
width: 32px;
height: 24px;
padding: 6px;
border-radius: 4px;
cursor: pointer;
> div {
width: 20px;
height: 20px;
background-image: url(/icons/ic-close.svg);
background-repeat: no-repeat;
background-position: center center;
}
`;
const Participants = styled.div`
width: 100%;
padding: 0 24px;
flex: 1;
`;
const ParticipantWrapper = styled.div`
display: flex;
align-items: center;
height: 60px;
& > div:first-child {
width: 32px;
height: 32px;
background-image: url(${(props) => props.src});
background-repeat: no-repeat;
background-position: center;
background-size: cover;
flex-shrink: 0;
border-radius: 50%;
margin-right: 12px;
}
`;
const ParticipantNickname = styled.div`
${normal};
${heavy};
color: black;
`;
const ParticipantId = styled.div`
${small};
color: black;
`;
const Participant = ({ participant }) => {
return (
<ParticipantWrapper
src={participant.user.profileUrl || "/icons/icon-avatar.svg"}
>
<div />
<div>
<ParticipantNickname>
{participant.user.nickname || "—"}
</ParticipantNickname>
<ParticipantId>User ID: {participant.user.userId}</ParticipantId>
</div>
</ParticipantWrapper>
);
};
const ShareWrapper = styled.div`
padding: 24px;
label {
${normal};
${demi};
letter-spacing: -0.1px;
}
`;
const GroupCall = ({ room, setOnCall }) => {
const [showDeviceSettings, setShowDeviceSettings] = useState(false);
const [showSide, setShowSide] = useState(false);
const [showRoomInfo, setShowRoomInfo] = useState(false);
const { participants, localParticipant, remoteParticipants } = room;
const endCall = () => {
room.exit();
setOnCall(false);
window.location.reload();
}
return (
<Wrapper>
<Main>
<Header>
<span
onClick={() => {
setShowRoomInfo(true);
}}
style={{ cursor: "pointer" }}
>
{room.roomId}
</span>
<ChevronRight />
</Header>
<MediaContent room={room} />
<Footer>
<Button onClick={() => setShowDeviceSettings(true)}>
<ButtonIcon src="/icons/ic-settings.svg" />
Settings
</Button>
<UtilityButtons>
{localParticipant.isAudioEnabled ? (
<MuteButton onClick={() => localParticipant.muteMicrophone()} />
) : (
<UnmuteButton
onClick={() => localParticipant.unmuteMicrophone()}
/>
)}
{localParticipant.isVideoEnabled ? (
<StopVideoButton onClick={() => localParticipant.stopVideo()} />
) : (
<StartVideoButton onClick={() => localParticipant.startVideo()} />
)}
<EndButton onClick={() => endCall()} />
{/* <EndButton onClick={() => room.exit()} /> */}
</UtilityButtons>
<Button onClick={() => setShowSide(!showSide)}>
<ButtonIcon src="/icons/ic-user.svg" />
Participants
</Button>
</Footer>
<DeviceSettings
isOpen={showDeviceSettings}
close={() => setShowDeviceSettings(false)}
/>
<RoomInfo
isOpen={showRoomInfo}
room={room}
close={() => setShowRoomInfo(false)}
/>
</Main>
<Side show={showSide}>
<SideTitle>
<div>Participants ({room.participants.length})</div>
<SideClose onClick={() => setShowSide(false)}>
<div />
</SideClose>
</SideTitle>
<Participants>
{participants.map((p) => (
<Participant participant={p} />
))}
</Participants>
<ShareWrapper>
<InputWithCopyIcon title="Share room ID" text={room.roomId} />
</ShareWrapper>
</Side>
</Wrapper>
);
};
export default GroupCall;
|
"""Various management server related constants.
@var CONFIG_FILE:
Windows INI file like config file.
@var SERVER_ADDRESS:
Our IP address.
@var SERVER_PORT:
Out SSL/TLS port.
@var REPOSITORY_KEYS_FILE:
File containing repository keys, delivered to clients.
@var LICENSE_MAX_VALIDITY:
Maximum (temporary) validity period delivered to clients. Note that this is not
the validity period of the purchased license; instead, this is the validity time
that a VPNease server may use without getting an update from the management server.
@var LICENSE_MIN_VALIDITY:
FIXME: needed?
@var LICENSE_RECHECK_DEFAULT:
Time from current time at which the management server should recheck the validity
of its license. This constant is applied in 'normal' cases, while LICENSE_RECHECK_QUICK
is applied in exceptional cases.
@var LICENSE_RECHECK_QUICK:
Like LICENSE_RECHECK_DEFAULT, but applied in exceptional situations to ensure that the
VPNease server will get timely update on its license parameters.
@var LICENSE_VALIDITY_START_LEEWAY:
Timedelta subtracted from final calculated validity start to ensure minor time differences
(in the order of an hour) do not change validity determination.
@var LICENSE_VALIDITY_END_LEEWAY:
Timedelta added to final calculated validityend to ensure minor time differences
(in the order of an hour) do not change validity determination.
@var DEMO_LICENSE_TIME:
Timedelta describing how long a demo license is valid from grant time.
@var DEMO_LICENSE_USER_COUNT:
Number of user connections in a demo license.
@var DEMO_LICENSE_SITE_TO_SITE_COUNT:
Number of site-to-site connections in a demo license.
@var CONNECTION_INFO_FILE:
File to write with connection info.
@var SERVER_VERSION_INFO_STRING:
Info string sent by server in Version exchange.
@var SERVER_IDENTIFY_SOFTWARE_BUILD_INFO:
Software build info string sent by server in Identify exchange.
@var SERVER_IDENTIFY_SERVER_INFO:
Server info string sent by server in Identify exchange.
@var MASTER_CHECK_INTERVAL:
Interval for status summary logging.
@var KEEPALIVE_INTERVAL:
Server keepalive interval.
@var KEEPALIVE_TIMEOUT:
Server keepalive timeout.
"""
__docformat__ = 'epytext en'
import datetime
CONFIG_FILE = '/etc/managementserver.conf'
# FIXME: where-to?
SERVER_ADDRESS = '0.0.0.0'
SERVER_PORT = 443
SERVER_PRIVATE_KEY1 = '/var/lib/vpnease-management-server-private-key-1.pem'
SERVER_CERTIFICATE1 = '/var/lib/vpnease-management-server-certificate-1.pem'
VPNEASE_CA_CERTIFICATE1 = '/var/lib/vpnease-ca-certificate-1.pem'
SERVER_PRIVATE_KEY2 = '/var/lib/vpnease-management-server-private-key-2.pem'
SERVER_CERTIFICATE2 = '/var/lib/vpnease-management-server-certificate-2.pem'
VPNEASE_CA_CERTIFICATE2 = '/var/lib/vpnease-ca-certificate-2.pem'
# Note: order is important here!
_APT_SOURCES_LIST_1_0 = """\
deb http://packages.vpnease.com/vpnease/1.0 dapper main
deb http://packages.vpnease.com/ubuntu/1.0 dapper main restricted
"""
_APT_SOURCES_LIST_1_1 = """\
deb http://packages.vpnease.com/vpnease/1.1 dapper main
deb http://packages.vpnease.com/ubuntu/1.1 dapper main restricted
"""
_APT_SOURCES_LIST_1_2 = """\
deb http://packages.vpnease.com/vpnease/1.2 dapper main
deb http://packages.vpnease.com/ubuntu/1.2 dapper main restricted
"""
# serve by default
STABLE_APT_SOURCES_LIST = _APT_SOURCES_LIST_1_1
# serve to "beta" servers
UNSTABLE_APT_SOURCES_LIST = _APT_SOURCES_LIST_1_2
REPOSITORY_KEYS_FILE = '/usr/lib/vpnease-management/repository-keys.txt'
LICENSE_CSV_FILE = '/var/lib/vpnease-licenses.csv' # oocalc utf-8 csv save
LICENSE_MAX_VALIDITY = datetime.timedelta(0, 7*24*60*60, 0) # FIXME: 7 days
LICENSE_MIN_VALIDITY = datetime.timedelta(0, 3*24*60*60, 0) # FIXME: 3 days
LICENSE_RECHECK_DEFAULT = datetime.timedelta(0, 8*60*60, 0) # FIXME: 8 hours
LICENSE_RECHECK_QUICK = datetime.timedelta(0, 1*60*60, 0) # FIXME: hourly
LICENSE_VALIDITY_START_LEEWAY = datetime.timedelta(7, 0, 0) # FIXME: 1 week backwards leeway
LICENSE_VALIDITY_END_LEEWAY = datetime.timedelta(1, 0, 0) # FIXME: 1 day forwards leeway
DEMO_LICENSE_DIRECTORY = '/root/demolicenses'
DEMO_LICENSE_TIME = datetime.timedelta(30, 15*60, 0) # extra 15min for prettier server status page (start count from 30d 0h)
DEMO_LICENSE_USER_COUNT = 10
DEMO_LICENSE_SITE_TO_SITE_COUNT = 10
CONNECTION_INFO_FILE = '/tmp/connections.txt'
SERVER_VERSION_INFO_STRING = u'VPNease Management Server'
SERVER_IDENTIFY_SOFTWARE_BUILD_INFO = u''
SERVER_IDENTIFY_SERVER_INFO = u'%s:%s' % (SERVER_ADDRESS, SERVER_PORT)
MASTER_CHECK_INTERVAL = 5*60
KEEPALIVE_INTERVAL = 5*60
KEEPALIVE_TIMEOUT = 30
|
#include<stdio.h>
void calcMaxMinAve (int tensu[],int *max,int *min,double *ave);
int calcMax(int tensu[]);
int calcMin(int tensu[]);
double calcAve(int tensu[]);
int main(void){
int tensu[10]={0};
int max,min;
double ave;
int *max_p=&max;
int *min_p=&min;
double *ave_p=&ave;
// INPUT
printf("入力\n");
for(int i=1;i<=10;i++){
printf("点数%d: ",i);
scanf("%d",&tensu[i-1]);
if(tensu[i-1]==-1){
break;
}
}
calcMaxMinAve(tensu,max_p,min_p,ave_p);
// OUTPUT
printf("出力 \n");
printf("最大:%d\n",max);
printf("最小:%d\n",min);
printf("平均:%f\n",ave);
return 0;
}
void calcMaxMinAve (int tensu[],int *max,int *min,double *ave){
*max=calcMax(tensu);
*min=calcMin(tensu);
*ave=calcAve(tensu);
}
int calcMax(int tensu[]){
int max=0;
for(int i=0;tensu[i]!=-1&&i<10;i++){
if(max<tensu[i]){
max=tensu[i];
}
}
// printf("%d",max);
return max;
}
int calcMin(int tensu[]){
int min=100;
for(int i=0;tensu[i]!=-1&&i<10;i++){
if(min>tensu[i]){
min=tensu[i];
}
}
// printf("%d",min);
return min;
}
double calcAve(int tensu[]){
double ave=0;
int i;
for(i=0;tensu[i]!=-1&&i<10;i++){
ave+=tensu[i];
}
// printf("%f",ave);
return ave/=i;
}
|
from copy import deepcopy
import numpy as np
from agents.base_agent import BaseAgent
from system.enums import Player
#from system.enums import TTFlag
class TranspositionEntry:
def __init__(self, value, depth, flag):
self.value = value
self.depth = depth
self.flag = flag
class NegamaxAgent(BaseAgent):
def __init__(self, game, depth, heuristic):
self.game = game
self.depth = depth
self.heuristic = heuristic
#self.transposition_table = {} # Not used due to too low search depth
def get_move(self):
winning_move = self.get_winning_move()
if winning_move is not None:
return winning_move
move, _ = self.best_evaluated_move(self.game, self.depth, -np.inf, np.inf)
return move
def register_move(self, move):
pass
def get_winning_move(self):
for move in self.game.get_moves():
current_game = deepcopy(self.game)
current_game.make_move(move)
if current_game.get_winner() != Player.NONE:
return move
return None
def best_evaluated_move(self, game, depth, alpha, beta):
""" alphaOrig = alpha
ttEntry = self.transposition_table.get(game)
if ttEntry is not None and ttEntry.depth >= depth:
if ttEntry.flag == TTFlag.EXACT:
return None, ttEntry.value
elif ttEntry.flag == TTFlag.LOWERBOUND:
alpha = max(alpha, ttEntry.value)
elif ttEntry.flag == TTFlag.UPPERBOUND:
beta = min(beta, ttEntry.value)
if alpha >= beta:
return None, ttEntry.value """
if depth == 0 or game.get_winner() != Player.NONE:
#print(game)
score = self.heuristic(game)
#print(score)
return None, score
best_move = None
max_heuristic = -np.inf
for move in game.get_moves():
current_game = deepcopy(game)
current_game.make_move(move)
current_heuristic = -self.best_evaluated_move(current_game, depth-1, -beta, -alpha)[1]
if current_heuristic > max_heuristic:
best_move = move
max_heuristic = current_heuristic
# only if current_heuristic is greater than max_heuristic, the alpha may change
alpha = max(alpha, max_heuristic)
if alpha >= beta:
break
""" if max_heuristic <= alphaOrig:
ttEntry = TranspositionEntry(max_heuristic, depth, TTFlag.UPPERBOUND)
elif max_heuristic >= beta:
ttEntry = TranspositionEntry(max_heuristic, depth, TTFlag.LOWERBOUND)
else:
ttEntry = TranspositionEntry(max_heuristic, depth, TTFlag.EXACT)
self.transposition_table[game] = ttEntry """
return (best_move, max_heuristic)
|
import fs from 'fs';
import path from 'path';
const request = (options, callback) => {
// console.log(options);
let file;
if (typeof options === 'object') {
file = encodeURIComponent(options.url.trim());
} else if (typeof options === 'string') {
file = encodeURIComponent(options.trim());
} else {
throw new Error('Unhandled options');
}
// console.log(file);
const filePath = path.resolve(__dirname, `../__mockData__/${file}`);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
return callback(err, null, null);
}
return callback(null, null, data);
});
};
request.defaults = jest.fn(() => {
return request;
});
export default request;
|
var el = document.querySelectorAll('#homepage-generator')[0];
el.innerHTML = '';
var strVar="";
strVar += "<style>";
strVar += " #random-container{";
strVar += " border: 1px solid #ccf;";
strVar += " width: 158px;";
strVar += " \/*height: 154px;*\/";
strVar += " font-size: 9pt;";
strVar += " font-family: verdana, sans;";
strVar += " }";
strVar += "";
strVar += " #header-random{";
strVar += " background: #ccccff;";
strVar += " text-align: center;";
strVar += " padding: 2px 0;";
strVar += " color: #00000c;";
strVar += " }";
strVar += "";
strVar += " #body-random{";
strVar += " padding: 10px 5px 5px 5px;";
strVar += " }";
strVar += "";
strVar += " .text-form-random{";
strVar += " width: 40px;";
strVar += " display: inline-block;";
strVar += " color: #77777d;";
strVar += " }";
strVar += "";
strVar += " .row-random{";
strVar += " margin-bottom: 5px;";
strVar += " }";
strVar += "";
strVar += " .row-random > input{";
strVar += " width: 80px;";
strVar += " }";
strVar += "";
strVar += " #result-random{";
strVar += " color: #777777;";
strVar += " }";
strVar += "";
strVar += " #line-bottom-random{";
strVar += " height: 4px;";
strVar += " \/*width: 100%;*\/";
strVar += " background: #ccccff;";
strVar += " }";
strVar += "";
strVar += " #copyright-random{";
strVar += " color: #797b7a;";
strVar += " font-size: 8px;";
strVar += " padding-top: 10px;";
strVar += " text-align: right;";
strVar += " }";
strVar += "";
strVar += " #copyright-random a{";
strVar += " color: #797b7a;";
strVar += " text-decoration: underline!important;";
strVar += " }";
strVar += "";
strVar += " #copyright-random a:hover{";
strVar += " color: #000;";
strVar += " }";
strVar += "";
strVar += " .line-result-random{";
strVar += " color: #000;";
strVar += " font-size: 11pt;";
strVar += " background: #CCCCFF;";
strVar += " padding: 2px;";
strVar += " \/* margin-bottom: 10px; *\/";
strVar += " height: auto!important;";
strVar += " }";
strVar += "<\/style>";
strVar += "";
strVar += "<div id=\"random-container\">";
strVar += " <div id=\"header-random\">";
strVar += " True Random Number Generator";
strVar += " <\/div>";
strVar += "";
strVar += " <div id=\"body-random\">";
strVar += " <div class=\"row-random\">";
strVar += " <span class=\"text-form-random\">Min: <\/span>";
strVar += " <input type=\"text\" name=\"min\" id=\"_min\" value=\"1\" \/>";
strVar += " <\/div>";
strVar += "";
strVar += " <div class=\"row-random\">";
strVar += " <span class=\"text-form-random\">Max: <\/span>";
strVar += " <input type=\"text\" name=\"max\" id=\"_max\" value=\"100\" \/>";
strVar += " <\/div>";
strVar += "";
strVar += " <button value=\"\" id=\"_generate\">Generate<\/button>";
strVar += "";
strVar += " <div id=\"result-random\">Result:<\/div>";
strVar += " <div id=\"line-bottom-random\"><\/div>";
strVar += "";
strVar += " <div id=\"copyright-random\">";
strVar += " Powered by <a href=\"RANDOM.ORG\">RANDOM.ORG<\/a>";
strVar += " <\/div>";
strVar += " <\/div>";
strVar += "<\/div>";
strVar += "";
strVar += "";
var node = document.createElement("div");
node.innerHTML = strVar;
el.appendChild(node);
var count = 0;
var list_number = localStorage.getItem('list_number').split(',');
document.getElementById('_generate').addEventListener('click', function(e){
// alert('ok');
var min = document.getElementById('_min').value;
var max = document.getElementById('_max').value;
if(min == ''){
min = 1;
document.getElementById('_min').value = 1;
}
if(max == ''){
max = 100;
document.getElementById('_max').value = 100;
}
if(min >= max){
max = parseInt(min) + 1;
document.getElementById('_max').value = max;
}
var el_line = document.getElementById('line-bottom-random');
var className = 'line-result-random';
if (el_line.classList)
el_line.classList.add(className);
else
el_line.className += ' ' + className;
el_line.innerHTML = '<img src="https://www.random.org/util/cp/images/ajax-loader.gif" />';
setTimeout(function () {
var number = list_number[count];
el_line.innerHTML = number;
count++;
if(count == list_number.length){
count = 0;
}
}, 2000);
});
|
#####################################################################
# #
# /setup_logging.py #
# #
# Copyright 2013, Monash University #
# #
# This file is part of labscript_utils, in the labscript suite #
# (see http://labscriptsuite.org), and is licensed under the #
# Simplified BSD License. See the license.txt file in the root of #
# the project for the full license. #
# #
#####################################################################
from __future__ import division, unicode_literals, print_function, absolute_import
import sys, os
import logging, logging.handlers
import zmq
from labscript_utils import check_version
check_version('zprocess', '2.8.4', '3.0.0')
import zprocess.zlog
from zprocess import start_daemon
import __main__
_connected_to_zlog = False
def ensure_connected_to_zlog(maxBytes, backupCount):
"""Ensure we are connected to a zlog server. If one is not running, start one with
the given maxBytes and backupCount."""
global _connected_to_zlog
if _connected_to_zlog:
return
# setup connection with the zlog server on localhost
try:
# short connection timeout on localhost, don't want to waste time:
zprocess.zlog.connect(timeout=0.05)
except zmq.ZMQError:
# No zlog server running on localhost. Start one. It will run
# forever, even after this program exits. This is important for
# other programs which might be using it. I don't really consider
# this bad practice since the server is typically supposed to
# be running all the time:
start_daemon(
[
sys.executable,
'-m',
'zprocess.zlog',
'--cls',
'RotatingFileHandler',
'--maxBytes',
str(maxBytes),
'--backupCount',
str(backupCount),
]
)
# Try again. Longer timeout this time, give it time to start up:
zprocess.zlog.connect(timeout=15)
_connected_to_zlog = True
class LessThanFilter(logging.Filter):
def __init__(self, less_than):
self.less_than = less_than
logging.Filter.__init__(self)
def filter(self, record):
return record.levelno < self.less_than
def setup_logging(program_name, log_level=logging.DEBUG, terminal_level=logging.INFO, maxBytes=1024*1024*50, backupCount=1):
ensure_connected_to_zlog(maxBytes, backupCount)
logger = logging.getLogger(program_name)
# Clear any previously added handlers from the logger:
for handler in logger.handlers[:]:
logger.removeHandler(handler)
try:
try:
program_module = __import__(program_name)
except ImportError:
program_module = __import__(program_name.lower())
main_path = program_module.__file__
except ImportError:
main_path = __main__.__file__ if hasattr(__main__, '__file__') else __file__
log_dir = os.path.dirname(os.path.realpath(main_path))
log_path = os.path.join(log_dir, '%s.log' % program_name)
handler = zprocess.zlog.ZMQLoggingHandler(log_path)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(name)s: %(message)s')
handler.setFormatter(formatter)
handler.setLevel(log_level)
logger.addHandler(handler)
if sys.stdout is not None and sys.stdout.fileno() >= 0:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.setLevel(terminal_level)
logger.addHandler(stdout_handler)
if sys.stderr is not None and sys.stderr.fileno() >= 0:
# Send warnings and greater to stderr instead of stdout:
stdout_handler.addFilter(LessThanFilter(logging.WARNING))
sterr_handler = logging.StreamHandler(sys.stderr)
sterr_handler.setFormatter(formatter)
sterr_handler.setLevel(logging.WARNING)
logger.addHandler(sterr_handler)
else:
# Prevent bug on windows where writing to stdout without a command
# window causes a crash:
sys.stdout = sys.stderr = open(os.devnull, 'w')
logger.setLevel(logging.DEBUG)
return logger
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, June 7, 2020 at 11:25:07 AM Mountain Standard Time
* Operating System: Version 13.4.5 (Build 17L562)
* Image Source: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@protocol PXPhotosGlobalFooterViewDelegate <NSObject>
@optional
-(void)photosGlobalFooterViewDidChangeHeight:(id)arg1;
@required
-(void)photosGlobalFooterView:(id)arg1 presentViewController:(id)arg2;
@end
|
import sys
import gzip
def eprint(*args):
print(*args, file=sys.stderr)
def open_file(filepath, mode):
return (gzip.open if filepath.suffix == ".gz" else open)(filepath, mode)
def get_attack_details(ipal_entry):
"""
Parse the attack-details IPAL field.
The field is expected to have the format "<attack category>;<attack type>".
Example: "2;12".
"""
split = ipal_entry["attack-details"].split(";")
assert (
len(split) == 2
), "'attack-details' field in IPAL has wrong format, expected 'attack category;attack type'"
attack_category = int(split[0])
attack_type = int(split[1])
return attack_category, attack_type
def chunks(list, n):
"""
Partition the list into successive n-sized chunks.
https://stackoverflow.com/a/312464
"""
for i in range(0, len(list), n):
yield list[i : i + n]
|
from django.contrib import admin
from .models import Product, Order
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'seller', 'price')
class OrderAdmin(admin.ModelAdmin):
list_display = ('product', 'buyer', 'state')
admin.site.register(Product, ProductAdmin)
admin.site.register(Order, OrderAdmin)
|
# -*- coding: utf-8 -*-
import os, sys
# env
sys.path.append('/usr/lib/python2.7/dist-packages/')
sys.path.append('/usr/lib/python2.7/')
sys.path.append('/usr/local/lib/python2.7/dist-packages/')
sys.path.append('/data2/django_1.9/')
sys.path.append('/data2/django_projects/')
sys.path.append('/data2/django_third/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djpsilobus.settings")
import django
django.setup()
from django.conf import settings
from djpsilobus.core.utils import sheet, syllabus_name
from djpsilobus.core.data import HEADERS
from djzbar.utils.academics import sections
from djzbar.utils.academics import division_departments
from openpyxl import Workbook
from openpyxl import load_workbook
import argparse
YEAR = settings.YEAR
SESS = settings.SESS
# set up command-line options
desc = """
Creates an OpenXML workbook with course syllabi data.
Required: Department code. e.g. PHY
"""
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
"--division",
required=True,
help="Department code e.q.'NSSS'",
dest="division"
)
parser.add_argument(
"--department",
required=False,
help="Department code e.q.'PHY'",
dest="department"
)
parser.add_argument(
"--debug",
action='store_true',
help="Dry run?",
dest="debug"
)
def main():
if debug:
print "department code = {}".format(department)
wb = load_workbook('assets/template.xlsx')
# obtain the active worksheet
template = wb.active
if department:
courses = sections(code=department,year=YEAR,sess=SESS)
if courses:
sheet(template, division, department, courses)
# Save the file
wb.save("{}.xlsx".format(department))
else:
print "no courses found"
else:
depts = division_departments(division)
for d in depts:
courses = sections(code=d.dept,year=YEAR,sess=SESS)
if courses:
ws = wb.copy_worksheet(template)
ws.title = d.dept
hoja = sheet(ws, division, d.dept, courses)
# remove the template sheet
wb.remove_sheet(template)
# Save the file
wb.save("{}.xlsx".format(division))
######################
# shell command line
######################
if __name__ == "__main__":
args = parser.parse_args()
department = args.department
division = args.division
debug = args.debug
sys.exit(main())
|
!function(e){function t(e){Object.defineProperty(this,e,{enumerable:!0,get:function(){return this[v][e]}})}function r(e){if("undefined"!=typeof System&&System.isModule?System.isModule(e):"[object Module]"===Object.prototype.toString.call(e))return e;var t={default:e,__useDefault:e};if(e&&e.__esModule)for(var r in e)Object.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return new o(t)}function o(e){Object.defineProperty(this,v,{value:e}),Object.keys(e).forEach(t,this)}function n(e){return"@node/"===e.substr(0,6)?c(e,r(m(e.substr(6))),{}):p[e]}function u(e){var t=n(e);if(!t)throw new Error('Module "'+e+'" expected, but not contained in build.');if(t.module)return t.module;var r=t.linkRecord;return i(t,r),a(t,r,[]),t.module}function i(e,t){if(!t.depLoads){t.declare&&d(e,t),t.depLoads=[];for(var r=0;r<t.deps.length;r++){var o=n(t.deps[r]);t.depLoads.push(o),o.linkRecord&&i(o,o.linkRecord);var u=t.setters&&t.setters[r];u&&(u(o.module||o.linkRecord.moduleObj),o.importerSetters.push(u))}return e}}function d(t,r){var o=r.moduleObj,n=t.importerSetters,u=!1,i=r.declare.call(e,function(e,t){if(!u){if("object"==typeof e)for(var r in e)"__useDefault"!==r&&(o[r]=e[r]);else o[e]=t;u=!0;for(var i=0;i<n.length;i++)n[i](o);return u=!1,t}},{id:t.key});"function"!=typeof i?(r.setters=i.setters,r.execute=i.execute):(r.setters=[],r.execute=i)}function l(e,t,r){return p[e]={key:e,module:void 0,importerSetters:[],linkRecord:{deps:t,depLoads:void 0,declare:r,setters:void 0,execute:void 0,moduleObj:{}}}}function f(e,t,r,o){var n={};return p[e]={key:e,module:void 0,importerSetters:[],linkRecord:{deps:t,depLoads:void 0,declare:void 0,execute:o,executingRequire:r,moduleObj:{default:n,__useDefault:n},setters:void 0}}}function s(e,t,r){return function(o){for(var n=0;n<e.length;n++)if(e[n]===o){var u,i=t[n],d=i.linkRecord;return u=d?-1===r.indexOf(i)?a(i,d,r):d.moduleObj:i.module,"__useDefault"in u?u.__useDefault:u}}}function a(t,r,n){if(n.push(t),t.module)return t.module;var u;if(r.setters){for(var i=0;i<r.deps.length;i++){var d=r.depLoads[i],l=d.linkRecord;l&&-1===n.indexOf(d)&&(u=a(d,l,l.setters?n:[]))}r.execute.call(y)}else{var f={id:t.key},c=r.moduleObj;Object.defineProperty(f,"exports",{configurable:!0,set:function(e){c.default=c.__useDefault=e},get:function(){return c.__useDefault}});var p=s(r.deps,r.depLoads,n);if(!r.executingRequire)for(var i=0;i<r.deps.length;i++)p(r.deps[i]);var v=r.execute.call(e,p,c.__useDefault,f);void 0!==v&&(c.default=c.__useDefault=v),f.exports!==c.__useDefault&&(c.default=c.__useDefault=f.exports);var m=c.default;if(m&&m.__esModule)for(var b in m)Object.hasOwnProperty.call(m,b)&&(c[b]=m[b])}var f=t.module=new o(r.moduleObj);if(!r.setters)for(var i=0;i<t.importerSetters.length;i++)t.importerSetters[i](f);return f}function c(e,t){return p[e]={key:e,module:t,importerSetters:[],linkRecord:void 0}}var p={},v="undefined"!=typeof Symbol?Symbol():"@@baseObject";o.prototype=Object.create(null),"undefined"!=typeof Symbol&&Symbol.toStringTag&&(o.prototype[Symbol.toStringTag]="Module");var m="undefined"!=typeof System&&System._nodeRequire||"undefined"!=typeof require&&"undefined"!=typeof require.resolve&&"undefined"!=typeof process&&process.platform&&require,y={};return Object.freeze&&Object.freeze(y),function(e,t,n,i){return function(d){d(function(d){var s={_nodeRequire:m,register:l,registerDynamic:f,registry:{get:function(e){return p[e].module},set:c},newModule:function(e){return new o(e)}};c("@empty",new o({}));for(var a=0;a<t.length;a++)c(t[a],r(arguments[a],{}));i(s);var v=u(e[0]);if(e.length>1)for(var a=1;a<e.length;a++)u(e[a]);return n?v.__useDefault:(v instanceof o&&Object.defineProperty(v,"__esModule",{value:!0}),v)})}}}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this)
|
#!/usr/bin/env python3
import sys
# Functions
LEFT_PBB = ('(', '[', '{')
RIGHT_PBB = (')', ']', '}')
def is_pbbmatched(s):
# TODO: Process string s using a stack to determine if the symbols are balanced
return False
# Main execution
if __name__ == '__main__':
for line in sys.stdin:
line = line.rstrip()
result = 'Yes' if is_pbbmatched(line) else 'No'
print('{:>10}: {}'.format(line, result))
|
/* file: service.h */
/*******************************************************************************
* Copyright 2017-2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
! Content:
! Auxiliary functions used in C++ samples
!******************************************************************************/
#ifndef _SERVICE_H
#define _SERVICE_H
#include "daal.h"
using namespace daal::data_management;
#include <algorithm>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstdarg>
#include <vector>
#include <queue>
#include "error_handling.h"
typedef std::vector<daal::byte> ByteBuffer;
size_t readTextFile(const std::string & datasetFileName, daal::byte ** data)
{
std::ifstream file(datasetFileName.c_str(), std::ios::binary | std::ios::ate);
if (!file.is_open())
{
fileOpenError(datasetFileName.c_str());
}
std::streampos end = file.tellg();
file.seekg(0, std::ios::beg);
size_t fileSize = static_cast<size_t>(end);
(*data) = new daal::byte[fileSize];
checkAllocation(data);
if (!file.read((char *)(*data), fileSize))
{
delete[] data;
fileReadError();
}
return fileSize;
}
template <typename item_type>
void readLine(std::string & line, size_t nCols, item_type * data, size_t firstPos = 0)
{
std::stringstream iss(line);
for (size_t col = 0; col < nCols; ++col)
{
std::string val;
std::getline(iss, val, ',');
std::stringstream convertor(val);
convertor >> data[firstPos + col];
}
}
template <typename item_type>
void readRowUnknownLength(char * line, std::vector<item_type> & data)
{
size_t n = 0;
const char * prevDelim = line - 1;
char * ptr = line;
for (; *ptr; ++ptr)
{
if (*ptr == ',' || *ptr == '\r')
{
if (prevDelim != ptr - 1) ++n;
*ptr = ' ';
prevDelim = ptr;
}
}
if (prevDelim != ptr - 1) ++n;
data.resize(n);
std::stringstream iss(line);
for (size_t i = 0; i < n; ++i)
{
iss >> data[i];
}
}
template <typename item_type>
CSRNumericTable * createSparseTable(const std::string & datasetFileName)
{
std::ifstream file(datasetFileName.c_str());
if (!file.is_open())
{
fileOpenError(datasetFileName.c_str());
}
std::string str;
//read row offsets
std::getline(file, str);
std::vector<size_t> rowOffsets;
readRowUnknownLength<size_t>(&str[0], rowOffsets);
if (!rowOffsets.size()) return NULL;
const size_t nVectors = rowOffsets.size() - 1;
//read cols indices
std::getline(file, str);
std::vector<size_t> colIndices;
readRowUnknownLength<size_t>(&str[0], colIndices);
//read values
std::getline(file, str);
std::vector<item_type> data;
readRowUnknownLength<item_type>(&str[0], data);
const size_t nNonZeros = data.size();
size_t maxCol = 0;
for (size_t i = 0; i < colIndices.size(); ++i)
{
if (colIndices[i] > maxCol) maxCol = colIndices[i];
}
const size_t nFeatures = maxCol;
if (!nFeatures || !nVectors || colIndices.size() != nNonZeros || nNonZeros != (rowOffsets[nVectors] - 1))
{
sparceFileReadError();
}
size_t * resultRowOffsets = NULL;
size_t * resultColIndices = NULL;
item_type * resultData = NULL;
CSRNumericTable * numericTable = new CSRNumericTable(resultData, resultColIndices, resultRowOffsets, nFeatures, nVectors);
numericTable->allocateDataMemory(nNonZeros);
numericTable->getArrays<item_type>(&resultData, &resultColIndices, &resultRowOffsets);
for (size_t i = 0; i < nNonZeros; ++i)
{
resultData[i] = data[i];
resultColIndices[i] = colIndices[i];
}
for (size_t i = 0; i < nVectors + 1; ++i)
{
resultRowOffsets[i] = rowOffsets[i];
}
return numericTable;
}
void printAprioriItemsets(NumericTablePtr largeItemsetsTable, NumericTablePtr largeItemsetsSupportTable, size_t nItemsetToPrint = 20)
{
size_t largeItemsetCount = largeItemsetsSupportTable->getNumberOfRows();
size_t nItemsInLargeItemsets = largeItemsetsTable->getNumberOfRows();
BlockDescriptor<int> block1;
largeItemsetsTable->getBlockOfRows(0, nItemsInLargeItemsets, readOnly, block1);
int * largeItemsets = block1.getBlockPtr();
BlockDescriptor<int> block2;
largeItemsetsSupportTable->getBlockOfRows(0, largeItemsetCount, readOnly, block2);
int * largeItemsetsSupportData = block2.getBlockPtr();
std::vector<std::vector<size_t> > largeItemsetsVector;
largeItemsetsVector.resize(largeItemsetCount);
for (size_t i = 0; i < nItemsInLargeItemsets; i++)
{
largeItemsetsVector[largeItemsets[2 * i]].push_back(largeItemsets[2 * i + 1]);
}
std::vector<size_t> supportVector;
supportVector.resize(largeItemsetCount);
for (size_t i = 0; i < largeItemsetCount; i++)
{
supportVector[largeItemsetsSupportData[2 * i]] = largeItemsetsSupportData[2 * i + 1];
}
std::cout << std::endl << "Apriori example program results" << std::endl;
std::cout << std::endl << "Last " << nItemsetToPrint << " large itemsets: " << std::endl;
std::cout << std::endl
<< "Itemset"
<< "\t\t\tSupport" << std::endl;
size_t iMin = (((largeItemsetCount > nItemsetToPrint) && (nItemsetToPrint != 0)) ? largeItemsetCount - nItemsetToPrint : 0);
for (size_t i = iMin; i < largeItemsetCount; i++)
{
std::cout << "{";
for (size_t l = 0; l < largeItemsetsVector[i].size() - 1; l++)
{
std::cout << largeItemsetsVector[i][l] << ", ";
}
std::cout << largeItemsetsVector[i][largeItemsetsVector[i].size() - 1] << "}\t\t";
std::cout << supportVector[i] << std::endl;
}
largeItemsetsTable->releaseBlockOfRows(block1);
largeItemsetsSupportTable->releaseBlockOfRows(block2);
}
void printAprioriRules(NumericTablePtr leftItemsTable, NumericTablePtr rightItemsTable, NumericTablePtr confidenceTable, size_t nRulesToPrint = 20)
{
size_t nRules = confidenceTable->getNumberOfRows();
size_t nLeftItems = leftItemsTable->getNumberOfRows();
size_t nRightItems = rightItemsTable->getNumberOfRows();
BlockDescriptor<int> block1;
leftItemsTable->getBlockOfRows(0, nLeftItems, readOnly, block1);
int * leftItems = block1.getBlockPtr();
BlockDescriptor<int> block2;
rightItemsTable->getBlockOfRows(0, nRightItems, readOnly, block2);
int * rightItems = block2.getBlockPtr();
BlockDescriptor<DAAL_DATA_TYPE> block3;
confidenceTable->getBlockOfRows(0, nRules, readOnly, block3);
DAAL_DATA_TYPE * confidence = block3.getBlockPtr();
std::vector<std::vector<size_t> > leftItemsVector;
leftItemsVector.resize(nRules);
if (nRules == 0)
{
std::cout << std::endl << "No association rules were found " << std::endl;
return;
}
for (size_t i = 0; i < nLeftItems; i++)
{
leftItemsVector[leftItems[2 * i]].push_back(leftItems[2 * i + 1]);
}
std::vector<std::vector<size_t> > rightItemsVector;
rightItemsVector.resize(nRules);
for (size_t i = 0; i < nRightItems; i++)
{
rightItemsVector[rightItems[2 * i]].push_back(rightItems[2 * i + 1]);
}
std::vector<DAAL_DATA_TYPE> confidenceVector;
confidenceVector.resize(nRules);
for (size_t i = 0; i < nRules; i++)
{
confidenceVector[i] = confidence[i];
}
std::cout << std::endl << "Last " << nRulesToPrint << " association rules: " << std::endl;
std::cout << std::endl
<< "Rule"
<< "\t\t\t\tConfidence" << std::endl;
size_t iMin = (((nRules > nRulesToPrint) && (nRulesToPrint != 0)) ? (nRules - nRulesToPrint) : 0);
for (size_t i = iMin; i < nRules; i++)
{
std::cout << "{";
for (size_t l = 0; l < leftItemsVector[i].size() - 1; l++)
{
std::cout << leftItemsVector[i][l] << ", ";
}
std::cout << leftItemsVector[i][leftItemsVector[i].size() - 1] << "} => {";
for (size_t l = 0; l < rightItemsVector[i].size() - 1; l++)
{
std::cout << rightItemsVector[i][l] << ", ";
}
std::cout << rightItemsVector[i][rightItemsVector[i].size() - 1] << "}\t\t";
std::cout << confidenceVector[i] << std::endl;
}
leftItemsTable->releaseBlockOfRows(block1);
rightItemsTable->releaseBlockOfRows(block2);
confidenceTable->releaseBlockOfRows(block3);
}
bool isFull(NumericTableIface::StorageLayout layout)
{
int layoutInt = (int)layout;
if (packed_mask & layoutInt)
{
return false;
}
return true;
}
bool isUpper(NumericTableIface::StorageLayout layout)
{
if (layout == NumericTableIface::upperPackedSymmetricMatrix || layout == NumericTableIface::upperPackedTriangularMatrix)
{
return true;
}
return false;
}
bool isLower(NumericTableIface::StorageLayout layout)
{
if (layout == NumericTableIface::lowerPackedSymmetricMatrix || layout == NumericTableIface::lowerPackedTriangularMatrix)
{
return true;
}
return false;
}
template <typename T>
void printArray(T * array, const size_t nPrintedCols, const size_t nPrintedRows, const size_t nCols, const std::string& message, size_t interval = 10)
{
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
for (size_t i = 0; i < nPrintedRows; i++)
{
for (size_t j = 0; j < nPrintedCols; j++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << array[i * nCols + j];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
template <typename T>
void printArray(T * array, const size_t nCols, const size_t nRows, const std::string& message, size_t interval = 10)
{
printArray(array, nCols, nRows, nCols, message, interval);
}
template <typename T>
void printLowerArray(T * array, const size_t nPrintedRows, const std::string& message, size_t interval = 10)
{
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
int ind = 0;
for (size_t i = 0; i < nPrintedRows; i++)
{
for (size_t j = 0; j <= i; j++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << array[ind++];
}
std::cout << std::endl;
}
std::cout << std::endl;
}
template <typename T>
void printUpperArray(T * array, const size_t nPrintedCols, const size_t nPrintedRows, const size_t nCols, const std::string& message, size_t interval = 10)
{
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
int ind = 0;
for (size_t i = 0; i < nPrintedRows; i++)
{
for (size_t j = 0; j < i; j++)
{
std::cout << " ";
}
for (size_t j = i; j < nPrintedCols; j++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << array[ind++];
}
for (size_t j = nPrintedCols; j < nCols; j++)
{
ind++;
}
std::cout << std::endl;
}
std::cout << std::endl;
}
void printNumericTable(NumericTable * dataTable, const char * message = "", size_t nPrintedRows = 0, size_t nPrintedCols = 0, size_t interval = 10)
{
size_t nRows = dataTable->getNumberOfRows();
size_t nCols = dataTable->getNumberOfColumns();
NumericTableIface::StorageLayout layout = dataTable->getDataLayout();
if (nPrintedRows != 0)
{
nPrintedRows = std::min(nRows, nPrintedRows);
}
else
{
nPrintedRows = nRows;
}
if (nPrintedCols != 0)
{
nPrintedCols = std::min(nCols, nPrintedCols);
}
else
{
nPrintedCols = nCols;
}
BlockDescriptor<DAAL_DATA_TYPE> block;
if (isFull(layout) || layout == NumericTableIface::csrArray)
{
dataTable->getBlockOfRows(0, nRows, readOnly, block);
printArray<DAAL_DATA_TYPE>(block.getBlockPtr(), nPrintedCols, nPrintedRows, nCols, message, interval);
dataTable->releaseBlockOfRows(block);
}
else
{
PackedArrayNumericTableIface * packedTable = dynamic_cast<PackedArrayNumericTableIface *>(dataTable);
packedTable->getPackedArray(readOnly, block);
if (isLower(layout))
{
printLowerArray<DAAL_DATA_TYPE>(block.getBlockPtr(), nPrintedRows, message, interval);
}
else if (isUpper(layout))
{
printUpperArray<DAAL_DATA_TYPE>(block.getBlockPtr(), nPrintedCols, nPrintedRows, nCols, message, interval);
}
packedTable->releasePackedArray(block);
}
}
void printNumericTable(NumericTable & dataTable, const char * message = "", size_t nPrintedRows = 0, size_t nPrintedCols = 0, size_t interval = 10)
{
printNumericTable(&dataTable, message, nPrintedRows, nPrintedCols, interval);
}
void printNumericTable(const NumericTablePtr & dataTable, const char * message = "", size_t nPrintedRows = 0, size_t nPrintedCols = 0,
size_t interval = 10)
{
printNumericTable(dataTable.get(), message, nPrintedRows, nPrintedCols, interval);
}
void printPackedNumericTable(NumericTable * dataTable, size_t nFeatures, const char * message = "", size_t interval = 10)
{
BlockDescriptor<DAAL_DATA_TYPE> block;
dataTable->getBlockOfRows(0, 1, readOnly, block);
DAAL_DATA_TYPE * data = block.getBlockPtr();
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
size_t index = 0;
for (size_t i = 0; i < nFeatures; i++)
{
for (size_t j = 0; j <= i; j++, index++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << data[index];
}
std::cout << std::endl;
}
std::cout << std::endl;
dataTable->releaseBlockOfRows(block);
}
void printPackedNumericTable(NumericTable & dataTable, size_t nFeatures, const char * message = "", size_t interval = 10)
{
printPackedNumericTable(&dataTable, nFeatures, message);
}
template <typename type1, typename type2>
void printNumericTables(NumericTable * dataTable1, NumericTable * dataTable2, const char * title1 = "", const char * title2 = "",
const char * message = "", size_t nPrintedRows = 0, size_t interval = 15)
{
size_t nRows1 = dataTable1->getNumberOfRows();
size_t nRows2 = dataTable2->getNumberOfRows();
size_t nCols1 = dataTable1->getNumberOfColumns();
size_t nCols2 = dataTable2->getNumberOfColumns();
BlockDescriptor<type1> block1;
BlockDescriptor<type2> block2;
size_t nRows = std::min(nRows1, nRows2);
if (nPrintedRows != 0)
{
nRows = std::min(std::min(nRows1, nRows2), nPrintedRows);
}
dataTable1->getBlockOfRows(0, nRows, readOnly, block1);
dataTable2->getBlockOfRows(0, nRows, readOnly, block2);
type1 * data1 = block1.getBlockPtr();
type2 * data2 = block2.getBlockPtr();
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
std::cout << std::setw(interval * nCols1) << title1;
std::cout << std::setw(interval * nCols2) << title2 << std::endl;
for (size_t i = 0; i < nRows; i++)
{
for (size_t j = 0; j < nCols1; j++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << data1[i * nCols1 + j];
}
for (size_t j = 0; j < nCols2; j++)
{
std::cout << std::setprecision(0) << std::setw(interval) << data2[i * nCols2 + j];
}
std::cout << std::endl;
}
std::cout << std::endl;
dataTable1->releaseBlockOfRows(block1);
dataTable2->releaseBlockOfRows(block2);
}
template <typename type1, typename type2>
void printNumericTables(NumericTable * dataTable1, NumericTable & dataTable2, const char * title1 = "", const char * title2 = "",
const char * message = "", size_t nPrintedRows = 0, size_t interval = 10)
{
printNumericTables<type1, type2>(dataTable1, &dataTable2, title1, title2, message, nPrintedRows, interval);
}
void printNumericTables(NumericTable * dataTable1, NumericTable * dataTable2, const char * title1 = "", const char * title2 = "",
const char * message = "", size_t nPrintedRows = 0, size_t interval = 10)
{
size_t nRows1 = dataTable1->getNumberOfRows();
size_t nRows2 = dataTable2->getNumberOfRows();
size_t nCols1 = dataTable1->getNumberOfColumns();
size_t nCols2 = dataTable2->getNumberOfColumns();
BlockDescriptor<DAAL_DATA_TYPE> block1;
BlockDescriptor<DAAL_DATA_TYPE> block2;
size_t nRows = std::min(nRows1, nRows2);
if (nPrintedRows != 0)
{
nRows = std::min(std::min(nRows1, nRows2), nPrintedRows);
}
dataTable1->getBlockOfRows(0, nRows, readOnly, block1);
dataTable2->getBlockOfRows(0, nRows, readOnly, block2);
DAAL_DATA_TYPE * data1 = block1.getBlockPtr();
DAAL_DATA_TYPE * data2 = block2.getBlockPtr();
std::cout << std::setiosflags(std::ios::left);
std::cout << message << std::endl;
std::cout << std::setw(interval * nCols1) << title1;
std::cout << std::setw(interval * nCols2) << title2 << std::endl;
for (size_t i = 0; i < nRows; i++)
{
for (size_t j = 0; j < nCols1; j++)
{
std::cout << std::setw(interval) << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << data1[i * nCols1 + j];
}
for (size_t j = 0; j < nCols2; j++)
{
std::cout << std::setprecision(0) << std::setw(interval) << data2[i * nCols2 + j];
}
std::cout << std::endl;
}
std::cout << std::endl;
dataTable1->releaseBlockOfRows(block1);
dataTable2->releaseBlockOfRows(block2);
}
void printNumericTables(NumericTable * dataTable1, NumericTable & dataTable2, const char * title1 = "", const char * title2 = "",
const char * message = "", size_t nPrintedRows = 0, size_t interval = 10)
{
printNumericTables(dataTable1, &dataTable2, title1, title2, message, nPrintedRows, interval);
}
template <typename type1, typename type2>
void printNumericTables(NumericTablePtr dataTable1, NumericTablePtr dataTable2, const char * title1 = "", const char * title2 = "",
const char * message = "", size_t nPrintedRows = 0, size_t interval = 10)
{
printNumericTables<type1, type2>(dataTable1.get(), dataTable2.get(), title1, title2, message, nPrintedRows, interval);
}
bool checkFileIsAvailable(std::string filename, bool needExit = false)
{
std::ifstream file(filename.c_str());
if (file.good())
{
return true;
}
else
{
std::cout << "Can't open file " << filename << std::endl;
if (needExit)
{
exit(fileError);
}
return false;
}
}
void checkArguments(int argc, char * argv[], int count, ...)
{
std::string ** filelist = new std::string *[count];
va_list ap;
va_start(ap, count);
for (int i = 0; i < count; i++)
{
filelist[i] = va_arg(ap, std::string *);
}
va_end(ap);
if (argc == 1)
{
for (int i = 0; i < count; i++)
{
checkFileIsAvailable(*(filelist[i]), true);
}
}
else if (argc == (count + 1))
{
bool isAllCorrect = true;
for (int i = 0; i < count; i++)
{
if (!checkFileIsAvailable(argv[i + 1]))
{
isAllCorrect = false;
break;
}
}
if (isAllCorrect == true)
{
for (int i = 0; i < count; i++)
{
(*filelist[i]) = argv[i + 1];
}
}
else
{
std::cout << "Warning: Try to open default datasetFileNames" << std::endl;
for (int i = 0; i < count; i++)
{
checkFileIsAvailable(*(filelist[i]), true);
}
}
}
else
{
std::cout << "Usage: " << argv[0] << " [ ";
for (int i = 0; i < count; i++)
{
std::cout << "<filename_" << i << "> ";
}
std::cout << "]" << std::endl;
std::cout << "Warning: Try to open default datasetFileNames" << std::endl;
for (int i = 0; i < count; i++)
{
checkFileIsAvailable(*(filelist[i]), true);
}
}
delete[] filelist;
}
void copyBytes(daal::byte * dst, daal::byte * src, size_t size)
{
for (size_t i = 0; i < size; i++)
{
dst[i] = src[i];
}
}
size_t checkBytes(daal::byte * dst, daal::byte * src, size_t size)
{
for (size_t i = 0; i < size; i++)
{
if (dst[i] != src[i])
{
return i + 1;
}
}
return 0;
}
static const unsigned int crcRem[] = {
0x00000000, 0x741B8CD6, 0xE83719AC, 0x9C2C957A, 0xA475BF8E, 0xD06E3358, 0x4C42A622, 0x38592AF4, 0x3CF0F3CA, 0x48EB7F1C, 0xD4C7EA66, 0xA0DC66B0,
0x98854C44, 0xEC9EC092, 0x70B255E8, 0x04A9D93E, 0x79E1E794, 0x0DFA6B42, 0x91D6FE38, 0xE5CD72EE, 0xDD94581A, 0xA98FD4CC, 0x35A341B6, 0x41B8CD60,
0x4511145E, 0x310A9888, 0xAD260DF2, 0xD93D8124, 0xE164ABD0, 0x957F2706, 0x0953B27C, 0x7D483EAA, 0xF3C3CF28, 0x87D843FE, 0x1BF4D684, 0x6FEF5A52,
0x57B670A6, 0x23ADFC70, 0xBF81690A, 0xCB9AE5DC, 0xCF333CE2, 0xBB28B034, 0x2704254E, 0x531FA998, 0x6B46836C, 0x1F5D0FBA, 0x83719AC0, 0xF76A1616,
0x8A2228BC, 0xFE39A46A, 0x62153110, 0x160EBDC6, 0x2E579732, 0x5A4C1BE4, 0xC6608E9E, 0xB27B0248, 0xB6D2DB76, 0xC2C957A0, 0x5EE5C2DA, 0x2AFE4E0C,
0x12A764F8, 0x66BCE82E, 0xFA907D54, 0x8E8BF182, 0x939C1286, 0xE7879E50, 0x7BAB0B2A, 0x0FB087FC, 0x37E9AD08, 0x43F221DE, 0xDFDEB4A4, 0xABC53872,
0xAF6CE14C, 0xDB776D9A, 0x475BF8E0, 0x33407436, 0x0B195EC2, 0x7F02D214, 0xE32E476E, 0x9735CBB8, 0xEA7DF512, 0x9E6679C4, 0x024AECBE, 0x76516068,
0x4E084A9C, 0x3A13C64A, 0xA63F5330, 0xD224DFE6, 0xD68D06D8, 0xA2968A0E, 0x3EBA1F74, 0x4AA193A2, 0x72F8B956, 0x06E33580, 0x9ACFA0FA, 0xEED42C2C,
0x605FDDAE, 0x14445178, 0x8868C402, 0xFC7348D4, 0xC42A6220, 0xB031EEF6, 0x2C1D7B8C, 0x5806F75A, 0x5CAF2E64, 0x28B4A2B2, 0xB49837C8, 0xC083BB1E,
0xF8DA91EA, 0x8CC11D3C, 0x10ED8846, 0x64F60490, 0x19BE3A3A, 0x6DA5B6EC, 0xF1892396, 0x8592AF40, 0xBDCB85B4, 0xC9D00962, 0x55FC9C18, 0x21E710CE,
0x254EC9F0, 0x51554526, 0xCD79D05C, 0xB9625C8A, 0x813B767E, 0xF520FAA8, 0x690C6FD2, 0x1D17E304, 0x5323A9DA, 0x2738250C, 0xBB14B076, 0xCF0F3CA0,
0xF7561654, 0x834D9A82, 0x1F610FF8, 0x6B7A832E, 0x6FD35A10, 0x1BC8D6C6, 0x87E443BC, 0xF3FFCF6A, 0xCBA6E59E, 0xBFBD6948, 0x2391FC32, 0x578A70E4,
0x2AC24E4E, 0x5ED9C298, 0xC2F557E2, 0xB6EEDB34, 0x8EB7F1C0, 0xFAAC7D16, 0x6680E86C, 0x129B64BA, 0x1632BD84, 0x62293152, 0xFE05A428, 0x8A1E28FE,
0xB247020A, 0xC65C8EDC, 0x5A701BA6, 0x2E6B9770, 0xA0E066F2, 0xD4FBEA24, 0x48D77F5E, 0x3CCCF388, 0x0495D97C, 0x708E55AA, 0xECA2C0D0, 0x98B94C06,
0x9C109538, 0xE80B19EE, 0x74278C94, 0x003C0042, 0x38652AB6, 0x4C7EA660, 0xD052331A, 0xA449BFCC, 0xD9018166, 0xAD1A0DB0, 0x313698CA, 0x452D141C,
0x7D743EE8, 0x096FB23E, 0x95432744, 0xE158AB92, 0xE5F172AC, 0x91EAFE7A, 0x0DC66B00, 0x79DDE7D6, 0x4184CD22, 0x359F41F4, 0xA9B3D48E, 0xDDA85858,
0xC0BFBB5C, 0xB4A4378A, 0x2888A2F0, 0x5C932E26, 0x64CA04D2, 0x10D18804, 0x8CFD1D7E, 0xF8E691A8, 0xFC4F4896, 0x8854C440, 0x1478513A, 0x6063DDEC,
0x583AF718, 0x2C217BCE, 0xB00DEEB4, 0xC4166262, 0xB95E5CC8, 0xCD45D01E, 0x51694564, 0x2572C9B2, 0x1D2BE346, 0x69306F90, 0xF51CFAEA, 0x8107763C,
0x85AEAF02, 0xF1B523D4, 0x6D99B6AE, 0x19823A78, 0x21DB108C, 0x55C09C5A, 0xC9EC0920, 0xBDF785F6, 0x337C7474, 0x4767F8A2, 0xDB4B6DD8, 0xAF50E10E,
0x9709CBFA, 0xE312472C, 0x7F3ED256, 0x0B255E80, 0x0F8C87BE, 0x7B970B68, 0xE7BB9E12, 0x93A012C4, 0xABF93830, 0xDFE2B4E6, 0x43CE219C, 0x37D5AD4A,
0x4A9D93E0, 0x3E861F36, 0xA2AA8A4C, 0xD6B1069A, 0xEEE82C6E, 0x9AF3A0B8, 0x06DF35C2, 0x72C4B914, 0x766D602A, 0x0276ECFC, 0x9E5A7986, 0xEA41F550,
0xD218DFA4, 0xA6035372, 0x3A2FC608, 0x4E344ADE
};
unsigned int getCRC32(daal::byte * input, unsigned int prevRes, size_t len)
{
size_t i;
daal::byte * p;
unsigned int res, highDigit, nextDigit;
const unsigned int crcPoly = 0xBA0DC66B;
p = input;
res = prevRes;
for (i = 0; i < len; i++)
{
highDigit = res >> 24;
nextDigit = (unsigned int)(p[len - 1 - i]);
res = (res << 8) ^ nextDigit;
res = res ^ crcRem[highDigit];
}
if (res >= crcPoly)
{
res = res ^ crcPoly;
}
return res;
}
void printALSRatings(NumericTablePtr usersOffsetTable, NumericTablePtr itemsOffsetTable, NumericTablePtr ratings)
{
size_t nUsers = ratings->getNumberOfRows();
size_t nItems = ratings->getNumberOfColumns();
BlockDescriptor<DAAL_DATA_TYPE> block1;
ratings->getBlockOfRows(0, nUsers, readOnly, block1);
DAAL_DATA_TYPE * ratingsData = block1.getBlockPtr();
size_t usersOffset, itemsOffset;
BlockDescriptor<int> block;
usersOffsetTable->getBlockOfRows(0, 1, readOnly, block);
usersOffset = (size_t)((block.getBlockPtr())[0]);
usersOffsetTable->releaseBlockOfRows(block);
itemsOffsetTable->getBlockOfRows(0, 1, readOnly, block);
itemsOffset = (size_t)((block.getBlockPtr())[0]);
itemsOffsetTable->releaseBlockOfRows(block);
std::cout << " User ID, Item ID, rating" << std::endl;
for (size_t i = 0; i < nUsers; i++)
{
for (size_t j = 0; j < nItems; j++)
{
std::cout << i + usersOffset << ", " << j + itemsOffset << ", " << ratingsData[i * nItems + j] << std::endl;
}
}
ratings->releaseBlockOfRows(block1);
}
size_t serializeDAALObject(SerializationIface * pData, ByteBuffer & buffer)
{
/* Create a data archive to serialize the numeric table */
InputDataArchive dataArch;
/* Serialize the numeric table into the data archive */
pData->serialize(dataArch);
/* Get the length of the serialized data in bytes */
const size_t length = dataArch.getSizeOfArchive();
/* Store the serialized data in an array */
buffer.resize(length);
if (length) dataArch.copyArchiveToArray(&buffer[0], length);
return length;
}
SerializationIfacePtr deserializeDAALObject(daal::byte * buff, size_t length)
{
/* Create a data archive to deserialize the object */
OutputDataArchive dataArch(buff, length);
/* Deserialize the numeric table from the data archive */
return dataArch.getAsSharedPtr();
}
#endif
|
import * as React from 'react';
import {
Edit,
SimpleForm,
TextInput,
} from 'react-admin';
const TracksEdit = (props) => (
<Edit title="Track" {...props}>
<SimpleForm>
<TextInput disabled source="_id" />
<TextInput source="name" />
</SimpleForm>
</Edit>
);
export default TracksEdit;
|
import matplotlib.pyplot as plt
from basic_units import cm
fig = plt.figure()
ax = fig.add_subplot(111)
ax.annotate( "Note 01", [0.5*cm, 0.5*cm] )
# xy and text both unitized
ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data',
xytext=(0.8*cm, 0.95*cm), textcoords='data',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
# mixing units w/ nonunits
ax.annotate('local max', xy=(3*cm, 1*cm), xycoords='data',
xytext=(0.8, 0.95), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
ax.set_xlim(0*cm, 4*cm)
ax.set_ylim(0*cm, 4*cm)
plt.show()
|
def add_time(start, duration):
return new_time
|
var data = {
"body": "<path d=\"M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81c1.66 0 3-1.34 3-3s-1.34-3-3-3s-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65c0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92c0-1.61-1.31-2.92-2.92-2.92zM18 4c.55 0 1 .45 1 1s-.45 1-1 1s-1-.45-1-1s.45-1 1-1zM6 13c-.55 0-1-.45-1-1s.45-1 1-1s1 .45 1 1s-.45 1-1 1zm12 7.02c-.55 0-1-.45-1-1s.45-1 1-1s1 .45 1 1s-.45 1-1 1z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
|
document.addEventListener('DOMContentLoaded', () => {
// Get all "navbar-burger" elements
const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);
// Check if there are any navbar burgers
if ($navbarBurgers.length > 0) {
// Add a click event on each of them
$navbarBurgers.forEach(el => {
el.addEventListener('click', () => {
// Get the target from the "data-target" attribute
const target = el.dataset.target;
const $target = document.getElementById(target);
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
el.classList.toggle('is-active');
$target.classList.toggle('is-active');
});
});
}
});
|
"""
Store strings as constant variables
*Examples:* ::
>>> import temp.constants
>>> s = temp.constants.SPHERE
*Author:*
* Jason.Parks, jason@continuityai.com, 2/25/14 8:09 AM
"""
SPHERE = 'mySphere'
JACK = 'JACK'
|
# Copyright (c) 2021 Cisco Systems, Inc. and its affiliates
# All rights reserved.
# Use of this source code is governed by a BSD 3-Clause License
# that can be found in the LICENSE file.
"""
controller generated to handled auth operation described at:
https://connexion.readthedocs.io/en/latest/security.html
"""
from typing import Dict, Any
from werkzeug.exceptions import Unauthorized
from swagger_server import db
from swagger_server.errors import StreamDoesNotExist
def check_BearerAuth(token: str) -> Dict[str, Any]:
"""Get the client ID from the dict of known tokens. Raise an error if
token is unknown
"""
if not db.stream_exists(token):
raise StreamDoesNotExist()
return {
'client_id': token,
'active': True,
}
|
/*global defineSuite*/
defineSuite([
'DataSources/CzmlDataSource',
'Core/BoundingRectangle',
'Core/Cartesian2',
'Core/Cartesian3',
'Core/Cartographic',
'Core/ClockRange',
'Core/ClockStep',
'Core/Color',
'Core/CornerType',
'Core/defined',
'Core/Ellipsoid',
'Core/Event',
'Core/ExtrapolationType',
'Core/Iso8601',
'Core/JulianDate',
'Core/loadJson',
'Core/Math',
'Core/NearFarScalar',
'Core/Quaternion',
'Core/Rectangle',
'Core/ReferenceFrame',
'Core/RuntimeError',
'Core/Spherical',
'Core/TimeInterval',
'Core/TranslationRotationScale',
'DataSources/EntityCollection',
'DataSources/ReferenceProperty',
'DataSources/StripeOrientation',
'Scene/HeightReference',
'Scene/HorizontalOrigin',
'Scene/LabelStyle',
'Scene/VerticalOrigin',
'Specs/pollToPromise',
'ThirdParty/when'
], function(
CzmlDataSource,
BoundingRectangle,
Cartesian2,
Cartesian3,
Cartographic,
ClockRange,
ClockStep,
Color,
CornerType,
defined,
Ellipsoid,
Event,
ExtrapolationType,
Iso8601,
JulianDate,
loadJson,
CesiumMath,
NearFarScalar,
Quaternion,
Rectangle,
ReferenceFrame,
RuntimeError,
Spherical,
TimeInterval,
TranslationRotationScale,
EntityCollection,
ReferenceProperty,
StripeOrientation,
HeightReference,
HorizontalOrigin,
LabelStyle,
VerticalOrigin,
pollToPromise,
when) {
'use strict';
function makePacket(packet) {
return [{
id : 'document',
version : '1.0'
}, packet];
}
var staticCzml = {
'id' : 'test',
'billboard' : {
'show' : true
}
};
var czmlDelete = {
'id' : 'test',
'delete' : true
};
var dynamicCzml = {
id : 'test',
availability : '2000-01-01/2001-01-01',
billboard : {
show : true
}
};
var clockCzml = {
id : 'document',
version : '1.0',
clock : {
interval : '2012-03-15T10:00:00Z/2012-03-16T10:00:00Z',
currentTime : '2012-03-15T10:00:00Z',
multiplier : 60.0,
range : 'LOOP_STOP',
step : 'SYSTEM_CLOCK_MULTIPLIER'
}
};
var clockCzml2 = {
id : 'document',
version : '1.0',
clock : {
interval : '2013-03-15T10:00:00Z/2013-03-16T10:00:00Z',
currentTime : '2013-03-15T10:00:00Z',
multiplier : 30.0,
range : 'UNBOUNDED',
step : 'TICK_DEPENDENT'
}
};
var parsedClock = {
interval : TimeInterval.fromIso8601({
iso8601 : clockCzml.clock.interval
}),
currentTime : JulianDate.fromIso8601(clockCzml.clock.currentTime),
multiplier : clockCzml.clock.multiplier,
range : ClockRange[clockCzml.clock.range],
step : ClockStep[clockCzml.clock.step]
};
var parsedClock2 = {
interval : TimeInterval.fromIso8601({
iso8601 : clockCzml2.clock.interval
}),
currentTime : JulianDate.fromIso8601(clockCzml2.clock.currentTime),
multiplier : clockCzml2.clock.multiplier,
range : ClockRange[clockCzml2.clock.range],
step : ClockStep[clockCzml2.clock.step]
};
var nameCzml = {
id : 'document',
version : '1.0',
name : 'czmlName'
};
var simple;
var simpleUrl = 'Data/CZML/simple.czml';
var vehicle;
var vehicleUrl = 'Data/CZML/Vehicle.czml';
beforeAll(function() {
return when.join(
loadJson(simpleUrl).then(function(result) {
simple = result;
}),
loadJson(vehicleUrl).then(function(result) {
vehicle = result;
}));
});
it('default constructor has expected values', function() {
var dataSource = new CzmlDataSource();
expect(dataSource.changedEvent).toBeInstanceOf(Event);
expect(dataSource.errorEvent).toBeInstanceOf(Event);
expect(dataSource.name).toBeUndefined();
expect(dataSource.clock).toBeUndefined();
expect(dataSource.entities).toBeInstanceOf(EntityCollection);
expect(dataSource.entities.values.length).toEqual(0);
expect(dataSource.show).toBe(true);
});
it('show sets underlying entity collection show.', function() {
var dataSource = new CzmlDataSource();
dataSource.show = false;
expect(dataSource.show).toBe(false);
expect(dataSource.show).toEqual(dataSource.entities.show);
dataSource.show = true;
expect(dataSource.show).toBe(true);
expect(dataSource.show).toEqual(dataSource.entities.show);
});
it('name returns CZML defined name', function() {
var dataSource = new CzmlDataSource();
dataSource.load(nameCzml);
expect(dataSource.name).toEqual('czmlName');
});
it('name uses source name if CZML name is undefined', function() {
var dataSource = new CzmlDataSource();
dataSource.load(clockCzml, {
sourceUri : 'Gallery/simple.czml?asd=true'
});
expect(dataSource.name).toEqual('simple.czml');
});
it('does not overwrite existing name if CZML name is undefined', function() {
var dataSource = new CzmlDataSource('myName');
dataSource.load(clockCzml, {
sourceUri : 'Gallery/simple.czml'
});
expect(dataSource.name).toEqual('myName');
});
it('clock returns undefined for static CZML', function() {
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(staticCzml));
expect(dataSource.clock).toBeUndefined();
});
it('clock returns CZML defined clock', function() {
var dataSource = new CzmlDataSource();
dataSource.load(clockCzml);
var clock = dataSource.clock;
expect(clock).toBeDefined();
expect(clock.startTime).toEqual(parsedClock.interval.start);
expect(clock.stopTime).toEqual(parsedClock.interval.stop);
expect(clock.currentTime).toEqual(parsedClock.currentTime);
expect(clock.clockRange).toEqual(parsedClock.range);
expect(clock.clockStep).toEqual(parsedClock.step);
expect(clock.multiplier).toEqual(parsedClock.multiplier);
dataSource.process(clockCzml2);
expect(clock).toBeDefined();
expect(clock.startTime).toEqual(parsedClock2.interval.start);
expect(clock.stopTime).toEqual(parsedClock2.interval.stop);
expect(clock.currentTime).toEqual(parsedClock2.currentTime);
expect(clock.clockRange).toEqual(parsedClock2.range);
expect(clock.clockStep).toEqual(parsedClock2.step);
expect(clock.multiplier).toEqual(parsedClock2.multiplier);
});
it('clock returns data interval if no clock defined', function() {
var interval = TimeInterval.fromIso8601({
iso8601 : dynamicCzml.availability
});
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(dynamicCzml));
var clock = dataSource.clock;
expect(clock).toBeDefined();
expect(clock.startTime).toEqual(interval.start);
expect(clock.stopTime).toEqual(interval.stop);
expect(clock.currentTime).toEqual(interval.start);
expect(clock.clockRange).toEqual(ClockRange.LOOP_STOP);
expect(clock.clockStep).toEqual(ClockStep.SYSTEM_CLOCK_MULTIPLIER);
expect(clock.multiplier).toEqual(JulianDate.secondsDifference(interval.stop, interval.start) / 120.0);
});
it('process loads expected data', function() {
var dataSource = new CzmlDataSource();
dataSource.process(simple, simpleUrl);
expect(dataSource.entities.values.length).toEqual(10);
});
it('process loads data on top of existing', function() {
var dataSource = new CzmlDataSource();
dataSource.process(simple, simpleUrl);
expect(dataSource.entities.values.length === 10);
dataSource.process(vehicle, vehicleUrl);
expect(dataSource.entities.values.length === 11);
});
it('load replaces data', function() {
var dataSource = new CzmlDataSource();
dataSource.process(simple, simpleUrl);
expect(dataSource.entities.values.length).toEqual(10);
dataSource.load(vehicle, vehicleUrl);
expect(dataSource.entities.values.length).toEqual(1);
});
it('process throws with undefined CZML', function() {
var dataSource = new CzmlDataSource();
expect(function() {
dataSource.process(undefined);
}).toThrowDeveloperError();
});
it('load throws with undefined CZML', function() {
var dataSource = new CzmlDataSource();
expect(function() {
dataSource.load(undefined);
}).toThrowDeveloperError();
});
it('raises changed event when loading CZML', function() {
var dataSource = new CzmlDataSource();
var spy = jasmine.createSpy('changedEvent');
dataSource.changedEvent.addEventListener(spy);
dataSource.load(clockCzml);
expect(spy).toHaveBeenCalledWith(dataSource);
});
it('raises changed event when name changes in CZML', function() {
var dataSource = new CzmlDataSource();
var originalCzml = {
id : 'document',
version : '1.0',
name : 'czmlName'
};
dataSource.load(originalCzml);
var spy = jasmine.createSpy('changedEvent');
dataSource.changedEvent.addEventListener(spy);
var newCzml = {
id : 'document',
name : 'newCzmlName'
};
dataSource.process(newCzml);
expect(spy).toHaveBeenCalledWith(dataSource);
});
it('does not raise changed event when name does not change in CZML', function() {
var dataSource = new CzmlDataSource();
dataSource.load(nameCzml);
var spy = jasmine.createSpy('changedEvent');
dataSource.changedEvent.addEventListener(spy);
dataSource.load(nameCzml);
expect(spy).not.toHaveBeenCalled();
});
it('raises changed event when clock changes in CZML', function() {
var dataSource = new CzmlDataSource();
var originalCzml = {
id : 'document',
version : '1.0',
clock : {
interval : '2012-03-15T10:00:00Z/2012-03-16T10:00:00Z',
currentTime : '2012-03-15T10:00:00Z',
multiplier : 60.0,
range : 'LOOP_STOP',
step : 'SYSTEM_CLOCK_MULTIPLIER'
}
};
dataSource.load(originalCzml);
var spy = jasmine.createSpy('changedEvent');
dataSource.changedEvent.addEventListener(spy);
var newCzml = {
id : 'document',
version : '1.0',
clock : {
interval : '2013-03-15T10:00:00Z/2013-03-16T10:00:00Z',
currentTime : '2012-03-15T10:00:00Z',
multiplier : 60.0,
range : 'LOOP_STOP',
step : 'SYSTEM_CLOCK_MULTIPLIER'
}
};
dataSource.load(newCzml);
expect(spy).toHaveBeenCalledWith(dataSource);
});
it('does not raise changed event when clock does not change in CZML', function() {
var dataSource = new CzmlDataSource();
dataSource.load(clockCzml);
var spy = jasmine.createSpy('changedEvent');
dataSource.changedEvent.addEventListener(spy);
dataSource.load(clockCzml);
expect(spy).not.toHaveBeenCalled();
});
it('raises error when an error occurs in load', function() {
var dataSource = new CzmlDataSource();
var spy = jasmine.createSpy('errorEvent');
dataSource.errorEvent.addEventListener(spy);
// Blue.png is not JSON
return dataSource.load('Data/Images/Blue.png').then(function() {
fail('should not be called');
}).otherwise(function() {
expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error));
});
});
it('raises error when an error occurs in process', function() {
var dataSource = new CzmlDataSource();
var spy = jasmine.createSpy('errorEvent');
dataSource.errorEvent.addEventListener(spy);
// Blue.png is not JSON
dataSource.process('Data/Images/Blue.png').then(function() {
fail('should not be called');
}).otherwise(function() {
expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error));
});
});
it('CZML adds data for infinite billboard.', function() {
var sourceUri = 'http://someImage.invalid/';
var billboardPacket = {
billboard : {
image : 'image.png',
scale : 1.0,
rotation : 1.3,
heightReference: 'CLAMP_TO_GROUND',
horizontalOrigin : 'CENTER',
verticalOrigin : 'CENTER',
color : {
rgbaf : [1.0, 1.0, 1.0, 1.0]
},
eyeOffset : {
cartesian : [3.0, 4.0, 5.0]
},
pixelOffset : {
cartesian2 : [1.0, 2.0]
},
alignedAxis : {
cartesian : [1.0, 0.0, 0.0]
},
show : true,
sizeInMeters : false,
width : 10,
height : 11,
scaleByDistance : {
nearFarScalar : [1.0, 2.0, 10000.0, 3.0]
},
translucencyByDistance : {
nearFarScalar : [1.0, 1.0, 10000.0, 0.0]
},
pixelOffsetScaleByDistance : {
nearFarScalar : [1.0, 20.0, 10000.0, 30.0]
},
imageSubRegion : {
boundingRectangle : [20, 30, 10, 11]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket), {
sourceUri : sourceUri
});
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image.getValue(Iso8601.MINIMUM_VALUE)).toEqual(sourceUri + 'image.png');
expect(entity.billboard.rotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(billboardPacket.billboard.rotation);
expect(entity.billboard.scale.getValue(Iso8601.MINIMUM_VALUE)).toEqual(billboardPacket.billboard.scale);
expect(entity.billboard.heightReference.getValue(Iso8601.MINIMUM_VALUE)).toEqual(HeightReference.CLAMP_TO_GROUND);
expect(entity.billboard.horizontalOrigin.getValue(Iso8601.MINIMUM_VALUE)).toEqual(HorizontalOrigin.CENTER);
expect(entity.billboard.verticalOrigin.getValue(Iso8601.MINIMUM_VALUE)).toEqual(VerticalOrigin.CENTER);
expect(entity.billboard.color.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(1.0, 1.0, 1.0, 1.0));
expect(entity.billboard.eyeOffset.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expect(entity.billboard.pixelOffset.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian2(1.0, 2.0));
expect(entity.billboard.alignedAxis.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1.0, 0.0, 0.0));
expect(entity.billboard.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.billboard.sizeInMeters.getValue(Iso8601.MINIMUM_VALUE)).toEqual(false);
expect(entity.billboard.width.getValue(Iso8601.MINIMUM_VALUE)).toEqual(10);
expect(entity.billboard.height.getValue(Iso8601.MINIMUM_VALUE)).toEqual(11);
expect(entity.billboard.scaleByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 2.0, 10000.0, 3.0));
expect(entity.billboard.translucencyByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 1.0, 10000.0, 0.0));
expect(entity.billboard.pixelOffsetScaleByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 20.0, 10000.0, 30.0));
expect(entity.billboard.imageSubRegion.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new BoundingRectangle(20, 30, 10, 11));
});
it('can handle image intervals both of type uri and image', function() {
var source = 'http://some.url.invalid/';
var packet = {
billboard : {
image : [{
interval : '2013-01-01T00:00:00Z/2013-01-01T01:00:00Z',
uri : 'image.png'
}, {
interval : '2013-01-01T01:00:00Z/2013-01-01T02:00:00Z',
uri : 'image2.png'
}]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet), {
sourceUri : source
});
var entity = dataSource.entities.values[0];
var imageProperty = entity.billboard.image;
expect(imageProperty.getValue(JulianDate.fromIso8601('2013-01-01T00:00:00Z'))).toEqual(source + 'image.png');
expect(imageProperty.getValue(JulianDate.fromIso8601('2013-01-01T01:00:00Z'))).toEqual(source + 'image2.png');
});
it('CZML adds data for constrained billboard.', function() {
var billboardPacket = {
billboard : {
interval : '2000-01-01/2001-01-01',
image : 'http://someImage.invalid/image',
scale : 1.0,
horizontalOrigin : 'CENTER',
verticalOrigin : 'CENTER',
color : {
rgbaf : [1.0, 1.0, 1.0, 1.0]
},
eyeOffset : {
cartesian : [3.0, 4.0, 5.0]
},
pixelOffset : {
cartesian2 : [1.0, 2.0]
},
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : billboardPacket.billboard.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket));
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image.getValue(validTime)).toEqual(billboardPacket.billboard.image);
expect(entity.billboard.scale.getValue(validTime)).toEqual(billboardPacket.billboard.scale);
expect(entity.billboard.horizontalOrigin.getValue(validTime)).toEqual(HorizontalOrigin.CENTER);
expect(entity.billboard.verticalOrigin.getValue(validTime)).toEqual(VerticalOrigin.CENTER);
expect(entity.billboard.color.getValue(validTime)).toEqual(new Color(1.0, 1.0, 1.0, 1.0));
expect(entity.billboard.eyeOffset.getValue(validTime)).toEqual(new Cartesian3(3.0, 4.0, 5.0));
expect(entity.billboard.pixelOffset.getValue(validTime)).toEqual(new Cartesian2(1.0, 2.0));
expect(entity.billboard.show.getValue(validTime)).toEqual(true);
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.scale.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.horizontalOrigin.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.verticalOrigin.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.color.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.eyeOffset.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.pixelOffset.getValue(invalidTime)).toBeUndefined();
expect(entity.billboard.show.getValue(invalidTime)).toBeUndefined();
});
it('can handle sampled billboard pixelOffset.', function() {
var epoch = JulianDate.now();
var billboardPacket = {
billboard : {
pixelOffset : {
epoch : JulianDate.toIso8601(epoch),
cartesian2 : [0.0, 1.0, 2.0,
1.0, 3.0, 4.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket));
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 0.5, new JulianDate());
var date3 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
expect(entity.billboard.pixelOffset.getValue(date1)).toEqual(new Cartesian2(1.0, 2.0));
expect(entity.billboard.pixelOffset.getValue(date2)).toEqual(new Cartesian2(2.0, 3.0));
expect(entity.billboard.pixelOffset.getValue(date3)).toEqual(new Cartesian2(3.0, 4.0));
});
it('can handle interval billboard scaleByDistance.', function() {
var billboardPacket = {
billboard : {
scaleByDistance : [{
interval : '2013-01-01T00:00:00Z/2013-01-01T01:00:00Z',
nearFarScalar : [1.0, 2.0, 10000.0, 3.0]
}, {
interval : '2013-01-01T01:00:00Z/2013-01-01T02:00:00Z',
nearFarScalar : [2.0, 3.0, 20000.0, 4.0]
}]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket));
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
expect(entity.billboard.scaleByDistance.getValue(JulianDate.fromIso8601('2013-01-01T00:00:00Z'))).toEqual(new NearFarScalar(1.0, 2.0, 10000.0, 3.0));
expect(entity.billboard.scaleByDistance.getValue(JulianDate.fromIso8601('2013-01-01T01:00:00Z'))).toEqual(new NearFarScalar(2.0, 3.0, 20000.0, 4.0));
});
it('can handle sampled billboard scaleByDistance.', function() {
var epoch = JulianDate.now();
var billboardPacket = {
billboard : {
scaleByDistance : {
epoch : JulianDate.toIso8601(epoch),
nearFarScalar : [
0, 1.0, 2.0, 10000.0, 3.0,
2, 2.0, 3.0, 20000.0, 4.0
]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket));
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
var date3 = JulianDate.addSeconds(epoch, 2.0, new JulianDate());
expect(entity.billboard.scaleByDistance.getValue(date1)).toEqual(new NearFarScalar(1.0, 2.0, 10000.0, 3.0));
expect(entity.billboard.scaleByDistance.getValue(date2)).toEqual(new NearFarScalar(1.5, 2.5, 15000.0, 3.5));
expect(entity.billboard.scaleByDistance.getValue(date3)).toEqual(new NearFarScalar(2.0, 3.0, 20000.0, 4.0));
});
it('can handle sampled billboard color rgba.', function() {
var epoch = JulianDate.now();
var billboardPacket = {
billboard : {
color : {
epoch : JulianDate.toIso8601(epoch),
rgba : [0, 200, 202, 204, 206,
2, 0, 0, 0, 0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(billboardPacket));
var entity = dataSource.entities.values[0];
expect(entity.billboard).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
var date3 = JulianDate.addSeconds(epoch, 2.0, new JulianDate());
expect(entity.billboard.color.getValue(date1)).toEqual(Color.fromBytes(200, 202, 204, 206));
expect(entity.billboard.color.getValue(date2)).toEqual(Color.fromBytes(100, 101, 102, 103));
expect(entity.billboard.color.getValue(date3)).toEqual(Color.fromBytes(0, 0, 0, 0));
});
it('can handle clock data.', function() {
var clockPacket = {
id : 'document',
version : '1.0',
clock : {
interval : '2012-03-15T10:00:00Z/2012-03-16T10:00:00Z',
currentTime : '2012-03-15T10:00:00Z',
multiplier : 60.0,
range : 'LOOP_STOP',
step : 'SYSTEM_CLOCK_MULTIPLIER'
}
};
var interval = TimeInterval.fromIso8601({
iso8601 : clockPacket.clock.interval
});
var currentTime = JulianDate.fromIso8601(clockPacket.clock.currentTime);
var multiplier = clockPacket.clock.multiplier;
var range = ClockRange[clockPacket.clock.range];
var step = ClockStep[clockPacket.clock.step];
var dataSource = new CzmlDataSource();
dataSource.load(clockPacket);
expect(dataSource.clock).toBeDefined();
expect(dataSource.clock.startTime).toEqual(interval.start);
expect(dataSource.clock.stopTime).toEqual(interval.stop);
expect(dataSource.clock.currentTime).toEqual(currentTime);
expect(dataSource.clock.clockRange).toEqual(range);
expect(dataSource.clock.clockStep).toEqual(step);
expect(dataSource.clock.multiplier).toEqual(multiplier);
});
it('can handle position specified as constant cartographicsDegrees.', function() {
var czml = {
position : {
cartographicDegrees : [34, 117, 10000]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.position.getValue(JulianDate.now());
expect(resultCartesian).toEqual(Cartesian3.fromDegrees(34, 117, 10000));
});
it('can handle position specified as sampled cartographicsDegrees.', function() {
var epoch = JulianDate.now();
var czml = {
position : {
epoch : JulianDate.toIso8601(epoch),
cartographicDegrees : [0, 34, 117, 10000,
1, 34, 117, 20000]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.position.getValue(epoch);
expect(resultCartesian).toEqual(Cartesian3.fromDegrees(34, 117, 10000));
resultCartesian = entity.position.getValue(JulianDate.addSeconds(epoch, 1, new JulianDate()));
expect(resultCartesian).toEqual(Cartesian3.fromDegrees(34, 117, 20000));
});
it('can handle position specified as sampled cartographicDegrees without epoch.', function() {
var lastDate = JulianDate.now();
var firstDate = new JulianDate(lastDate.dayNumber - 1, 0);
var czml = {
position : {
cartographicDegrees : [JulianDate.toIso8601(firstDate), 34, 117, 10000,
JulianDate.toIso8601(lastDate), 34, 117, 20000]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.position.getValue(firstDate);
expect(resultCartesian).toEqual(Cartesian3.fromDegrees(34, 117, 10000));
resultCartesian = entity.position.getValue(lastDate);
expect(resultCartesian).toEqual(Cartesian3.fromDegrees(34, 117, 20000));
});
it('can handle position specified as constant cartographicRadians.', function() {
var czml = {
position : {
cartographicRadians : [1, 2, 10000]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.position.getValue(JulianDate.now());
expect(resultCartesian).toEqual(Cartesian3.fromRadians(1, 2, 10000));
});
it('can handle position specified as sampled cartographicRadians.', function() {
var epoch = JulianDate.now();
var czml = {
position : {
epoch : JulianDate.toIso8601(epoch),
cartographicRadians : [0, 2, 0.3, 10000,
1, 0.2, 0.5, 20000]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.position.getValue(epoch);
expect(resultCartesian).toEqual(Cartesian3.fromRadians(2, 0.3, 10000));
resultCartesian = entity.position.getValue(JulianDate.addSeconds(epoch, 1, new JulianDate()));
expect(resultCartesian).toEqual(Cartesian3.fromRadians(0.2, 0.5, 20000));
});
it('Can set reference frame', function() {
var epoch = JulianDate.now();
var dataSource = new CzmlDataSource();
var czml = {
position : {
referenceFrame : 'INERTIAL',
epoch : JulianDate.toIso8601(epoch),
cartesian : [1.0, 2.0, 3.0]
}
};
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
expect(entity.position.referenceFrame).toBe(ReferenceFrame.INERTIAL);
czml = {
position : {
referenceFrame : 'FIXED',
epoch : JulianDate.toIso8601(epoch),
cartesian : [1.0, 2.0, 3.0]
}
};
dataSource.load(makePacket(czml));
entity = dataSource.entities.values[0];
expect(entity.position.referenceFrame).toBe(ReferenceFrame.FIXED);
});
it('uses FIXED as default if not specified in CZML', function() {
var epoch = JulianDate.now();
var dataSource = new CzmlDataSource();
var czml = {
position : {
epoch : JulianDate.toIso8601(epoch),
cartesian : [1.0, 2.0, 3.0]
}
};
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
expect(entity.position.referenceFrame).toBe(ReferenceFrame.FIXED);
});
it('Default reference frame on existing interval does not reset value to FIXED.', function() {
var epoch = JulianDate.now();
var dataSource = new CzmlDataSource();
var czml = {
position : {
referenceFrame : 'INERTIAL',
epoch : JulianDate.toIso8601(epoch),
cartesian : [1.0, 2.0, 3.0]
}
};
dataSource.process(makePacket(czml));
var entity = dataSource.entities.values[0];
expect(entity.position.referenceFrame).toBe(ReferenceFrame.INERTIAL);
var czml2 = {
position : {
epoch : JulianDate.toIso8601(epoch),
cartesian : [1.0, 2.0, 3.0]
}
};
dataSource.process(czml2);
expect(entity.position.referenceFrame).toBe(ReferenceFrame.INERTIAL);
});
it('can handle a number specified as sampled values without epoch.', function() {
var firstDate = Iso8601.MINIMUM_VALUE;
var midDate = JulianDate.addDays(firstDate, 1, new JulianDate());
var lastDate = JulianDate.addDays(firstDate, 2, new JulianDate());
var ellipsePacket = {
ellipse : {
semiMajorAxis : {
number : [JulianDate.toIso8601(firstDate), 0,
JulianDate.toIso8601(lastDate), 10]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(ellipsePacket));
var entity = dataSource.entities.values[0];
expect(entity.ellipse).toBeDefined();
expect(entity.ellipse.semiMajorAxis.getValue(firstDate)).toEqual(0);
expect(entity.ellipse.semiMajorAxis.getValue(midDate)).toEqual(5);
expect(entity.ellipse.semiMajorAxis.getValue(lastDate)).toEqual(10);
});
it('can handle a direction specified as constant unitSpherical', function() {
var czml = {
billboard : {
alignedAxis : {
unitSpherical : [1.0, 2.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.billboard.alignedAxis.getValue(JulianDate.now());
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(1.0, 2.0)));
});
it('can handle a direction specified as sampled unitSpherical.', function() {
var epoch = JulianDate.now();
var czml = {
billboard : {
alignedAxis : {
epoch : JulianDate.toIso8601(epoch),
unitSpherical : [0, 1.0, 2.0,
1, -1.0, -2.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.billboard.alignedAxis.getValue(epoch);
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(1.0, 2.0)));
resultCartesian = entity.billboard.alignedAxis.getValue(JulianDate.addSeconds(epoch, 1, new JulianDate()));
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(-1.0, -2.0)));
});
it('can handle a direction specified as constant spherical', function() {
var czml = {
billboard : {
alignedAxis : {
spherical : [1.0, 2.0, 30.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.billboard.alignedAxis.getValue(JulianDate.now());
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(1.0, 2.0, 30.0)));
});
it('can handle a direction specified as sampled spherical.', function() {
var epoch = JulianDate.now();
var czml = {
billboard : {
alignedAxis : {
epoch : JulianDate.toIso8601(epoch),
spherical : [0, 1.0, 2.0, 30.0,
1, -1.0, -2.0, 40.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(czml));
var entity = dataSource.entities.values[0];
var resultCartesian = entity.billboard.alignedAxis.getValue(epoch);
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(1.0, 2.0, 30.0)));
resultCartesian = entity.billboard.alignedAxis.getValue(JulianDate.addSeconds(epoch, 1, new JulianDate()));
expect(resultCartesian).toEqual(Cartesian3.fromSpherical(new Spherical(-1.0, -2.0, 40.0)));
});
it('CZML adds data for infinite ellipse.', function() {
var ellipsePacket = {
ellipse : {
semiMajorAxis : 10,
semiMinorAxis : 20,
rotation : 1.0,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(ellipsePacket));
var entity = dataSource.entities.values[0];
expect(entity.ellipse).toBeDefined();
expect(entity.ellipse.semiMajorAxis.getValue(Iso8601.MINIMUM_VALUE)).toEqual(ellipsePacket.ellipse.semiMajorAxis);
expect(entity.ellipse.semiMinorAxis.getValue(Iso8601.MINIMUM_VALUE)).toEqual(ellipsePacket.ellipse.semiMinorAxis);
expect(entity.ellipse.rotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(ellipsePacket.ellipse.rotation);
expect(entity.ellipse.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.ellipse.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.ellipse.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
});
it('CZML adds data for constrained ellipse.', function() {
var ellipsePacketInterval = {
ellipse : {
interval : '2000-01-01/2001-01-01',
semiMajorAxis : 10,
semiMinorAxis : 20,
rotation : 1.0
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(ellipsePacketInterval));
var entity = dataSource.entities.values[0];
var validTime = TimeInterval.fromIso8601({
iso8601 : ellipsePacketInterval.ellipse.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
expect(entity.ellipse).toBeDefined();
expect(entity.ellipse.semiMajorAxis.getValue(validTime)).toEqual(ellipsePacketInterval.ellipse.semiMajorAxis);
expect(entity.ellipse.semiMinorAxis.getValue(validTime)).toEqual(ellipsePacketInterval.ellipse.semiMinorAxis);
expect(entity.ellipse.rotation.getValue(validTime)).toEqual(ellipsePacketInterval.ellipse.rotation);
expect(entity.ellipse.semiMajorAxis.getValue(invalidTime)).toBeUndefined();
expect(entity.ellipse.semiMinorAxis.getValue(invalidTime)).toBeUndefined();
expect(entity.ellipse.rotation.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite ellipsoid.', function() {
var expectedRadii = new Cartesian3(1.0, 2.0, 3.0);
var ellipsoidPacket = {
ellipsoid : {
radii : {
cartesian : [1.0, 2.0, 3.0]
},
show : true,
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
},
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6,
stackPartitions : 25,
slicePartitions : 26,
subdivisions : 27
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(ellipsoidPacket));
var entity = dataSource.entities.values[0];
expect(entity.ellipsoid).toBeDefined();
expect(entity.ellipsoid.radii.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedRadii);
expect(entity.ellipsoid.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(ellipsoidPacket.ellipsoid.show);
expect(entity.ellipsoid.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.ellipsoid.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.ellipsoid.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.ellipsoid.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
expect(entity.ellipsoid.stackPartitions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(25);
expect(entity.ellipsoid.slicePartitions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(26);
expect(entity.ellipsoid.subdivisions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(27);
});
it('CZML adds data for constrained ellipsoid.', function() {
var expectedRadii = new Cartesian3(1.0, 2.0, 3.0);
var ellipsoidPacketInterval = {
ellipsoid : {
interval : '2000-01-01/2001-01-01',
radii : {
cartesian : [1.0, 2.0, 3.0]
},
show : true,
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
}
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : ellipsoidPacketInterval.ellipsoid.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(ellipsoidPacketInterval));
var entity = dataSource.entities.values[0];
expect(entity.ellipsoid).toBeDefined();
expect(entity.ellipsoid.radii.getValue(validTime)).toEqual(expectedRadii);
expect(entity.ellipsoid.show.getValue(validTime)).toEqual(ellipsoidPacketInterval.ellipsoid.show);
expect(entity.ellipsoid.material.getValue(validTime).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.ellipsoid.radii.getValue(invalidTime)).toBeUndefined();
expect(entity.ellipsoid.show.getValue(invalidTime)).toBeUndefined();
expect(entity.ellipsoid.material.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite label.', function() {
var labelPacket = {
label : {
text : 'TestFacility',
font : '10pt "Open Sans"',
style : 'FILL',
fillColor : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 3.14,
horizontalOrigin : 'LEFT',
verticalOrigin : 'CENTER',
eyeOffset : {
cartesian : [1.0, 2.0, 3.0]
},
pixelOffset : {
cartesian2 : [4.0, 5.0]
},
scale : 1.0,
show : true,
translucencyByDistance : {
nearFarScalar : [1.0, 1.0, 10000.0, 0.0]
},
pixelOffsetScaleByDistance : {
nearFarScalar : [1.0, 20.0, 10000.0, 30.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(labelPacket));
var entity = dataSource.entities.values[0];
expect(entity.label).toBeDefined();
expect(entity.label.text.getValue(Iso8601.MINIMUM_VALUE)).toEqual(labelPacket.label.text);
expect(entity.label.font.getValue(Iso8601.MINIMUM_VALUE)).toEqual(labelPacket.label.font);
expect(entity.label.style.getValue(Iso8601.MINIMUM_VALUE)).toEqual(LabelStyle.FILL);
expect(entity.label.fillColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.label.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.label.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(labelPacket.label.outlineWidth);
expect(entity.label.horizontalOrigin.getValue(Iso8601.MINIMUM_VALUE)).toEqual(HorizontalOrigin.LEFT);
expect(entity.label.verticalOrigin.getValue(Iso8601.MINIMUM_VALUE)).toEqual(VerticalOrigin.CENTER);
expect(entity.label.eyeOffset.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(entity.label.pixelOffset.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian2(4.0, 5.0));
expect(entity.label.scale.getValue(Iso8601.MINIMUM_VALUE)).toEqual(labelPacket.label.scale);
expect(entity.label.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(labelPacket.label.show);
expect(entity.label.translucencyByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 1.0, 10000.0, 0.0));
expect(entity.label.pixelOffsetScaleByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 20.0, 10000.0, 30.0));
});
it('CZML adds data for constrained label.', function() {
var labelPacket = {
label : {
interval : '2000-01-01/2001-01-01',
text : 'TestFacility',
font : '10pt "Open Sans"',
style : 'FILL',
fillColor : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 2.78,
horizontalOrigin : 'LEFT',
verticalOrigin : 'CENTER',
eyeOffset : {
cartesian : [1.0, 2.0, 3.0]
},
pixelOffset : {
cartesian2 : [4.0, 5.0]
},
scale : 1.0,
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : labelPacket.label.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(labelPacket));
var entity = dataSource.entities.values[0];
expect(entity.label).toBeDefined();
expect(entity.label.text.getValue(validTime)).toEqual(labelPacket.label.text);
expect(entity.label.font.getValue(validTime)).toEqual(labelPacket.label.font);
expect(entity.label.style.getValue(validTime)).toEqual(LabelStyle.FILL);
expect(entity.label.fillColor.getValue(validTime)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.label.outlineColor.getValue(validTime)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.label.outlineWidth.getValue(validTime)).toEqual(labelPacket.label.outlineWidth);
expect(entity.label.horizontalOrigin.getValue(validTime)).toEqual(HorizontalOrigin.LEFT);
expect(entity.label.verticalOrigin.getValue(validTime)).toEqual(VerticalOrigin.CENTER);
expect(entity.label.eyeOffset.getValue(validTime)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(entity.label.pixelOffset.getValue(validTime)).toEqual(new Cartesian2(4.0, 5.0));
expect(entity.label.scale.getValue(validTime)).toEqual(labelPacket.label.scale);
expect(entity.label.show.getValue(validTime)).toEqual(labelPacket.label.show);
expect(entity.label.text.getValue(invalidTime)).toBeUndefined();
expect(entity.label.font.getValue(invalidTime)).toBeUndefined();
expect(entity.label.style.getValue(invalidTime)).toBeUndefined();
expect(entity.label.fillColor.getValue(invalidTime)).toBeUndefined();
expect(entity.label.outlineColor.getValue(invalidTime)).toBeUndefined();
expect(entity.label.outlineWidth.getValue(invalidTime)).toBeUndefined();
expect(entity.label.horizontalOrigin.getValue(invalidTime)).toBeUndefined();
expect(entity.label.verticalOrigin.getValue(invalidTime)).toBeUndefined();
expect(entity.label.eyeOffset.getValue(invalidTime)).toBeUndefined();
expect(entity.label.pixelOffset.getValue(invalidTime)).toBeUndefined();
expect(entity.label.scale.getValue(invalidTime)).toBeUndefined();
expect(entity.label.show.getValue(invalidTime)).toBeUndefined();
});
it('can handle sampled label pixelOffset.', function() {
var epoch = JulianDate.now();
var labelPacket = {
label : {
pixelOffset : {
epoch : JulianDate.toIso8601(epoch),
cartesian2 : [0, 1, 2, 1, 3, 4]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(labelPacket));
var entity = dataSource.entities.values[0];
expect(entity.label).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
expect(entity.label.pixelOffset.getValue(date1)).toEqual(new Cartesian2(1.0, 2.0));
expect(entity.label.pixelOffset.getValue(date2)).toEqual(new Cartesian2(3.0, 4.0));
});
it('CZML Position works.', function() {
var packet = {
position : {
cartesian : [1.0, 2.0, 3.0]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.position.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
});
it('CZML Orientation works.', function() {
var packet = {
orientation : {
unitQuaternion : [0.0, 0.0, 0.0, 1.0]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.orientation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Quaternion(0.0, 0.0, 0.0, 1.0));
});
it('CZML Orientation is normalized on load.', function() {
var packet = {
orientation : {
unitQuaternion : [0.0, 0.0, 0.7071067, 0.7071067]
}
};
var expected = new Quaternion(0.0, 0.0, 0.7071067, 0.7071067);
Quaternion.normalize(expected, expected);
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.orientation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expected);
});
it('CZML Orientation is normalized on load.', function() {
var time1 = '2000-01-01T00:00:00Z';
var time2 = '2000-01-01T00:00:01Z';
var packet = {
orientation : {
unitQuaternion : [time1, 0.0, 0.0, 0.7071067, 0.7071067, time2, 0.7071067, 0.7071067, 0.0, 0.0]
}
};
var expected1 = new Quaternion(0.0, 0.0, 0.7071067, 0.7071067);
Quaternion.normalize(expected1, expected1);
var expected2 = new Quaternion(0.7071067, 0.7071067, 0.0, 0.0);
Quaternion.normalize(expected2, expected2);
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.orientation.getValue(JulianDate.fromIso8601(time1))).toEqual(expected1);
expect(entity.orientation.getValue(JulianDate.fromIso8601(time2))).toEqual(expected2);
});
it('positions work with cartesians.', function() {
var expectedResult = [new Cartesian3(1.0, 2.0, 3.0), new Cartesian3(5.0, 6.0, 7.0)];
var packet = {
polyline : {
positions : {
cartesian : [expectedResult[0].x, expectedResult[0].y, expectedResult[0].z, expectedResult[1].x, expectedResult[1].y, expectedResult[1].z]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.polyline.positions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedResult);
});
it('positions work with cartographicRadians.', function() {
var input = [new Cartographic(1.0, 2.0, 4.0), new Cartographic(5.0, 6.0, 7.0)];
var expectedResult = Ellipsoid.WGS84.cartographicArrayToCartesianArray(input);
var packet = {
polyline : {
positions : {
cartographicRadians : [input[0].longitude, input[0].latitude, input[0].height, input[1].longitude, input[1].latitude, input[1].height]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.polyline.positions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedResult);
});
it('positions work with cartographicDegrees.', function() {
var expectedResult = Cartesian3.fromDegreesArrayHeights([
1.0, 2.0, 3.0,
5.0, 6.0, 7.0
]);
var packet = {
polyline : {
positions : {
cartographicDegrees : [1.0, 2.0, 3.0, 5.0, 6.0, 7.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.polyline.positions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedResult);
});
it('CZML ViewFrom works.', function() {
var packet = {
viewFrom : {
cartesian : [1.0, 2.0, 3.0]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.viewFrom.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
});
it('CZML description works.', function() {
var packet = {
description : 'this is a description'
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.description.getValue(Iso8601.MINIMUM_VALUE)).toEqual(packet.description);
});
it('CZML Availability works with a single interval.', function() {
var packet1 = {
id : 'testObject',
availability : '2000-01-01/2001-01-01'
};
var dataSource = new CzmlDataSource();
dataSource.process(makePacket(packet1));
var entity = dataSource.entities.values[0];
var interval = TimeInterval.fromIso8601({
iso8601 : packet1.availability
});
expect(entity.availability.length).toEqual(1);
expect(entity.availability.get(0)).toEqual(interval);
var packet2 = {
id : 'testObject',
availability : '2000-02-02/2001-02-02'
};
dataSource.process(packet2);
interval = TimeInterval.fromIso8601({
iso8601 : packet2.availability
});
expect(entity.availability.length).toEqual(1);
expect(entity.availability.get(0)).toEqual(interval);
});
it('CZML Availability works with multiple intervals.', function() {
var packet1 = {
id : 'testObject',
availability : ['2000-01-01/2001-01-01', '2002-01-01/2003-01-01']
};
var dataSource = new CzmlDataSource();
dataSource.process(makePacket(packet1));
var entity = dataSource.entities.values[0];
var interval1 = TimeInterval.fromIso8601({
iso8601 : packet1.availability[0]
});
var interval2 = TimeInterval.fromIso8601({
iso8601 : packet1.availability[1]
});
expect(entity.availability.length).toEqual(2);
expect(entity.availability.get(0)).toEqual(interval1);
expect(entity.availability.get(1)).toEqual(interval2);
var packet2 = {
id : 'testObject',
availability : ['2003-01-01/2004-01-01', '2005-01-01/2006-01-01']
};
dataSource.process(packet2);
interval1 = TimeInterval.fromIso8601({
iso8601 : packet2.availability[0]
});
interval2 = TimeInterval.fromIso8601({
iso8601 : packet2.availability[1]
});
expect(entity.availability.length).toEqual(2);
expect(entity.availability.get(0)).toEqual(interval1);
expect(entity.availability.get(1)).toEqual(interval2);
});
it('CZML adds data for infinite path.', function() {
var pathPacket = {
path : {
material : {
polylineOutline : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0
}
},
width : 1.0,
resolution : 23.0,
leadTime : 2.0,
trailTime : 3.0,
show : true
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(pathPacket));
var entity = dataSource.entities.values[0];
expect(entity.path).toBeDefined();
expect(entity.path.material.color.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.path.width.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pathPacket.path.width);
expect(entity.path.resolution.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pathPacket.path.resolution);
expect(entity.path.material.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.path.material.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(1.0);
expect(entity.path.leadTime.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pathPacket.path.leadTime);
expect(entity.path.trailTime.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pathPacket.path.trailTime);
expect(entity.path.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
});
it('CZML adds data for constrained path.', function() {
var pathPacket = {
path : {
interval : '2000-01-01/2001-01-01',
material : {
polylineOutline : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0
}
},
width : 1.0,
resolution : 23.0,
leadTime : 2.0,
trailTime : 3.0,
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : pathPacket.path.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(pathPacket));
var entity = dataSource.entities.values[0];
expect(entity.path).toBeDefined();
expect(entity.path.width.getValue(validTime)).toEqual(pathPacket.path.width);
expect(entity.path.resolution.getValue(validTime)).toEqual(pathPacket.path.resolution);
expect(entity.path.leadTime.getValue(validTime)).toEqual(pathPacket.path.leadTime);
expect(entity.path.trailTime.getValue(validTime)).toEqual(pathPacket.path.trailTime);
expect(entity.path.show.getValue(validTime)).toEqual(true);
expect(entity.path.material.getValue(validTime).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.path.material.getValue(validTime).outlineColor).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.path.material.getValue(validTime).outlineWidth).toEqual(1.0);
expect(entity.path.material.getValue(invalidTime)).toBeUndefined();
expect(entity.path.width.getValue(invalidTime)).toBeUndefined();
expect(entity.path.leadTime.getValue(invalidTime)).toBeUndefined();
expect(entity.path.trailTime.getValue(invalidTime)).toBeUndefined();
expect(entity.path.show.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite point.', function() {
var pointPacket = {
point : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
pixelSize : 1.0,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0,
show : true,
scaleByDistance : {
nearFarScalar : [1.0, 2.0, 10000.0, 3.0]
},
translucencyByDistance : {
nearFarScalar : [1.0, 1.0, 10000.0, 0.0]
},
heightReference : 'CLAMP_TO_GROUND'
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(pointPacket));
var entity = dataSource.entities.values[0];
expect(entity.point).toBeDefined();
expect(entity.point.color.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.point.pixelSize.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pointPacket.point.pixelSize);
expect(entity.point.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.point.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(pointPacket.point.outlineWidth);
expect(entity.point.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.point.scaleByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 2.0, 10000.0, 3.0));
expect(entity.point.translucencyByDistance.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new NearFarScalar(1.0, 1.0, 10000.0, 0.0));
expect(entity.point.heightReference.getValue(Iso8601.MINIMUM_VALUE)).toEqual(HeightReference.CLAMP_TO_GROUND);
});
it('CZML adds data for constrained point.', function() {
var pointPacket = {
point : {
interval : '2000-01-01/2001-01-01',
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
pixelSize : 1.0,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0,
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : pointPacket.point.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(pointPacket));
var entity = dataSource.entities.values[0];
expect(entity.point).toBeDefined();
expect(entity.point.color.getValue(validTime)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.point.pixelSize.getValue(validTime)).toEqual(pointPacket.point.pixelSize);
expect(entity.point.outlineColor.getValue(validTime)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.point.outlineWidth.getValue(validTime)).toEqual(pointPacket.point.outlineWidth);
expect(entity.point.show.getValue(validTime)).toEqual(true);
expect(entity.point.color.getValue(invalidTime)).toBeUndefined();
expect(entity.point.pixelSize.getValue(invalidTime)).toBeUndefined();
expect(entity.point.outlineColor.getValue(invalidTime)).toBeUndefined();
expect(entity.point.outlineWidth.getValue(invalidTime)).toBeUndefined();
expect(entity.point.show.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite polygon.', function() {
var polygonPacket = {
polygon : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
},
height : 1,
extrudedHeight : 2,
granularity : 3,
stRotation : 4,
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6,
closeTop : false,
closeBottom : false
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(polygonPacket));
var entity = dataSource.entities.values[0];
expect(entity.polygon).toBeDefined();
expect(entity.polygon.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.polygon.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.polygon.height.getValue(Iso8601.MINIMUM_VALUE)).toEqual(1);
expect(entity.polygon.extrudedHeight.getValue(Iso8601.MINIMUM_VALUE)).toEqual(2);
expect(entity.polygon.granularity.getValue(Iso8601.MINIMUM_VALUE)).toEqual(3);
expect(entity.polygon.stRotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(4);
expect(entity.polygon.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.polygon.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.polygon.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
expect(entity.polygon.closeTop.getValue(Iso8601.MINIMUM_VALUE)).toEqual(false);
expect(entity.polygon.closeBottom.getValue(Iso8601.MINIMUM_VALUE)).toEqual(false);
});
it('CZML adds data for constrained polygon.', function() {
var polygonPacket = {
polygon : {
interval : '2000-01-01/2001-01-01',
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
},
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : polygonPacket.polygon.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(polygonPacket));
var entity = dataSource.entities.values[0];
expect(entity.polygon).toBeDefined();
expect(entity.polygon.material.getValue(validTime).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.polygon.show.getValue(validTime)).toEqual(true);
expect(entity.polygon.material.getValue(invalidTime)).toBeUndefined();
expect(entity.polygon.show.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite polyline.', function() {
var polylinePacket = {
polyline : {
material : {
polylineOutline : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0
}
},
width : 1.0,
show : true
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(polylinePacket));
var entity = dataSource.entities.values[0];
expect(entity.polyline).toBeDefined();
expect(entity.polyline.material.color.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.polyline.width.getValue(Iso8601.MINIMUM_VALUE)).toEqual(polylinePacket.polyline.width);
expect(entity.polyline.material.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.polyline.material.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(1.0);
expect(entity.polyline.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
});
it('CZML adds data for constrained polyline.', function() {
var polylinePacket = {
polyline : {
interval : '2000-01-01/2001-01-01',
material : {
polylineOutline : {
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
},
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 1.0
}
},
width : 1.0,
show : true
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : polylinePacket.polyline.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(polylinePacket));
var entity = dataSource.entities.values[0];
expect(entity.polyline).toBeDefined();
expect(entity.polyline.material.getValue(validTime).color).toEqual(new Color(0.1, 0.1, 0.1, 0.1));
expect(entity.polyline.width.getValue(validTime)).toEqual(polylinePacket.polyline.width);
expect(entity.polyline.material.getValue(validTime).outlineColor).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.polyline.material.getValue(validTime).outlineWidth).toEqual(1.0);
expect(entity.polyline.show.getValue(validTime)).toEqual(true);
expect(entity.polyline.material.getValue(invalidTime)).toBeUndefined();
expect(entity.polyline.width.getValue(invalidTime)).toBeUndefined();
expect(entity.polyline.show.getValue(invalidTime)).toBeUndefined();
});
it('CZML adds data for infinite model.', function() {
var modelPacket = {
model : {
show : true,
scale : 3.0,
minimumPixelSize : 5.0,
maximumScale : 4.0,
gltf : './Data/Models/Box/CesiumBoxTest.gltf',
incrementallyLoadTextures : true,
castShadows : true,
receiveShadows : true,
heightReference: 'CLAMP_TO_GROUND',
nodeTransformations : {
Mesh : {
scale : {
cartesian : [1.0, 2.0, 3.0]
},
translation : {
cartesian : [4.0, 5.0, 6.0]
},
rotation : {
unitQuaternion : [0.0, 0.707, 0.0, 0.707]
}
}
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(modelPacket));
var entity = dataSource.entities.values[0];
expect(entity.model).toBeDefined();
expect(entity.model.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.model.scale.getValue(Iso8601.MINIMUM_VALUE)).toEqual(3.0);
expect(entity.model.minimumPixelSize.getValue(Iso8601.MINIMUM_VALUE)).toEqual(5.0);
expect(entity.model.maximumScale.getValue(Iso8601.MINIMUM_VALUE)).toEqual(4.0);
expect(entity.model.uri.getValue(Iso8601.MINIMUM_VALUE)).toEqual('./Data/Models/Box/CesiumBoxTest.gltf');
expect(entity.model.incrementallyLoadTextures.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.model.castShadows.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.model.receiveShadows.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.model.heightReference.getValue(Iso8601.MINIMUM_VALUE)).toEqual(HeightReference.CLAMP_TO_GROUND);
var nodeTransform = entity.model.nodeTransformations.getValue(Iso8601.MINIMUM_VALUE).Mesh;
expect(nodeTransform).toBeDefined();
expect(nodeTransform.scale).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(nodeTransform.translation).toEqual(new Cartesian3(4.0, 5.0, 6.0));
var expectedRotation = new Quaternion(0.0, 0.707, 0.0, 0.707);
Quaternion.normalize(expectedRotation, expectedRotation);
expect(nodeTransform.rotation).toEqual(expectedRotation);
expect(entity.model.nodeTransformations.Mesh.scale.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(entity.model.nodeTransformations.Mesh.translation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(4.0, 5.0, 6.0));
expect(entity.model.nodeTransformations.Mesh.rotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedRotation);
});
it('CZML adds data for constrained model.', function() {
var modelPacket = {
model : {
interval : '2000-01-01/2001-01-01',
show : true,
scale : 3.0,
minimumPixelSize : 5.0,
gltf : './Data/Models/Box/CesiumBoxTest.gltf',
incrementallyLoadTextures : true,
castShadows : true,
receiveShadows : true,
nodeTransformations : {
Mesh : {
scale : {
cartesian : [1.0, 2.0, 3.0]
},
translation : {
cartesian : [4.0, 5.0, 6.0]
},
rotation : {
unitQuaternion : [0.0, 0.707, 0.0, 0.707]
}
}
}
}
};
var validTime = TimeInterval.fromIso8601({
iso8601 : modelPacket.model.interval
}).start;
var invalidTime = JulianDate.addSeconds(validTime, -1, new JulianDate());
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(modelPacket));
var entity = dataSource.entities.values[0];
expect(entity.model).toBeDefined();
expect(entity.model.show.getValue(validTime)).toEqual(true);
expect(entity.model.scale.getValue(validTime)).toEqual(3.0);
expect(entity.model.minimumPixelSize.getValue(validTime)).toEqual(5.0);
expect(entity.model.uri.getValue(validTime)).toEqual('./Data/Models/Box/CesiumBoxTest.gltf');
expect(entity.model.incrementallyLoadTextures.getValue(validTime)).toEqual(true);
expect(entity.model.castShadows.getValue(validTime)).toEqual(true);
expect(entity.model.receiveShadows.getValue(validTime)).toEqual(true);
var nodeTransform = entity.model.nodeTransformations.getValue(validTime).Mesh;
expect(nodeTransform).toBeDefined();
expect(nodeTransform.scale).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(nodeTransform.translation).toEqual(new Cartesian3(4.0, 5.0, 6.0));
var expectedRotation = new Quaternion(0.0, 0.707, 0.0, 0.707);
Quaternion.normalize(expectedRotation, expectedRotation);
expect(nodeTransform.rotation).toEqual(expectedRotation);
expect(entity.model.nodeTransformations.Mesh.scale.getValue(validTime)).toEqual(new Cartesian3(1.0, 2.0, 3.0));
expect(entity.model.nodeTransformations.Mesh.translation.getValue(validTime)).toEqual(new Cartesian3(4.0, 5.0, 6.0));
expect(entity.model.nodeTransformations.Mesh.rotation.getValue(validTime)).toEqual(expectedRotation);
expect(entity.model.show.getValue(invalidTime)).toBeUndefined();
expect(entity.model.scale.getValue(invalidTime)).toBeUndefined();
expect(entity.model.minimumPixelSize.getValue(invalidTime)).toBeUndefined();
expect(entity.model.uri.getValue(invalidTime)).toBeUndefined();
expect(entity.model.incrementallyLoadTextures.getValue(invalidTime)).toBeUndefined();
expect(entity.model.castShadows.getValue(invalidTime)).toBeUndefined();
expect(entity.model.receiveShadows.getValue(invalidTime)).toBeUndefined();
expect(entity.model.nodeTransformations.Mesh.getValue(invalidTime)).toEqual(new TranslationRotationScale());
expect(entity.model.nodeTransformations.Mesh.scale.getValue(invalidTime)).toBeUndefined();
expect(entity.model.nodeTransformations.Mesh.translation.getValue(invalidTime)).toBeUndefined();
expect(entity.model.nodeTransformations.Mesh.rotation.getValue(invalidTime)).toBeUndefined();
});
it('processCzml deletes an existing object.', function() {
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(staticCzml));
var objects = dataSource.entities.values;
expect(objects.length).toEqual(1);
dataSource.load(makePacket(czmlDelete));
expect(objects.length).toEqual(0);
});
it('Processes parent property.', function() {
var parentChildCzml = [{
id : 'document',
version : '1.0'
}, {
'id' : 'parent'
}, {
'id' : 'child',
'parent' : 'parent'
}];
var dataSource = new CzmlDataSource();
dataSource.load(parentChildCzml);
var objects = dataSource.entities;
var parent = objects.getById('parent');
expect(parent.parent).toBeUndefined();
var child = objects.getById('child');
expect(child.parent).toBe(parent);
});
it('Processes parent property out of order.', function() {
var parentChildCzml = [{
id : 'document',
version : '1.0'
}, {
id : 'child',
parent : 'parent'
}, {
id : 'child2',
parent : 'parent'
}, {
id : 'grandparent'
}, {
id : 'grandparent2'
}, {
id : 'parent',
parent : 'grandparent'
}, {
id : 'parent2',
parent : 'grandparent'
}];
var dataSource = new CzmlDataSource();
dataSource.load(parentChildCzml);
var objects = dataSource.entities;
var grandparent = objects.getById('grandparent');
expect(grandparent.parent).toBeUndefined();
var grandparent2 = objects.getById('grandparent');
expect(grandparent2.parent).toBeUndefined();
var parent = objects.getById('parent');
expect(parent.parent).toBe(grandparent);
var parent2 = objects.getById('parent2');
expect(parent2.parent).toBe(grandparent);
var child = objects.getById('child');
expect(child.parent).toBe(parent);
var child2 = objects.getById('child2');
expect(child2.parent).toBe(parent);
});
it('Processes JulianDate packets.', function() {
var date = JulianDate.fromIso8601('2000-01-01');
var object = {};
CzmlDataSource.processPacketData(JulianDate, object, 'simpleDate', JulianDate.toIso8601(date));
expect(object.simpleDate).toBeDefined();
expect(object.simpleDate.getValue()).toEqual(date);
CzmlDataSource.processPacketData(JulianDate, object, 'objDate', {
date : JulianDate.toIso8601(date)
});
expect(object.objDate).toBeDefined();
expect(object.objDate.getValue()).toEqual(date);
});
it('Processes array packets.', function() {
var arrayPacket = {
array : [1, 2, 3, 4, 5]
};
var object = {};
CzmlDataSource.processPacketData(Array, object, 'arrayData', arrayPacket);
expect(object.arrayData).toBeDefined();
expect(object.arrayData.getValue()).toEqual(arrayPacket.array);
});
it('CZML load suspends events.', function() {
var packets = [{
id : 'document',
version : '1.0'
}, {
point : {
show : true,
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
}, {
point : {
show : false,
color : {
rgbaf : [0.1, 0.1, 0.1, 0.1]
}
}
}];
var spy = jasmine.createSpy('changedEvent');
var dataSource = new CzmlDataSource();
dataSource.entities.collectionChanged.addEventListener(spy);
dataSource.load(packets);
expect(spy.calls.count()).toEqual(1);
});
it('CZML materials work with composite interval', function() {
var before = JulianDate.fromIso8601('2012-03-15T09:23:59Z');
var solid = JulianDate.fromIso8601('2012-03-15T10:00:00Z');
var grid1 = JulianDate.fromIso8601('2012-03-15T11:00:00Z');
var grid2 = JulianDate.fromIso8601('2012-03-15T12:00:00Z');
var after = JulianDate.fromIso8601('2012-03-15T12:00:01Z');
var packet = {
polygon : {
material : [{
interval : '2012-03-15T10:00:00Z/2012-03-15T11:00:00Z',
interpolationAlgorithm : 'LINEAR',
interpolationDegree : 1,
epoch : '2012-03-15T10:00:00Z',
solidColor : {
color : {
rgba : [240, 0, 0, 0]
}
}
}, {
interval : '2012-03-15T11:00:00Z/2012-03-15T12:00:00Z',
interpolationAlgorithm : 'LINEAR',
interpolationDegree : 1,
epoch : '2012-03-15T11:00:00Z',
grid : {
color : {
rgba : [240, 255, 255, 255]
},
cellAlpha : 0,
lineCount : {
cartesian2 : [36, 9]
},
lineThickness : {
cartesian2 : [1, 1]
},
lineOffset : {
cartesian2 : [0.5, 0.5]
}
}
}]
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.values[0];
expect(entity.polygon.material.getType(solid)).toBe('Color');
expect(entity.polygon.material.getType(grid1)).toBe('Grid');
expect(entity.polygon.material.getType(grid2)).toBe('Grid');
expect(entity.polygon.material.getType(before)).toBeUndefined();
expect(entity.polygon.material.getType(after)).toBeUndefined();
});
it('CZML adds data for rectangle.', function() {
var rectanglePacket = {
rectangle : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
},
coordinates : {
wsen : [0, 1, 2, 3]
},
height : 1,
extrudedHeight : 2,
granularity : 3,
rotation : 4,
stRotation : 5,
closeBottom : true,
closeTop : false,
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6
}
};
var czmlRectangle = rectanglePacket.rectangle;
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(rectanglePacket));
var entity = dataSource.entities.values[0];
expect(entity.rectangle).toBeDefined();
expect(entity.rectangle.coordinates.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Rectangle(0, 1, 2, 3));
expect(entity.rectangle.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.rectangle.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.show);
expect(entity.rectangle.height.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.height);
expect(entity.rectangle.extrudedHeight.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.extrudedHeight);
expect(entity.rectangle.granularity.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.granularity);
expect(entity.rectangle.rotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.rotation);
expect(entity.rectangle.stRotation.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.stRotation);
expect(entity.rectangle.closeBottom.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.closeBottom);
expect(entity.rectangle.closeTop.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.closeTop);
expect(entity.rectangle.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.rectangle.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.rectangle.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
});
it('can handle constant rectangle coordinates in degrees.', function() {
var rectanglePacket = {
rectangle : {
coordinates : {
wsenDegrees : [0, 1, 2, 3]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(rectanglePacket));
var entity = dataSource.entities.values[0];
expect(entity.rectangle.coordinates.getValue(Iso8601.MINIMUM_VALUE)).toEqual(Rectangle.fromDegrees(0, 1, 2, 3));
});
it('can handle sampled rectangle coordinates.', function() {
var epoch = JulianDate.now();
var rectanglePacket = {
rectangle : {
coordinates : {
epoch : JulianDate.toIso8601(epoch),
wsen : [0.0, 1.0, 2.0, 3.0, 4.0,
1.0, 3.0, 4.0, 5.0, 6.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(rectanglePacket));
var entity = dataSource.entities.values[0];
expect(entity.rectangle).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 0.5, new JulianDate());
var date3 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
expect(entity.rectangle.coordinates.getValue(date1)).toEqual(new Rectangle(1.0, 2.0, 3.0, 4.0));
expect(entity.rectangle.coordinates.getValue(date2)).toEqual(new Rectangle(2.0, 3.0, 4.0, 5.0));
expect(entity.rectangle.coordinates.getValue(date3)).toEqual(new Rectangle(3.0, 4.0, 5.0, 6.0));
});
it('can handle sampled rectangle coordinates in degrees.', function() {
var epoch = JulianDate.now();
var rectanglePacket = {
rectangle : {
coordinates : {
epoch : JulianDate.toIso8601(epoch),
wsenDegrees : [0.0, 1.0, 2.0, 3.0, 4.0,
1.0, 3.0, 4.0, 5.0, 6.0]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(rectanglePacket));
var entity = dataSource.entities.values[0];
expect(entity.rectangle).toBeDefined();
var date1 = epoch;
var date2 = JulianDate.addSeconds(epoch, 0.5, new JulianDate());
var date3 = JulianDate.addSeconds(epoch, 1.0, new JulianDate());
expect(entity.rectangle.coordinates.getValue(date1)).toEqual(Rectangle.fromDegrees(1.0, 2.0, 3.0, 4.0));
expect(entity.rectangle.coordinates.getValue(date2)).toEqualEpsilon(Rectangle.fromDegrees(2.0, 3.0, 4.0, 5.0), CesiumMath.EPSILON15);
expect(entity.rectangle.coordinates.getValue(date3)).toEqual(Rectangle.fromDegrees(3.0, 4.0, 5.0, 6.0));
});
it('CZML adds data for wall.', function() {
var wallPacket = {
wall : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
},
granularity : 3,
minimumHeights : {
array : [1, 2, 3]
},
maximumHeights : {
array : [4, 5, 6]
},
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6
}
};
var czmlRectangle = wallPacket.wall;
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(wallPacket));
var entity = dataSource.entities.values[0];
expect(entity.wall).toBeDefined();
expect(entity.wall.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.wall.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.show);
expect(entity.wall.granularity.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.granularity);
expect(entity.wall.minimumHeights.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.minimumHeights.array);
expect(entity.wall.maximumHeights.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlRectangle.maximumHeights.array);
expect(entity.wall.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.wall.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.wall.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
});
it('CZML adds data for wall with minimumHeights as references.', function() {
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'obj1',
billboard : {
scale : 1.0
}
}, {
id : 'obj2',
billboard : {
scale : 4.0
}
}, {
id : 'wall',
wall : {
minimumHeights : {
references : ['obj1#billboard.scale', 'obj2#billboard.scale']
},
maximumHeights : {
references : ['obj2#billboard.scale', 'obj1#billboard.scale']
}
}
}];
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var entity = dataSource.entities.getById('wall');
expect(entity.wall).toBeDefined();
expect(entity.wall.minimumHeights.getValue(Iso8601.MINIMUM_VALUE)).toEqual([packets[1].billboard.scale, packets[2].billboard.scale]);
expect(entity.wall.maximumHeights.getValue(Iso8601.MINIMUM_VALUE)).toEqual([packets[2].billboard.scale, packets[1].billboard.scale]);
});
it('CZML adds data for box.', function() {
var boxPacket = {
box : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
},
dimensions : {
cartesian : [1, 2, 3]
},
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(boxPacket));
var entity = dataSource.entities.values[0];
expect(entity.box).toBeDefined();
expect(entity.box.dimensions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Cartesian3(1, 2, 3));
expect(entity.box.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.box.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.box.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.box.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.box.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
});
it('CZML adds data for cylinder.', function() {
var cylinderPacket = {
cylinder : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
},
length : 5,
topRadius: 6,
bottomRadius: 7,
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6,
numberOfVerticalLines : 15,
slices : 100
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(cylinderPacket));
var entity = dataSource.entities.values[0];
expect(entity.cylinder).toBeDefined();
expect(entity.cylinder.length.getValue(Iso8601.MINIMUM_VALUE)).toEqual(5);
expect(entity.cylinder.topRadius.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
expect(entity.cylinder.bottomRadius.getValue(Iso8601.MINIMUM_VALUE)).toEqual(7);
expect(entity.cylinder.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.cylinder.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.cylinder.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.cylinder.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.cylinder.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
expect(entity.cylinder.numberOfVerticalLines.getValue(Iso8601.MINIMUM_VALUE)).toEqual(15);
expect(entity.cylinder.slices.getValue(Iso8601.MINIMUM_VALUE)).toEqual(100);
});
it('CZML adds data for corridor.', function() {
var expectedResult = [new Cartesian3(1.0, 2.0, 3.0), new Cartesian3(5.0, 6.0, 7.0)];
var corridorPacket = {
corridor : {
material : {
solidColor : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
},
positions : {
cartesian : [expectedResult[0].x, expectedResult[0].y, expectedResult[0].z, expectedResult[1].x, expectedResult[1].y, expectedResult[1].z]
},
cornerType : "MITERED",
extrudedHeight : 2,
granularity : 3,
height : 4,
width: 9,
show : true,
outline : true,
outlineColor : {
rgbaf : [0.2, 0.2, 0.2, 0.2]
},
outlineWidth : 6
}
};
var czmlCorridor = corridorPacket.corridor;
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(corridorPacket));
var entity = dataSource.entities.values[0];
expect(entity.corridor).toBeDefined();
expect(entity.corridor.positions.getValue(Iso8601.MINIMUM_VALUE)).toEqual(expectedResult);
expect(entity.corridor.material.getValue(Iso8601.MINIMUM_VALUE).color).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.corridor.show.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlCorridor.show);
expect(entity.corridor.height.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlCorridor.height);
expect(entity.corridor.width.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlCorridor.width);
expect(entity.corridor.cornerType.getValue(Iso8601.MINIMUM_VALUE)).toEqual(CornerType.MITERED);
expect(entity.corridor.extrudedHeight.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlCorridor.extrudedHeight);
expect(entity.corridor.granularity.getValue(Iso8601.MINIMUM_VALUE)).toEqual(czmlCorridor.granularity);
expect(entity.corridor.outline.getValue(Iso8601.MINIMUM_VALUE)).toEqual(true);
expect(entity.corridor.outlineColor.getValue(Iso8601.MINIMUM_VALUE)).toEqual(new Color(0.2, 0.2, 0.2, 0.2));
expect(entity.corridor.outlineWidth.getValue(Iso8601.MINIMUM_VALUE)).toEqual(6);
});
it('Has entity collection with link to data source', function() {
var dataSource = new CzmlDataSource();
dataSource.load(nameCzml);
var entityCollection = dataSource.entities;
expect(entityCollection.owner).toEqual(dataSource);
});
it('Has entity with link to entity collection', function() {
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(staticCzml));
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.entityCollection).toEqual(entityCollection);
});
it('Can use constant reference properties', function() {
var time = JulianDate.now();
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'targetId',
point : {
pixelSize : 1.0
}
}, {
id : 'referenceId',
point : {
pixelSize : {
reference : 'targetId#point.pixelSize'
}
}
}];
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var targetEntity = dataSource.entities.getById('targetId');
var referenceObject = dataSource.entities.getById('referenceId');
expect(referenceObject.point.pixelSize instanceof ReferenceProperty).toBe(true);
expect(targetEntity.point.pixelSize.getValue(time)).toEqual(referenceObject.point.pixelSize.getValue(time));
});
it('Can use interval reference properties', function() {
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'targetId',
point : {
pixelSize : 1.0
}
}, {
id : 'targetId2',
point : {
pixelSize : 2.0
}
}, {
id : 'referenceId',
point : {
pixelSize : [{
interval : '2012/2013',
reference : 'targetId#point.pixelSize'
}, {
interval : '2013/2014',
reference : 'targetId2#point.pixelSize'
}]
}
}];
var time1 = JulianDate.fromIso8601('2012');
var time2 = JulianDate.fromIso8601('2014');
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var targetEntity = dataSource.entities.getById('targetId');
var targetEntity2 = dataSource.entities.getById('targetId2');
var referenceObject = dataSource.entities.getById('referenceId');
expect(targetEntity.point.pixelSize.getValue(time1)).toEqual(referenceObject.point.pixelSize.getValue(time1));
expect(targetEntity2.point.pixelSize.getValue(time2)).toEqual(referenceObject.point.pixelSize.getValue(time2));
});
it('Can use constant reference properties for position', function() {
var time = JulianDate.now();
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'targetId',
position : {
cartesian : [1.0, 2.0, 3.0]
}
}, {
id : 'referenceId',
position : {
reference : 'targetId#position'
}
}];
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var targetEntity = dataSource.entities.getById('targetId');
var referenceObject = dataSource.entities.getById('referenceId');
expect(referenceObject.position instanceof ReferenceProperty).toBe(true);
expect(targetEntity.position.getValue(time)).toEqual(referenceObject.position.getValue(time));
});
it('Can use interval reference properties for positions', function() {
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'targetId',
position : {
cartesian : [1.0, 2.0, 3.0]
}
}, {
id : 'targetId2',
position : {
cartesian : [4.0, 5.0, 6.0]
}
}, {
id : 'referenceId',
position : [{
interval : '2012/2013',
reference : 'targetId#position'
}, {
interval : '2013/2014',
reference : 'targetId2#position'
}]
}];
var time1 = JulianDate.fromIso8601('2012');
var time2 = JulianDate.fromIso8601('2014');
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var targetEntity = dataSource.entities.getById('targetId');
var targetEntity2 = dataSource.entities.getById('targetId2');
var referenceObject = dataSource.entities.getById('referenceId');
expect(targetEntity.position.getValue(time1)).toEqual(referenceObject.position.getValue(time1));
expect(targetEntity2.position.getValue(time2)).toEqual(referenceObject.position.getValue(time2));
});
it('Can reference properties before they exist.', function() {
var time = JulianDate.now();
var packets = [{
id : 'document',
version : '1.0'
}, {
id : 'referenceId',
point : {
pixelSize : {
reference : 'targetId#point.pixelSize'
}
}
}, {
id : 'targetId',
point : {
pixelSize : 1.0
}
}];
var dataSource = new CzmlDataSource();
dataSource.load(packets);
var targetEntity = dataSource.entities.getById('targetId');
var referenceObject = dataSource.entities.getById('referenceId');
expect(referenceObject.point.pixelSize instanceof ReferenceProperty).toBe(true);
expect(targetEntity.point.pixelSize.getValue(time)).toEqual(referenceObject.point.pixelSize.getValue(time));
});
it('Can reference local properties.', function() {
var time = JulianDate.now();
var packet = {
id : 'testObject',
point : {
pixelSize : 1.0,
outlineWidth : {
reference : '#point.pixelSize'
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var targetEntity = dataSource.entities.getById('testObject');
expect(targetEntity.point.outlineWidth instanceof ReferenceProperty).toBe(true);
expect(targetEntity.point.outlineWidth.getValue(time)).toEqual(targetEntity.point.pixelSize.getValue(time));
});
it('Polyline glow.', function() {
var packet = {
id : 'polylineGlow',
polyline : {
material : {
polylineGlow : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
},
glowPower : 0.75
}
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.getById('polylineGlow');
expect(entity.polyline.material.color.getValue()).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
expect(entity.polyline.material.glowPower.getValue()).toEqual(0.75);
});
it('Polyline arrow.', function() {
var packet = {
id : 'polylineArrow',
polyline : {
material : {
polylineArrow : {
color : {
rgbaf : [0.1, 0.2, 0.3, 0.4]
}
}
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.getById('polylineArrow');
expect(entity.polyline.material.color.getValue()).toEqual(new Color(0.1, 0.2, 0.3, 0.4));
});
it('Processes extrapolation options', function() {
var packet = {
id : 'point',
position : {
forwardExtrapolationType : "HOLD",
forwardExtrapolationDuration : 2.0,
backwardExtrapolationType : "NONE",
backwardExtrapolationDuration : 1.0,
cartesian : ['2012', 0, 0, 0]
},
point : {
color : {
forwardExtrapolationType : "NONE",
forwardExtrapolationDuration : 1.0,
backwardExtrapolationType : "HOLD",
backwardExtrapolationDuration : 2.0,
rgbaf : ['2012', 0.1, 0.2, 0.3, 0.4]
}
}
};
var dataSource = new CzmlDataSource();
dataSource.load(makePacket(packet));
var entity = dataSource.entities.getById('point');
var color = entity.point.color;
expect(color.forwardExtrapolationType).toEqual(ExtrapolationType.NONE);
expect(color.forwardExtrapolationDuration).toEqual(1.0);
expect(color.backwardExtrapolationType).toEqual(ExtrapolationType.HOLD);
expect(color.backwardExtrapolationDuration).toEqual(2.0);
var position = entity.position;
expect(position.forwardExtrapolationType).toEqual(ExtrapolationType.HOLD);
expect(position.forwardExtrapolationDuration).toEqual(2.0);
expect(position.backwardExtrapolationType).toEqual(ExtrapolationType.NONE);
expect(position.backwardExtrapolationDuration).toEqual(1.0);
});
it('rejects if first document packet lacks version information', function() {
return CzmlDataSource.load({
id : 'document'
}).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toEqual('CZML version information invalid. It is expected to be a property on the document object in the <Major>.<Minor> version format.');
});
});
it('rejects if first packet is not document', function() {
return CzmlDataSource.load({
id : 'someId'
}).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toEqual('The first CZML packet is required to be the document object.');
});
});
it('rejects if document packet contains bad version', function() {
return CzmlDataSource.load({
id : 'document'
}).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('CZML version information invalid. It is expected to be a property on the document object in the <Major>.<Minor> version format.');
});
});
// The below test was generated, along with ValidationDocument.czml,
// by the czml-writer ValidationDocumentationGenerator.
// https://github.com/AnalyticalGraphicsInc/czml-writer/blob/master/DotNet/GenerateFromSchema/ValidationDocumentGenerator.cs
// using command line
// GenerateFromSchema.exe -p ..\..\..\..\Schema\Packet.jsonschema -t validation -o ..\..\..\CesiumLanguageWriterTests\
// then running the generated TestGenerateValidationDocument unit test
// to produce ValidationDocument.czml and ValidationDocumentAssertions.js
it('checks validation document', function() {
return CzmlDataSource.load('Data/CZML/ValidationDocument.czml').then(function(dataSource) {
/*jshint -W120 */
var e;
var date;
var documentStartDate = JulianDate.fromIso8601('2016-06-17T12:00:00Z');
var documentStopDate = JulianDate.fromIso8601('2016-06-17T13:00:00Z');
expect(dataSource.clock.startTime).toEqual(documentStartDate);
expect(dataSource.clock.stopTime).toEqual(documentStopDate);
expect(dataSource.clock.currentTime).toEqual(documentStartDate);
expect(dataSource.clock.multiplier).toEqual(1.0);
expect(dataSource.clock.clockRange).toEqual(ClockRange.UNBOUNDED);
expect(dataSource.clock.clockStep).toEqual(ClockStep.SYSTEM_CLOCK_MULTIPLIER);
var constant = e = dataSource.entities.getById('Constant');
expect(e).toBeDefined();
date = JulianDate.now();
expect(e.description.getValue(date)).toEqual('string0');
expect(e.position.getValue(date)).toEqual(new Cartesian3(1, 2, 3));
expect(e.orientation.getValue(date)).toEqualEpsilon(new Quaternion(0.445435403187374, 0.534522483824849, 0.623609564462324, 0.356348322549899), 1e-14);
expect(e.viewFrom.getValue(date)).toEqual(new Cartesian3(8, 9, 10));
expect(e.billboard.show.getValue(date)).toEqual(true);
expect(e.billboard.image.getValue(date)).toEqual('http://example.com/11');
expect(e.billboard.scale.getValue(date)).toEqual(12.0);
expect(e.billboard.pixelOffset.getValue(date)).toEqual(new Cartesian2(13, 14));
expect(e.billboard.eyeOffset.getValue(date)).toEqual(new Cartesian3(15, 16, 17));
expect(e.billboard.horizontalOrigin.getValue(date)).toEqual(HorizontalOrigin.LEFT);
expect(e.billboard.verticalOrigin.getValue(date)).toEqual(VerticalOrigin.BOTTOM);
expect(e.billboard.color.getValue(date)).toEqual(Color.fromBytes(19, 20, 21, 18));
expect(e.billboard.rotation.getValue(date)).toEqual(22.0);
expect(e.billboard.alignedAxis.getValue(date)).toEqual(new Cartesian3(23, 24, 25));
expect(e.billboard.sizeInMeters.getValue(date)).toEqual(true);
expect(e.billboard.width.getValue(date)).toEqual(26.0);
expect(e.billboard.height.getValue(date)).toEqual(27.0);
expect(e.billboard.scaleByDistance.getValue(date)).toEqual(new NearFarScalar(28, 29, 30, 31));
expect(e.billboard.translucencyByDistance.getValue(date)).toEqual(new NearFarScalar(32, 33, 34, 35));
expect(e.billboard.pixelOffsetScaleByDistance.getValue(date)).toEqual(new NearFarScalar(36, 37, 38, 39));
expect(e.billboard.imageSubRegion.getValue(date)).toEqual(new BoundingRectangle(40, 41, 42, 43));
expect(e.box.show.getValue(date)).toEqual(true);
expect(e.box.dimensions.getValue(date)).toEqual(new Cartesian3(44, 45, 46));
expect(e.box.fill.getValue(date)).toEqual(true);
expect(e.box.material.color.getValue(date)).toEqual(Color.fromBytes(48, 49, 50, 47));
expect(e.box.outline.getValue(date)).toEqual(true);
expect(e.box.outlineColor.getValue(date)).toEqual(Color.fromBytes(52, 53, 54, 51));
expect(e.box.outlineWidth.getValue(date)).toEqual(55.0);
expect(e.corridor.show.getValue(date)).toEqual(true);
expect(e.corridor.positions.getValue(date)).toEqual([ new Cartesian3(56, 57, 58), new Cartesian3(59, 60, 61) ]);
expect(e.corridor.width.getValue(date)).toEqual(62.0);
expect(e.corridor.height.getValue(date)).toEqual(63.0);
expect(e.corridor.extrudedHeight.getValue(date)).toEqual(64.0);
expect(e.corridor.cornerType.getValue(date)).toEqual(CornerType.BEVELED);
expect(e.corridor.granularity.getValue(date)).toEqual(65.0);
expect(e.corridor.fill.getValue(date)).toEqual(true);
expect(e.corridor.material.color.getValue(date)).toEqual(Color.fromBytes(67, 68, 69, 66));
expect(e.corridor.outline.getValue(date)).toEqual(true);
expect(e.corridor.outlineColor.getValue(date)).toEqual(Color.fromBytes(71, 72, 73, 70));
expect(e.corridor.outlineWidth.getValue(date)).toEqual(74.0);
expect(e.cylinder.show.getValue(date)).toEqual(true);
expect(e.cylinder.length.getValue(date)).toEqual(75.0);
expect(e.cylinder.topRadius.getValue(date)).toEqual(76.0);
expect(e.cylinder.bottomRadius.getValue(date)).toEqual(77.0);
expect(e.cylinder.fill.getValue(date)).toEqual(true);
expect(e.cylinder.material.color.getValue(date)).toEqual(Color.fromBytes(79, 80, 81, 78));
expect(e.cylinder.outline.getValue(date)).toEqual(true);
expect(e.cylinder.outlineColor.getValue(date)).toEqual(Color.fromBytes(83, 84, 85, 82));
expect(e.cylinder.outlineWidth.getValue(date)).toEqual(86.0);
expect(e.cylinder.numberOfVerticalLines.getValue(date)).toEqual(87.0);
expect(e.cylinder.slices.getValue(date)).toEqual(88.0);
expect(e.ellipse.show.getValue(date)).toEqual(true);
expect(e.ellipse.semiMajorAxis.getValue(date)).toEqual(89.0);
expect(e.ellipse.semiMinorAxis.getValue(date)).toEqual(90.0);
expect(e.ellipse.height.getValue(date)).toEqual(91.0);
expect(e.ellipse.extrudedHeight.getValue(date)).toEqual(92.0);
expect(e.ellipse.rotation.getValue(date)).toEqual(93.0);
expect(e.ellipse.stRotation.getValue(date)).toEqual(94.0);
expect(e.ellipse.granularity.getValue(date)).toEqual(95.0);
expect(e.ellipse.fill.getValue(date)).toEqual(true);
expect(e.ellipse.material.color.getValue(date)).toEqual(Color.fromBytes(97, 98, 99, 96));
expect(e.ellipse.outline.getValue(date)).toEqual(true);
expect(e.ellipse.outlineColor.getValue(date)).toEqual(Color.fromBytes(101, 102, 103, 100));
expect(e.ellipse.outlineWidth.getValue(date)).toEqual(104.0);
expect(e.ellipse.numberOfVerticalLines.getValue(date)).toEqual(105.0);
expect(e.ellipsoid.show.getValue(date)).toEqual(true);
expect(e.ellipsoid.radii.getValue(date)).toEqual(new Cartesian3(106, 107, 108));
expect(e.ellipsoid.fill.getValue(date)).toEqual(true);
expect(e.ellipsoid.material.color.getValue(date)).toEqual(Color.fromBytes(110, 111, 112, 109));
expect(e.ellipsoid.outline.getValue(date)).toEqual(true);
expect(e.ellipsoid.outlineColor.getValue(date)).toEqual(Color.fromBytes(114, 115, 116, 113));
expect(e.ellipsoid.outlineWidth.getValue(date)).toEqual(117.0);
expect(e.ellipsoid.stackPartitions.getValue(date)).toEqual(118.0);
expect(e.ellipsoid.slicePartitions.getValue(date)).toEqual(119.0);
expect(e.ellipsoid.subdivisions.getValue(date)).toEqual(120.0);
expect(e.label.show.getValue(date)).toEqual(true);
expect(e.label.text.getValue(date)).toEqual('string121');
expect(e.label.font.getValue(date)).toEqual('22px sans-serif');
expect(e.label.style.getValue(date)).toEqual(LabelStyle.FILL_AND_OUTLINE);
expect(e.label.scale.getValue(date)).toEqual(123.0);
expect(e.label.pixelOffset.getValue(date)).toEqual(new Cartesian2(124, 125));
expect(e.label.eyeOffset.getValue(date)).toEqual(new Cartesian3(126, 127, 128));
expect(e.label.horizontalOrigin.getValue(date)).toEqual(HorizontalOrigin.LEFT);
expect(e.label.verticalOrigin.getValue(date)).toEqual(VerticalOrigin.BOTTOM);
expect(e.label.fillColor.getValue(date)).toEqual(Color.fromBytes(130, 131, 132, 129));
expect(e.label.outlineColor.getValue(date)).toEqual(Color.fromBytes(134, 135, 136, 133));
expect(e.label.outlineWidth.getValue(date)).toEqual(137.0);
expect(e.label.translucencyByDistance.getValue(date)).toEqual(new NearFarScalar(138, 139, 140, 141));
expect(e.label.pixelOffsetScaleByDistance.getValue(date)).toEqual(new NearFarScalar(142, 143, 144, 145));
expect(e.model.show.getValue(date)).toEqual(true);
expect(e.model.uri.getValue(date)).toEqual('http://example.com/146');
expect(e.model.scale.getValue(date)).toEqual(147.0);
expect(e.model.minimumPixelSize.getValue(date)).toEqual(148.0);
expect(e.model.maximumScale.getValue(date)).toEqual(149.0);
expect(e.model.incrementallyLoadTextures.getValue(date)).toEqual(true);
expect(e.model.runAnimations.getValue(date)).toEqual(true);
expect(e.model.nodeTransformations.prop.translation.getValue(date)).toEqual(new Cartesian3(150, 151, 152));
expect(e.model.nodeTransformations.prop.rotation.getValue(date)).toEqualEpsilon(new Quaternion(0.498368828292958, 0.50160498951564, 0.504841150738322, 0.495132667070277), 1e-14);
expect(e.model.nodeTransformations.prop.scale.getValue(date)).toEqual(new Cartesian3(157, 158, 159));
expect(e.path.show.getValue(date)).toEqual(true);
expect(e.path.width.getValue(date)).toEqual(160.0);
expect(e.path.resolution.getValue(date)).toEqual(161.0);
expect(e.path.leadTime.getValue(date)).toEqual(162.0);
expect(e.path.trailTime.getValue(date)).toEqual(163.0);
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(165, 166, 167, 164));
expect(e.point.show.getValue(date)).toEqual(true);
expect(e.point.pixelSize.getValue(date)).toEqual(168.0);
expect(e.point.color.getValue(date)).toEqual(Color.fromBytes(170, 171, 172, 169));
expect(e.point.outlineColor.getValue(date)).toEqual(Color.fromBytes(174, 175, 176, 173));
expect(e.point.outlineWidth.getValue(date)).toEqual(177.0);
expect(e.point.scaleByDistance.getValue(date)).toEqual(new NearFarScalar(178, 179, 180, 181));
expect(e.point.translucencyByDistance.getValue(date)).toEqual(new NearFarScalar(182, 183, 184, 185));
expect(e.polygon.show.getValue(date)).toEqual(true);
expect(e.polygon.hierarchy.getValue(date)).toEqual([ new Cartesian3(186, 187, 188), new Cartesian3(189, 190, 191) ]);
expect(e.polygon.height.getValue(date)).toEqual(192.0);
expect(e.polygon.extrudedHeight.getValue(date)).toEqual(193.0);
expect(e.polygon.stRotation.getValue(date)).toEqual(194.0);
expect(e.polygon.granularity.getValue(date)).toEqual(195.0);
expect(e.polygon.fill.getValue(date)).toEqual(true);
expect(e.polygon.material.color.getValue(date)).toEqual(Color.fromBytes(197, 198, 199, 196));
expect(e.polygon.outline.getValue(date)).toEqual(true);
expect(e.polygon.outlineColor.getValue(date)).toEqual(Color.fromBytes(201, 202, 203, 200));
expect(e.polygon.outlineWidth.getValue(date)).toEqual(204.0);
expect(e.polygon.perPositionHeight.getValue(date)).toEqual(true);
expect(e.polygon.closeTop.getValue(date)).toEqual(true);
expect(e.polygon.closeBottom.getValue(date)).toEqual(true);
expect(e.polyline.show.getValue(date)).toEqual(true);
expect(e.polyline.positions.getValue(date)).toEqual([ new Cartesian3(205, 206, 207), new Cartesian3(208, 209, 210) ]);
expect(e.polyline.width.getValue(date)).toEqual(211.0);
expect(e.polyline.granularity.getValue(date)).toEqual(212.0);
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(214, 215, 216, 213));
expect(e.polyline.followSurface.getValue(date)).toEqual(true);
expect(e.rectangle.show.getValue(date)).toEqual(true);
expect(e.rectangle.coordinates.getValue(date)).toEqual(new Rectangle(0.230106902304275, 1.23010690230428, 0.659310575509378, 0.0885142487144819));
expect(e.rectangle.height.getValue(date)).toEqual(221.0);
expect(e.rectangle.extrudedHeight.getValue(date)).toEqual(222.0);
expect(e.rectangle.rotation.getValue(date)).toEqual(223.0);
expect(e.rectangle.stRotation.getValue(date)).toEqual(224.0);
expect(e.rectangle.granularity.getValue(date)).toEqual(225.0);
expect(e.rectangle.fill.getValue(date)).toEqual(true);
expect(e.rectangle.material.color.getValue(date)).toEqual(Color.fromBytes(227, 228, 229, 226));
expect(e.rectangle.outline.getValue(date)).toEqual(true);
expect(e.rectangle.outlineColor.getValue(date)).toEqual(Color.fromBytes(231, 232, 233, 230));
expect(e.rectangle.outlineWidth.getValue(date)).toEqual(234.0);
expect(e.rectangle.closeTop.getValue(date)).toEqual(true);
expect(e.rectangle.closeBottom.getValue(date)).toEqual(true);
expect(e.wall.show.getValue(date)).toEqual(true);
expect(e.wall.positions.getValue(date)).toEqual([ new Cartesian3(235, 236, 237), new Cartesian3(238, 239, 240) ]);
expect(e.wall.minimumHeights.getValue(date)).toEqual([ 241, 242 ]);
expect(e.wall.maximumHeights.getValue(date)).toEqual([ 243, 244 ]);
expect(e.wall.granularity.getValue(date)).toEqual(245.0);
expect(e.wall.fill.getValue(date)).toEqual(true);
expect(e.wall.material.color.getValue(date)).toEqual(Color.fromBytes(247, 248, 249, 246));
expect(e.wall.outline.getValue(date)).toEqual(true);
expect(e.wall.outlineColor.getValue(date)).toEqual(Color.fromBytes(251, 252, 253, 250));
expect(e.wall.outlineWidth.getValue(date)).toEqual(254.0);
expect(e = dataSource.entities.getById('constant386')).toBeDefined();
expect(e.position.getValue(date)).toEqual(Cartesian3.fromRadians(0.584103608455447, 0.0133072816605502, 389));
expect(e = dataSource.entities.getById('constant390')).toBeDefined();
expect(e.position.getValue(date)).toEqual(Cartesian3.fromDegrees(31, 32, 393));
expect(e = dataSource.entities.getById('constant394')).toBeDefined();
expect(e.position.getValue(date)).toEqual(new Cartesian3(395, 396, 397));
expect(e = dataSource.entities.getById('constant401')).toBeDefined();
expect(e.billboard.color.getValue(date)).toEqualEpsilon(new Color(0.580392156862745, 0.584313725490196, 0.588235294117647, 0.576470588235294), 1e-14);
expect(e = dataSource.entities.getById('constant406')).toBeDefined();
expect(e.box.material.color.getValue(date)).toEqualEpsilon(new Color(0.6, 0.603921568627451, 0.607843137254902, 0.596078431372549), 1e-14);
expect(e = dataSource.entities.getById('material_box_material_image'));
expect(e.box.material.image.getValue(date)).toEqual('http://example.com/411');
expect(e.box.material.repeat.getValue(date)).toEqual(new Cartesian2(412, 413));
expect(e.box.material.color.getValue(date)).toEqual(Color.fromBytes(160, 161, 162, 159));
expect(e.box.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_box_material_grid'));
expect(e.box.material.color.getValue(date)).toEqual(Color.fromBytes(164, 165, 166, 163));
expect(e.box.material.cellAlpha.getValue(date)).toEqual(422.0);
expect(e.box.material.lineCount.getValue(date)).toEqual(new Cartesian2(423, 424));
expect(e.box.material.lineThickness.getValue(date)).toEqual(new Cartesian2(425, 426));
expect(e.box.material.lineOffset.getValue(date)).toEqual(new Cartesian2(427, 428));
expect(e = dataSource.entities.getById('material_box_material_stripe'));
expect(e.box.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.box.material.evenColor.getValue(date)).toEqual(Color.fromBytes(175, 176, 177, 174));
expect(e.box.material.oddColor.getValue(date)).toEqual(Color.fromBytes(179, 180, 181, 178));
expect(e.box.material.offset.getValue(date)).toEqual(437.0);
expect(e.box.material.repeat.getValue(date)).toEqual(438.0);
expect(e = dataSource.entities.getById('material_box_material_image_439')).toBeDefined();
expect(e.box.material.color.getValue(date)).toEqualEpsilon(new Color(0.729411764705882, 0.733333333333333, 0.737254901960784, 0.725490196078431), 1e-14);
expect(e = dataSource.entities.getById('material_box_material_grid_444')).toBeDefined();
expect(e.box.material.color.getValue(date)).toEqualEpsilon(new Color(0.749019607843137, 0.752941176470588, 0.756862745098039, 0.745098039215686), 1e-14);
expect(e = dataSource.entities.getById('material_box_material_stripe_449')).toBeDefined();
expect(e.box.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.768627450980392, 0.772549019607843, 0.776470588235294, 0.764705882352941), 1e-14);
expect(e = dataSource.entities.getById('material_box_material_stripe_454')).toBeDefined();
expect(e.box.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.788235294117647, 0.792156862745098, 0.796078431372549, 0.784313725490196), 1e-14);
expect(e = dataSource.entities.getById('constant459')).toBeDefined();
expect(e.box.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.807843137254902, 0.811764705882353, 0.815686274509804, 0.803921568627451), 1e-14);
expect(e = dataSource.entities.getById('constant464')).toBeDefined();
expect(e.corridor.positions.getValue(date)).toEqual([ Cartesian3.fromRadians(0.0442872687106188, 1.04428726871062, 467), Cartesian3.fromRadians(1.47349094191572, 0.902694615120826, 470) ]);
expect(e = dataSource.entities.getById('constant471')).toBeDefined();
expect(e.corridor.positions.getValue(date)).toEqual([ Cartesian3.fromDegrees(22, 23, 474), Cartesian3.fromDegrees(25, 26, 477) ]);
expect(e = dataSource.entities.getById('constant478')).toBeDefined();
expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new Color(0.882352941176471, 0.886274509803922, 0.890196078431373, 0.87843137254902), 1e-14);
expect(e = dataSource.entities.getById('material_corridor_material_image'));
expect(e.corridor.material.image.getValue(date)).toEqual('http://example.com/483');
expect(e.corridor.material.repeat.getValue(date)).toEqual(new Cartesian2(484, 485));
expect(e.corridor.material.color.getValue(date)).toEqual(Color.fromBytes(232, 233, 234, 231));
expect(e.corridor.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_corridor_material_grid'));
expect(e.corridor.material.color.getValue(date)).toEqual(Color.fromBytes(236, 237, 238, 235));
expect(e.corridor.material.cellAlpha.getValue(date)).toEqual(494.0);
expect(e.corridor.material.lineCount.getValue(date)).toEqual(new Cartesian2(495, 496));
expect(e.corridor.material.lineThickness.getValue(date)).toEqual(new Cartesian2(497, 498));
expect(e.corridor.material.lineOffset.getValue(date)).toEqual(new Cartesian2(499, 500));
expect(e = dataSource.entities.getById('material_corridor_material_stripe'));
expect(e.corridor.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.corridor.material.evenColor.getValue(date)).toEqual(Color.fromBytes(247, 248, 249, 246));
expect(e.corridor.material.oddColor.getValue(date)).toEqual(Color.fromBytes(251, 252, 253, 250));
expect(e.corridor.material.offset.getValue(date)).toEqual(509.0);
expect(e.corridor.material.repeat.getValue(date)).toEqual(510.0);
expect(e = dataSource.entities.getById('material_corridor_material_image_511')).toBeDefined();
expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new Color(0.0117647058823529, 0.0156862745098039, 0.0196078431372549, 0.00784313725490196), 1e-14);
expect(e = dataSource.entities.getById('material_corridor_material_grid_516')).toBeDefined();
expect(e.corridor.material.color.getValue(date)).toEqualEpsilon(new Color(0.0313725490196078, 0.0352941176470588, 0.0392156862745098, 0.0274509803921569), 1e-14);
expect(e = dataSource.entities.getById('material_corridor_material_stripe_521')).toBeDefined();
expect(e.corridor.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.0509803921568627, 0.0549019607843137, 0.0588235294117647, 0.0470588235294118), 1e-14);
expect(e = dataSource.entities.getById('material_corridor_material_stripe_526')).toBeDefined();
expect(e.corridor.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.0705882352941176, 0.0745098039215686, 0.0784313725490196, 0.0666666666666667), 1e-14);
expect(e = dataSource.entities.getById('constant531')).toBeDefined();
expect(e.corridor.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.0901960784313725, 0.0941176470588235, 0.0980392156862745, 0.0862745098039216), 1e-14);
expect(e = dataSource.entities.getById('constant536')).toBeDefined();
expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('material_cylinder_material_image'));
expect(e.cylinder.material.image.getValue(date)).toEqual('http://example.com/541');
expect(e.cylinder.material.repeat.getValue(date)).toEqual(new Cartesian2(542, 543));
expect(e.cylinder.material.color.getValue(date)).toEqual(Color.fromBytes(35, 36, 37, 34));
expect(e.cylinder.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_cylinder_material_grid'));
expect(e.cylinder.material.color.getValue(date)).toEqual(Color.fromBytes(39, 40, 41, 38));
expect(e.cylinder.material.cellAlpha.getValue(date)).toEqual(552.0);
expect(e.cylinder.material.lineCount.getValue(date)).toEqual(new Cartesian2(553, 554));
expect(e.cylinder.material.lineThickness.getValue(date)).toEqual(new Cartesian2(555, 556));
expect(e.cylinder.material.lineOffset.getValue(date)).toEqual(new Cartesian2(557, 558));
expect(e = dataSource.entities.getById('material_cylinder_material_stripe'));
expect(e.cylinder.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.cylinder.material.evenColor.getValue(date)).toEqual(Color.fromBytes(50, 51, 52, 49));
expect(e.cylinder.material.oddColor.getValue(date)).toEqual(Color.fromBytes(54, 55, 56, 53));
expect(e.cylinder.material.offset.getValue(date)).toEqual(567.0);
expect(e.cylinder.material.repeat.getValue(date)).toEqual(568.0);
expect(e = dataSource.entities.getById('material_cylinder_material_image_569')).toBeDefined();
expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new Color(0.23921568627451, 0.243137254901961, 0.247058823529412, 0.235294117647059), 1e-14);
expect(e = dataSource.entities.getById('material_cylinder_material_grid_574')).toBeDefined();
expect(e.cylinder.material.color.getValue(date)).toEqualEpsilon(new Color(0.258823529411765, 0.262745098039216, 0.266666666666667, 0.254901960784314), 1e-14);
expect(e = dataSource.entities.getById('material_cylinder_material_stripe_579')).toBeDefined();
expect(e.cylinder.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.27843137254902, 0.282352941176471, 0.286274509803922, 0.274509803921569), 1e-14);
expect(e = dataSource.entities.getById('material_cylinder_material_stripe_584')).toBeDefined();
expect(e.cylinder.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.298039215686275, 0.301960784313725, 0.305882352941176, 0.294117647058824), 1e-14);
expect(e = dataSource.entities.getById('constant589')).toBeDefined();
expect(e.cylinder.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.317647058823529, 0.32156862745098, 0.325490196078431, 0.313725490196078), 1e-14);
expect(e = dataSource.entities.getById('constant594')).toBeDefined();
expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new Color(0.337254901960784, 0.341176470588235, 0.345098039215686, 0.333333333333333), 1e-14);
expect(e = dataSource.entities.getById('material_ellipse_material_image'));
expect(e.ellipse.material.image.getValue(date)).toEqual('http://example.com/599');
expect(e.ellipse.material.repeat.getValue(date)).toEqual(new Cartesian2(600, 601));
expect(e.ellipse.material.color.getValue(date)).toEqual(Color.fromBytes(93, 94, 95, 92));
expect(e.ellipse.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_ellipse_material_grid'));
expect(e.ellipse.material.color.getValue(date)).toEqual(Color.fromBytes(97, 98, 99, 96));
expect(e.ellipse.material.cellAlpha.getValue(date)).toEqual(610.0);
expect(e.ellipse.material.lineCount.getValue(date)).toEqual(new Cartesian2(611, 612));
expect(e.ellipse.material.lineThickness.getValue(date)).toEqual(new Cartesian2(613, 614));
expect(e.ellipse.material.lineOffset.getValue(date)).toEqual(new Cartesian2(615, 616));
expect(e = dataSource.entities.getById('material_ellipse_material_stripe'));
expect(e.ellipse.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.ellipse.material.evenColor.getValue(date)).toEqual(Color.fromBytes(108, 109, 110, 107));
expect(e.ellipse.material.oddColor.getValue(date)).toEqual(Color.fromBytes(112, 113, 114, 111));
expect(e.ellipse.material.offset.getValue(date)).toEqual(625.0);
expect(e.ellipse.material.repeat.getValue(date)).toEqual(626.0);
expect(e = dataSource.entities.getById('material_ellipse_material_image_627')).toBeDefined();
expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new Color(0.466666666666667, 0.470588235294118, 0.474509803921569, 0.462745098039216), 1e-14);
expect(e = dataSource.entities.getById('material_ellipse_material_grid_632')).toBeDefined();
expect(e.ellipse.material.color.getValue(date)).toEqualEpsilon(new Color(0.486274509803922, 0.490196078431373, 0.494117647058824, 0.482352941176471), 1e-14);
expect(e = dataSource.entities.getById('material_ellipse_material_stripe_637')).toBeDefined();
expect(e.ellipse.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.505882352941176, 0.509803921568627, 0.513725490196078, 0.501960784313725), 1e-14);
expect(e = dataSource.entities.getById('material_ellipse_material_stripe_642')).toBeDefined();
expect(e.ellipse.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.525490196078431, 0.529411764705882, 0.533333333333333, 0.52156862745098), 1e-14);
expect(e = dataSource.entities.getById('constant647')).toBeDefined();
expect(e.ellipse.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.545098039215686, 0.549019607843137, 0.552941176470588, 0.541176470588235), 1e-14);
expect(e = dataSource.entities.getById('constant652')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new Color(0.564705882352941, 0.568627450980392, 0.572549019607843, 0.56078431372549), 1e-14);
expect(e = dataSource.entities.getById('material_ellipsoid_material_image'));
expect(e.ellipsoid.material.image.getValue(date)).toEqual('http://example.com/657');
expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(new Cartesian2(658, 659));
expect(e.ellipsoid.material.color.getValue(date)).toEqual(Color.fromBytes(151, 152, 153, 150));
expect(e.ellipsoid.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_ellipsoid_material_grid'));
expect(e.ellipsoid.material.color.getValue(date)).toEqual(Color.fromBytes(155, 156, 157, 154));
expect(e.ellipsoid.material.cellAlpha.getValue(date)).toEqual(668.0);
expect(e.ellipsoid.material.lineCount.getValue(date)).toEqual(new Cartesian2(669, 670));
expect(e.ellipsoid.material.lineThickness.getValue(date)).toEqual(new Cartesian2(671, 672));
expect(e.ellipsoid.material.lineOffset.getValue(date)).toEqual(new Cartesian2(673, 674));
expect(e = dataSource.entities.getById('material_ellipsoid_material_stripe'));
expect(e.ellipsoid.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(Color.fromBytes(166, 167, 168, 165));
expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(Color.fromBytes(170, 171, 172, 169));
expect(e.ellipsoid.material.offset.getValue(date)).toEqual(683.0);
expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(684.0);
expect(e = dataSource.entities.getById('material_ellipsoid_material_image_685')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new Color(0.694117647058824, 0.698039215686274, 0.701960784313725, 0.690196078431373), 1e-14);
expect(e = dataSource.entities.getById('material_ellipsoid_material_grid_690')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(date)).toEqualEpsilon(new Color(0.713725490196078, 0.717647058823529, 0.72156862745098, 0.709803921568627), 1e-14);
expect(e = dataSource.entities.getById('material_ellipsoid_material_stripe_695')).toBeDefined();
expect(e.ellipsoid.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.733333333333333, 0.737254901960784, 0.741176470588235, 0.729411764705882), 1e-14);
expect(e = dataSource.entities.getById('material_ellipsoid_material_stripe_700')).toBeDefined();
expect(e.ellipsoid.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.752941176470588, 0.756862745098039, 0.76078431372549, 0.749019607843137), 1e-14);
expect(e = dataSource.entities.getById('constant705')).toBeDefined();
expect(e.ellipsoid.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.772549019607843, 0.776470588235294, 0.780392156862745, 0.768627450980392), 1e-14);
expect(e = dataSource.entities.getById('constant710')).toBeDefined();
expect(e.label.fillColor.getValue(date)).toEqualEpsilon(new Color(0.792156862745098, 0.796078431372549, 0.8, 0.788235294117647), 1e-14);
expect(e = dataSource.entities.getById('constant715')).toBeDefined();
expect(e.label.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.811764705882353, 0.815686274509804, 0.819607843137255, 0.807843137254902), 1e-14);
expect(e = dataSource.entities.getById('constant720')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.831372549019608, 0.835294117647059, 0.83921568627451, 0.827450980392157), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_polylineOutline'));
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(216, 217, 218, 215));
expect(e.path.material.outlineColor.getValue(date)).toEqual(Color.fromBytes(220, 221, 222, 219));
expect(e.path.material.outlineWidth.getValue(date)).toEqual(733.0);
expect(e = dataSource.entities.getById('material_path_material_polylineArrow'));
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(225, 226, 227, 224));
expect(e = dataSource.entities.getById('material_path_material_polylineGlow'));
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(229, 230, 231, 228));
expect(e.path.material.glowPower.getValue(date)).toEqual(742.0);
expect(e = dataSource.entities.getById('material_path_material_image'));
expect(e.path.material.image.getValue(date)).toEqual('http://example.com/743');
expect(e.path.material.repeat.getValue(date)).toEqual(new Cartesian2(744, 745));
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(237, 238, 239, 236));
expect(e.path.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_path_material_grid'));
expect(e.path.material.color.getValue(date)).toEqual(Color.fromBytes(241, 242, 243, 240));
expect(e.path.material.cellAlpha.getValue(date)).toEqual(754.0);
expect(e.path.material.lineCount.getValue(date)).toEqual(new Cartesian2(755, 756));
expect(e.path.material.lineThickness.getValue(date)).toEqual(new Cartesian2(757, 758));
expect(e.path.material.lineOffset.getValue(date)).toEqual(new Cartesian2(759, 760));
expect(e = dataSource.entities.getById('material_path_material_stripe'));
expect(e.path.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.path.material.evenColor.getValue(date)).toEqual(Color.fromBytes(252, 253, 254, 251));
expect(e.path.material.oddColor.getValue(date)).toEqual(Color.fromBytes(1, 2, 3, 0));
expect(e.path.material.offset.getValue(date)).toEqual(769.0);
expect(e.path.material.repeat.getValue(date)).toEqual(770.0);
expect(e = dataSource.entities.getById('material_path_material_polylineOutline_771')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.0313725490196078, 0.0352941176470588, 0.0392156862745098, 0.0274509803921569), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_polylineOutline_776')).toBeDefined();
expect(e.path.material.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.0509803921568627, 0.0549019607843137, 0.0588235294117647, 0.0470588235294118), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_polylineArrow_781')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.0705882352941176, 0.0745098039215686, 0.0784313725490196, 0.0666666666666667), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_polylineGlow_786')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.0901960784313725, 0.0941176470588235, 0.0980392156862745, 0.0862745098039216), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_image_791')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_grid_796')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqualEpsilon(new Color(0.129411764705882, 0.133333333333333, 0.137254901960784, 0.125490196078431), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_stripe_801')).toBeDefined();
expect(e.path.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.149019607843137, 0.152941176470588, 0.156862745098039, 0.145098039215686), 1e-14);
expect(e = dataSource.entities.getById('material_path_material_stripe_806')).toBeDefined();
expect(e.path.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.168627450980392, 0.172549019607843, 0.176470588235294, 0.164705882352941), 1e-14);
expect(e = dataSource.entities.getById('constant811')).toBeDefined();
expect(e.point.color.getValue(date)).toEqualEpsilon(new Color(0.188235294117647, 0.192156862745098, 0.196078431372549, 0.184313725490196), 1e-14);
expect(e = dataSource.entities.getById('constant816')).toBeDefined();
expect(e.point.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.207843137254902, 0.211764705882353, 0.215686274509804, 0.203921568627451), 1e-14);
expect(e = dataSource.entities.getById('constant821')).toBeDefined();
expect(e.polygon.hierarchy.getValue(date)).toEqual([ Cartesian3.fromRadians(0.4735210862691, 1.4735210862691, 824), Cartesian3.fromRadians(0.331928432679307, 1.33192843267931, 827) ]);
expect(e = dataSource.entities.getById('constant828')).toBeDefined();
expect(e.polygon.hierarchy.getValue(date)).toEqual([ Cartesian3.fromDegrees(19, 20, 831), Cartesian3.fromDegrees(22, 23, 834) ]);
expect(e = dataSource.entities.getById('constant835')).toBeDefined();
expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new Color(0.282352941176471, 0.286274509803922, 0.290196078431373, 0.27843137254902), 1e-14);
expect(e = dataSource.entities.getById('material_polygon_material_image'));
expect(e.polygon.material.image.getValue(date)).toEqual('http://example.com/840');
expect(e.polygon.material.repeat.getValue(date)).toEqual(new Cartesian2(841, 842));
expect(e.polygon.material.color.getValue(date)).toEqual(Color.fromBytes(79, 80, 81, 78));
expect(e.polygon.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_polygon_material_grid'));
expect(e.polygon.material.color.getValue(date)).toEqual(Color.fromBytes(83, 84, 85, 82));
expect(e.polygon.material.cellAlpha.getValue(date)).toEqual(851.0);
expect(e.polygon.material.lineCount.getValue(date)).toEqual(new Cartesian2(852, 853));
expect(e.polygon.material.lineThickness.getValue(date)).toEqual(new Cartesian2(854, 855));
expect(e.polygon.material.lineOffset.getValue(date)).toEqual(new Cartesian2(856, 857));
expect(e = dataSource.entities.getById('material_polygon_material_stripe'));
expect(e.polygon.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.polygon.material.evenColor.getValue(date)).toEqual(Color.fromBytes(94, 95, 96, 93));
expect(e.polygon.material.oddColor.getValue(date)).toEqual(Color.fromBytes(98, 99, 100, 97));
expect(e.polygon.material.offset.getValue(date)).toEqual(866.0);
expect(e.polygon.material.repeat.getValue(date)).toEqual(867.0);
expect(e = dataSource.entities.getById('material_polygon_material_image_868')).toBeDefined();
expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new Color(0.411764705882353, 0.415686274509804, 0.419607843137255, 0.407843137254902), 1e-14);
expect(e = dataSource.entities.getById('material_polygon_material_grid_873')).toBeDefined();
expect(e.polygon.material.color.getValue(date)).toEqualEpsilon(new Color(0.431372549019608, 0.435294117647059, 0.43921568627451, 0.427450980392157), 1e-14);
expect(e = dataSource.entities.getById('material_polygon_material_stripe_878')).toBeDefined();
expect(e.polygon.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.450980392156863, 0.454901960784314, 0.458823529411765, 0.447058823529412), 1e-14);
expect(e = dataSource.entities.getById('material_polygon_material_stripe_883')).toBeDefined();
expect(e.polygon.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.470588235294118, 0.474509803921569, 0.47843137254902, 0.466666666666667), 1e-14);
expect(e = dataSource.entities.getById('constant888')).toBeDefined();
expect(e.polygon.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.490196078431373, 0.494117647058824, 0.498039215686275, 0.486274509803922), 1e-14);
expect(e = dataSource.entities.getById('constant893')).toBeDefined();
expect(e.polyline.positions.getValue(date)).toEqual([ Cartesian3.fromRadians(0.216890053703859, 1.21689005370386, 896), Cartesian3.fromRadians(0.0752974001140654, 1.07529740011407, 899) ]);
expect(e = dataSource.entities.getById('constant900')).toBeDefined();
expect(e.polyline.positions.getValue(date)).toEqual([ Cartesian3.fromDegrees(1, 2, 903), Cartesian3.fromDegrees(4, 5, 906) ]);
expect(e = dataSource.entities.getById('constant907')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.564705882352941, 0.568627450980392, 0.572549019607843, 0.56078431372549), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_polylineOutline'));
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(148, 149, 150, 147));
expect(e.polyline.material.outlineColor.getValue(date)).toEqual(Color.fromBytes(152, 153, 154, 151));
expect(e.polyline.material.outlineWidth.getValue(date)).toEqual(920.0);
expect(e = dataSource.entities.getById('material_polyline_material_polylineArrow'));
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(157, 158, 159, 156));
expect(e = dataSource.entities.getById('material_polyline_material_polylineGlow'));
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(161, 162, 163, 160));
expect(e.polyline.material.glowPower.getValue(date)).toEqual(929.0);
expect(e = dataSource.entities.getById('material_polyline_material_image'));
expect(e.polyline.material.image.getValue(date)).toEqual('http://example.com/930');
expect(e.polyline.material.repeat.getValue(date)).toEqual(new Cartesian2(931, 932));
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(169, 170, 171, 168));
expect(e.polyline.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_polyline_material_grid'));
expect(e.polyline.material.color.getValue(date)).toEqual(Color.fromBytes(173, 174, 175, 172));
expect(e.polyline.material.cellAlpha.getValue(date)).toEqual(941.0);
expect(e.polyline.material.lineCount.getValue(date)).toEqual(new Cartesian2(942, 943));
expect(e.polyline.material.lineThickness.getValue(date)).toEqual(new Cartesian2(944, 945));
expect(e.polyline.material.lineOffset.getValue(date)).toEqual(new Cartesian2(946, 947));
expect(e = dataSource.entities.getById('material_polyline_material_stripe'));
expect(e.polyline.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.polyline.material.evenColor.getValue(date)).toEqual(Color.fromBytes(184, 185, 186, 183));
expect(e.polyline.material.oddColor.getValue(date)).toEqual(Color.fromBytes(188, 189, 190, 187));
expect(e.polyline.material.offset.getValue(date)).toEqual(956.0);
expect(e.polyline.material.repeat.getValue(date)).toEqual(957.0);
expect(e = dataSource.entities.getById('material_polyline_material_polylineOutline_958')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.764705882352941, 0.768627450980392, 0.772549019607843, 0.76078431372549), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_polylineOutline_963')).toBeDefined();
expect(e.polyline.material.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.784313725490196, 0.788235294117647, 0.792156862745098, 0.780392156862745), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_polylineArrow_968')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.803921568627451, 0.807843137254902, 0.811764705882353, 0.8), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_polylineGlow_973')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.823529411764706, 0.827450980392157, 0.831372549019608, 0.819607843137255), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_image_978')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.843137254901961, 0.847058823529412, 0.850980392156863, 0.83921568627451), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_grid_983')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqualEpsilon(new Color(0.862745098039216, 0.866666666666667, 0.870588235294118, 0.858823529411765), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_stripe_988')).toBeDefined();
expect(e.polyline.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.882352941176471, 0.886274509803922, 0.890196078431373, 0.87843137254902), 1e-14);
expect(e = dataSource.entities.getById('material_polyline_material_stripe_993')).toBeDefined();
expect(e.polyline.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.901960784313726, 0.905882352941176, 0.909803921568627, 0.898039215686275), 1e-14);
expect(e = dataSource.entities.getById('constant998')).toBeDefined();
expect(e.rectangle.coordinates.getValue(date)).toEqual(Rectangle.fromDegrees(9, 10, 11, 12));
expect(e = dataSource.entities.getById('constant1003')).toBeDefined();
expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new Color(0.941176470588235, 0.945098039215686, 0.949019607843137, 0.937254901960784), 1e-14);
expect(e = dataSource.entities.getById('material_rectangle_material_image'));
expect(e.rectangle.material.image.getValue(date)).toEqual('http://example.com/1008');
expect(e.rectangle.material.repeat.getValue(date)).toEqual(new Cartesian2(1009, 1010));
expect(e.rectangle.material.color.getValue(date)).toEqual(Color.fromBytes(247, 248, 249, 246));
expect(e.rectangle.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_rectangle_material_grid'));
expect(e.rectangle.material.color.getValue(date)).toEqual(Color.fromBytes(251, 252, 253, 250));
expect(e.rectangle.material.cellAlpha.getValue(date)).toEqual(1019.0);
expect(e.rectangle.material.lineCount.getValue(date)).toEqual(new Cartesian2(1020, 1021));
expect(e.rectangle.material.lineThickness.getValue(date)).toEqual(new Cartesian2(1022, 1023));
expect(e.rectangle.material.lineOffset.getValue(date)).toEqual(new Cartesian2(1024, 1025));
expect(e = dataSource.entities.getById('material_rectangle_material_stripe'));
expect(e.rectangle.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.rectangle.material.evenColor.getValue(date)).toEqual(Color.fromBytes(7, 8, 9, 6));
expect(e.rectangle.material.oddColor.getValue(date)).toEqual(Color.fromBytes(11, 12, 13, 10));
expect(e.rectangle.material.offset.getValue(date)).toEqual(1034.0);
expect(e.rectangle.material.repeat.getValue(date)).toEqual(1035.0);
expect(e = dataSource.entities.getById('material_rectangle_material_image_1036')).toBeDefined();
expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new Color(0.0705882352941176, 0.0745098039215686, 0.0784313725490196, 0.0666666666666667), 1e-14);
expect(e = dataSource.entities.getById('material_rectangle_material_grid_1041')).toBeDefined();
expect(e.rectangle.material.color.getValue(date)).toEqualEpsilon(new Color(0.0901960784313725, 0.0941176470588235, 0.0980392156862745, 0.0862745098039216), 1e-14);
expect(e = dataSource.entities.getById('material_rectangle_material_stripe_1046')).toBeDefined();
expect(e.rectangle.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('material_rectangle_material_stripe_1051')).toBeDefined();
expect(e.rectangle.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.129411764705882, 0.133333333333333, 0.137254901960784, 0.125490196078431), 1e-14);
expect(e = dataSource.entities.getById('constant1056')).toBeDefined();
expect(e.rectangle.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.149019607843137, 0.152941176470588, 0.156862745098039, 0.145098039215686), 1e-14);
expect(e = dataSource.entities.getById('constant1061')).toBeDefined();
expect(e.wall.positions.getValue(date)).toEqual([ Cartesian3.fromRadians(0.141683086649927, 1.14168308664993, 1064), Cartesian3.fromRadians(9.04330601336767E-05, 1.00009043306013, 1067) ]);
expect(e = dataSource.entities.getById('constant1068')).toBeDefined();
expect(e.wall.positions.getValue(date)).toEqual([ Cartesian3.fromDegrees(34, 35, 1071), Cartesian3.fromDegrees(37, 38, 1074) ]);
expect(e = dataSource.entities.getById('constant1075')).toBeDefined();
expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new Color(0.223529411764706, 0.227450980392157, 0.231372549019608, 0.219607843137255), 1e-14);
expect(e = dataSource.entities.getById('material_wall_material_image'));
expect(e.wall.material.image.getValue(date)).toEqual('http://example.com/1080');
expect(e.wall.material.repeat.getValue(date)).toEqual(new Cartesian2(1081, 1082));
expect(e.wall.material.color.getValue(date)).toEqual(Color.fromBytes(64, 65, 66, 63));
expect(e.wall.material.transparent.getValue(date)).toEqual(true);
expect(e = dataSource.entities.getById('material_wall_material_grid'));
expect(e.wall.material.color.getValue(date)).toEqual(Color.fromBytes(68, 69, 70, 67));
expect(e.wall.material.cellAlpha.getValue(date)).toEqual(1091.0);
expect(e.wall.material.lineCount.getValue(date)).toEqual(new Cartesian2(1092, 1093));
expect(e.wall.material.lineThickness.getValue(date)).toEqual(new Cartesian2(1094, 1095));
expect(e.wall.material.lineOffset.getValue(date)).toEqual(new Cartesian2(1096, 1097));
expect(e = dataSource.entities.getById('material_wall_material_stripe'));
expect(e.wall.material.orientation.getValue(date)).toEqual(StripeOrientation.VERTICAL);
expect(e.wall.material.evenColor.getValue(date)).toEqual(Color.fromBytes(79, 80, 81, 78));
expect(e.wall.material.oddColor.getValue(date)).toEqual(Color.fromBytes(83, 84, 85, 82));
expect(e.wall.material.offset.getValue(date)).toEqual(1106.0);
expect(e.wall.material.repeat.getValue(date)).toEqual(1107.0);
expect(e = dataSource.entities.getById('material_wall_material_image_1108')).toBeDefined();
expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new Color(0.352941176470588, 0.356862745098039, 0.36078431372549, 0.349019607843137), 1e-14);
expect(e = dataSource.entities.getById('material_wall_material_grid_1113')).toBeDefined();
expect(e.wall.material.color.getValue(date)).toEqualEpsilon(new Color(0.372549019607843, 0.376470588235294, 0.380392156862745, 0.368627450980392), 1e-14);
expect(e = dataSource.entities.getById('material_wall_material_stripe_1118')).toBeDefined();
expect(e.wall.material.evenColor.getValue(date)).toEqualEpsilon(new Color(0.392156862745098, 0.396078431372549, 0.4, 0.388235294117647), 1e-14);
expect(e = dataSource.entities.getById('material_wall_material_stripe_1123')).toBeDefined();
expect(e.wall.material.oddColor.getValue(date)).toEqualEpsilon(new Color(0.411764705882353, 0.415686274509804, 0.419607843137255, 0.407843137254902), 1e-14);
expect(e = dataSource.entities.getById('constant1128')).toBeDefined();
expect(e.wall.outlineColor.getValue(date)).toEqualEpsilon(new Color(0.431372549019608, 0.435294117647059, 0.43921568627451, 0.427450980392157), 1e-14);
expect(e = dataSource.entities.getById('constant1133')).toBeDefined();
expect(e = dataSource.entities.getById('constant1138')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_image_1171')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_grid_1176')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_stripe_1181')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_lateralSurfaceMaterial_stripe_1186')).toBeDefined();
expect(e = dataSource.entities.getById('constant1191')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_image_1224')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_grid_1229')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_stripe_1234')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidSurfaceMaterial_stripe_1239')).toBeDefined();
expect(e = dataSource.entities.getById('constant1244')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_image_1277')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_grid_1282')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_1287')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_ellipsoidHorizonSurfaceMaterial_stripe_1292')).toBeDefined();
expect(e = dataSource.entities.getById('constant1297')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_image_1330')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_grid_1335')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_stripe_1340')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_domeSurfaceMaterial_stripe_1345')).toBeDefined();
expect(e = dataSource.entities.getById('constant1350')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_image'));
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_grid'));
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_stripe'));
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_image_1383')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_grid_1388')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_stripe_1393')).toBeDefined();
expect(e = dataSource.entities.getById('material_conicSensor_environmentOcclusionMaterial_stripe_1398')).toBeDefined();
expect(e = dataSource.entities.getById('constant1403')).toBeDefined();
expect(e = dataSource.entities.getById('constant1408')).toBeDefined();
expect(e = dataSource.entities.getById('constant1413')).toBeDefined();
expect(e = dataSource.entities.getById('constant1420')).toBeDefined();
expect(e = dataSource.entities.getById('constant1427')).toBeDefined();
expect(e = dataSource.entities.getById('constant1432')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_image_1465')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_grid_1470')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_stripe_1475')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_lateralSurfaceMaterial_stripe_1480')).toBeDefined();
expect(e = dataSource.entities.getById('constant1485')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_image_1518')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_grid_1523')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_stripe_1528')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidSurfaceMaterial_stripe_1533')).toBeDefined();
expect(e = dataSource.entities.getById('constant1538')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_image_1571')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_grid_1576')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_1581')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_ellipsoidHorizonSurfaceMaterial_stripe_1586')).toBeDefined();
expect(e = dataSource.entities.getById('constant1591')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_image_1624')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_grid_1629')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_stripe_1634')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_domeSurfaceMaterial_stripe_1639')).toBeDefined();
expect(e = dataSource.entities.getById('constant1644')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_image'));
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_grid'));
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_stripe'));
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_image_1677')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_grid_1682')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_stripe_1687')).toBeDefined();
expect(e = dataSource.entities.getById('material_customPatternSensor_environmentOcclusionMaterial_stripe_1692')).toBeDefined();
expect(e = dataSource.entities.getById('constant1697')).toBeDefined();
expect(e = dataSource.entities.getById('constant1702')).toBeDefined();
expect(e = dataSource.entities.getById('constant1707')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_image_1740')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_grid_1745')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_stripe_1750')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_lateralSurfaceMaterial_stripe_1755')).toBeDefined();
expect(e = dataSource.entities.getById('constant1760')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_image_1793')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_grid_1798')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_stripe_1803')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidSurfaceMaterial_stripe_1808')).toBeDefined();
expect(e = dataSource.entities.getById('constant1813')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_image_1846')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_grid_1851')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_1856')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_ellipsoidHorizonSurfaceMaterial_stripe_1861')).toBeDefined();
expect(e = dataSource.entities.getById('constant1866')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_image'));
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_grid'));
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_stripe'));
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_image_1899')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_grid_1904')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_stripe_1909')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_domeSurfaceMaterial_stripe_1914')).toBeDefined();
expect(e = dataSource.entities.getById('constant1919')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_image'));
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_grid'));
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_stripe'));
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_image_1952')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_grid_1957')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_stripe_1962')).toBeDefined();
expect(e = dataSource.entities.getById('material_rectangularSensor_environmentOcclusionMaterial_stripe_1967')).toBeDefined();
expect(e = dataSource.entities.getById('constant1972')).toBeDefined();
expect(e = dataSource.entities.getById('constant1977')).toBeDefined();
expect(e = dataSource.entities.getById('constant1982')).toBeDefined();
expect(e = dataSource.entities.getById('constant1989')).toBeDefined();
expect(e = dataSource.entities.getById('constant1996')).toBeDefined();
expect(e = dataSource.entities.getById('material_fan_material_image'));
expect(e = dataSource.entities.getById('material_fan_material_grid'));
expect(e = dataSource.entities.getById('material_fan_material_stripe'));
expect(e = dataSource.entities.getById('material_fan_material_image_2029')).toBeDefined();
expect(e = dataSource.entities.getById('material_fan_material_grid_2034')).toBeDefined();
expect(e = dataSource.entities.getById('material_fan_material_stripe_2039')).toBeDefined();
expect(e = dataSource.entities.getById('material_fan_material_stripe_2044')).toBeDefined();
expect(e = dataSource.entities.getById('constant2049')).toBeDefined();
expect(e = dataSource.entities.getById('constant2054')).toBeDefined();
expect(e = dataSource.entities.getById('constant2059')).toBeDefined();
expect(e = dataSource.entities.getById('constant2062')).toBeDefined();
expect(e = dataSource.entities.getById('constant2066')).toBeDefined();
expect(e = dataSource.entities.getById('ConstantPosition1')).toBeDefined();
expect(e.position.getValue(date)).toEqual(new Cartesian3(2070, 2071, 2072));
expect(e = dataSource.entities.getById('ConstantDouble1')).toBeDefined();
expect(e.billboard.scale.getValue(date)).toEqual(2073.0);
expect(e = dataSource.entities.getById('ConstantPosition2')).toBeDefined();
expect(e.position.getValue(date)).toEqual(new Cartesian3(2074, 2075, 2076));
expect(e = dataSource.entities.getById('ConstantDouble2')).toBeDefined();
expect(e.billboard.scale.getValue(date)).toEqual(2077.0);
expect(e = dataSource.entities.getById('Reference')).toBeDefined();
expect(e.description.getValue(date)).toEqual(constant.description.getValue(date));
expect(e.position.getValue(date)).toEqual(constant.position.getValue(date));
expect(e.orientation.getValue(date)).toEqual(constant.orientation.getValue(date));
expect(e.viewFrom.getValue(date)).toEqual(constant.viewFrom.getValue(date));
expect(e.billboard.show.getValue(date)).toEqual(constant.billboard.show.getValue(date));
expect(e.billboard.image.getValue(date)).toEqual(constant.billboard.image.getValue(date));
expect(e.billboard.scale.getValue(date)).toEqual(constant.billboard.scale.getValue(date));
expect(e.billboard.pixelOffset.getValue(date)).toEqual(constant.billboard.pixelOffset.getValue(date));
expect(e.billboard.eyeOffset.getValue(date)).toEqual(constant.billboard.eyeOffset.getValue(date));
expect(e.billboard.horizontalOrigin.getValue(date)).toEqual(constant.billboard.horizontalOrigin.getValue(date));
expect(e.billboard.verticalOrigin.getValue(date)).toEqual(constant.billboard.verticalOrigin.getValue(date));
expect(e.billboard.color.getValue(date)).toEqual(constant.billboard.color.getValue(date));
expect(e.billboard.rotation.getValue(date)).toEqual(constant.billboard.rotation.getValue(date));
expect(e.billboard.alignedAxis.getValue(date)).toEqual(constant.billboard.alignedAxis.getValue(date));
expect(e.billboard.sizeInMeters.getValue(date)).toEqual(constant.billboard.sizeInMeters.getValue(date));
expect(e.billboard.width.getValue(date)).toEqual(constant.billboard.width.getValue(date));
expect(e.billboard.height.getValue(date)).toEqual(constant.billboard.height.getValue(date));
expect(e.billboard.scaleByDistance.getValue(date)).toEqual(constant.billboard.scaleByDistance.getValue(date));
expect(e.billboard.translucencyByDistance.getValue(date)).toEqual(constant.billboard.translucencyByDistance.getValue(date));
expect(e.billboard.pixelOffsetScaleByDistance.getValue(date)).toEqual(constant.billboard.pixelOffsetScaleByDistance.getValue(date));
expect(e.billboard.imageSubRegion.getValue(date)).toEqual(constant.billboard.imageSubRegion.getValue(date));
expect(e.box.show.getValue(date)).toEqual(constant.box.show.getValue(date));
expect(e.box.dimensions.getValue(date)).toEqual(constant.box.dimensions.getValue(date));
expect(e.box.fill.getValue(date)).toEqual(constant.box.fill.getValue(date));
expect(e.box.material.color.getValue(date)).toEqual(constant.box.material.color.getValue(date));
expect(e.box.outline.getValue(date)).toEqual(constant.box.outline.getValue(date));
expect(e.box.outlineColor.getValue(date)).toEqual(constant.box.outlineColor.getValue(date));
expect(e.box.outlineWidth.getValue(date)).toEqual(constant.box.outlineWidth.getValue(date));
expect(e.corridor.show.getValue(date)).toEqual(constant.corridor.show.getValue(date));
expect(e.corridor.positions.getValue(date)).toEqual([dataSource.entities.getById('ConstantPosition1').position.getValue(date), dataSource.entities.getById('ConstantPosition2').position.getValue(date)]);
expect(e.corridor.width.getValue(date)).toEqual(constant.corridor.width.getValue(date));
expect(e.corridor.height.getValue(date)).toEqual(constant.corridor.height.getValue(date));
expect(e.corridor.extrudedHeight.getValue(date)).toEqual(constant.corridor.extrudedHeight.getValue(date));
expect(e.corridor.cornerType.getValue(date)).toEqual(constant.corridor.cornerType.getValue(date));
expect(e.corridor.granularity.getValue(date)).toEqual(constant.corridor.granularity.getValue(date));
expect(e.corridor.fill.getValue(date)).toEqual(constant.corridor.fill.getValue(date));
expect(e.corridor.material.color.getValue(date)).toEqual(constant.corridor.material.color.getValue(date));
expect(e.corridor.outline.getValue(date)).toEqual(constant.corridor.outline.getValue(date));
expect(e.corridor.outlineColor.getValue(date)).toEqual(constant.corridor.outlineColor.getValue(date));
expect(e.corridor.outlineWidth.getValue(date)).toEqual(constant.corridor.outlineWidth.getValue(date));
expect(e.cylinder.show.getValue(date)).toEqual(constant.cylinder.show.getValue(date));
expect(e.cylinder.length.getValue(date)).toEqual(constant.cylinder.length.getValue(date));
expect(e.cylinder.topRadius.getValue(date)).toEqual(constant.cylinder.topRadius.getValue(date));
expect(e.cylinder.bottomRadius.getValue(date)).toEqual(constant.cylinder.bottomRadius.getValue(date));
expect(e.cylinder.fill.getValue(date)).toEqual(constant.cylinder.fill.getValue(date));
expect(e.cylinder.material.color.getValue(date)).toEqual(constant.cylinder.material.color.getValue(date));
expect(e.cylinder.outline.getValue(date)).toEqual(constant.cylinder.outline.getValue(date));
expect(e.cylinder.outlineColor.getValue(date)).toEqual(constant.cylinder.outlineColor.getValue(date));
expect(e.cylinder.outlineWidth.getValue(date)).toEqual(constant.cylinder.outlineWidth.getValue(date));
expect(e.cylinder.numberOfVerticalLines.getValue(date)).toEqual(constant.cylinder.numberOfVerticalLines.getValue(date));
expect(e.cylinder.slices.getValue(date)).toEqual(constant.cylinder.slices.getValue(date));
expect(e.ellipse.show.getValue(date)).toEqual(constant.ellipse.show.getValue(date));
expect(e.ellipse.semiMajorAxis.getValue(date)).toEqual(constant.ellipse.semiMajorAxis.getValue(date));
expect(e.ellipse.semiMinorAxis.getValue(date)).toEqual(constant.ellipse.semiMinorAxis.getValue(date));
expect(e.ellipse.height.getValue(date)).toEqual(constant.ellipse.height.getValue(date));
expect(e.ellipse.extrudedHeight.getValue(date)).toEqual(constant.ellipse.extrudedHeight.getValue(date));
expect(e.ellipse.rotation.getValue(date)).toEqual(constant.ellipse.rotation.getValue(date));
expect(e.ellipse.stRotation.getValue(date)).toEqual(constant.ellipse.stRotation.getValue(date));
expect(e.ellipse.granularity.getValue(date)).toEqual(constant.ellipse.granularity.getValue(date));
expect(e.ellipse.fill.getValue(date)).toEqual(constant.ellipse.fill.getValue(date));
expect(e.ellipse.material.color.getValue(date)).toEqual(constant.ellipse.material.color.getValue(date));
expect(e.ellipse.outline.getValue(date)).toEqual(constant.ellipse.outline.getValue(date));
expect(e.ellipse.outlineColor.getValue(date)).toEqual(constant.ellipse.outlineColor.getValue(date));
expect(e.ellipse.outlineWidth.getValue(date)).toEqual(constant.ellipse.outlineWidth.getValue(date));
expect(e.ellipse.numberOfVerticalLines.getValue(date)).toEqual(constant.ellipse.numberOfVerticalLines.getValue(date));
expect(e.ellipsoid.show.getValue(date)).toEqual(constant.ellipsoid.show.getValue(date));
expect(e.ellipsoid.radii.getValue(date)).toEqual(constant.ellipsoid.radii.getValue(date));
expect(e.ellipsoid.fill.getValue(date)).toEqual(constant.ellipsoid.fill.getValue(date));
expect(e.ellipsoid.material.color.getValue(date)).toEqual(constant.ellipsoid.material.color.getValue(date));
expect(e.ellipsoid.outline.getValue(date)).toEqual(constant.ellipsoid.outline.getValue(date));
expect(e.ellipsoid.outlineColor.getValue(date)).toEqual(constant.ellipsoid.outlineColor.getValue(date));
expect(e.ellipsoid.outlineWidth.getValue(date)).toEqual(constant.ellipsoid.outlineWidth.getValue(date));
expect(e.ellipsoid.stackPartitions.getValue(date)).toEqual(constant.ellipsoid.stackPartitions.getValue(date));
expect(e.ellipsoid.slicePartitions.getValue(date)).toEqual(constant.ellipsoid.slicePartitions.getValue(date));
expect(e.ellipsoid.subdivisions.getValue(date)).toEqual(constant.ellipsoid.subdivisions.getValue(date));
expect(e.label.show.getValue(date)).toEqual(constant.label.show.getValue(date));
expect(e.label.text.getValue(date)).toEqual(constant.label.text.getValue(date));
expect(e.label.font.getValue(date)).toEqual(constant.label.font.getValue(date));
expect(e.label.style.getValue(date)).toEqual(constant.label.style.getValue(date));
expect(e.label.scale.getValue(date)).toEqual(constant.label.scale.getValue(date));
expect(e.label.pixelOffset.getValue(date)).toEqual(constant.label.pixelOffset.getValue(date));
expect(e.label.eyeOffset.getValue(date)).toEqual(constant.label.eyeOffset.getValue(date));
expect(e.label.horizontalOrigin.getValue(date)).toEqual(constant.label.horizontalOrigin.getValue(date));
expect(e.label.verticalOrigin.getValue(date)).toEqual(constant.label.verticalOrigin.getValue(date));
expect(e.label.fillColor.getValue(date)).toEqual(constant.label.fillColor.getValue(date));
expect(e.label.outlineColor.getValue(date)).toEqual(constant.label.outlineColor.getValue(date));
expect(e.label.outlineWidth.getValue(date)).toEqual(constant.label.outlineWidth.getValue(date));
expect(e.label.translucencyByDistance.getValue(date)).toEqual(constant.label.translucencyByDistance.getValue(date));
expect(e.label.pixelOffsetScaleByDistance.getValue(date)).toEqual(constant.label.pixelOffsetScaleByDistance.getValue(date));
expect(e.model.show.getValue(date)).toEqual(constant.model.show.getValue(date));
expect(e.model.uri.getValue(date)).toEqual(constant.model.uri.getValue(date));
expect(e.model.scale.getValue(date)).toEqual(constant.model.scale.getValue(date));
expect(e.model.minimumPixelSize.getValue(date)).toEqual(constant.model.minimumPixelSize.getValue(date));
expect(e.model.maximumScale.getValue(date)).toEqual(constant.model.maximumScale.getValue(date));
expect(e.model.incrementallyLoadTextures.getValue(date)).toEqual(constant.model.incrementallyLoadTextures.getValue(date));
expect(e.model.runAnimations.getValue(date)).toEqual(constant.model.runAnimations.getValue(date));
expect(e.model.nodeTransformations.referenceProp.translation.getValue(date)).toEqual(constant.model.nodeTransformations.prop.translation.getValue(date));
expect(e.model.nodeTransformations.referenceProp.rotation.getValue(date)).toEqual(constant.model.nodeTransformations.prop.rotation.getValue(date));
expect(e.model.nodeTransformations.referenceProp.scale.getValue(date)).toEqual(constant.model.nodeTransformations.prop.scale.getValue(date));
expect(e.path.show.getValue(date)).toEqual(constant.path.show.getValue(date));
expect(e.path.width.getValue(date)).toEqual(constant.path.width.getValue(date));
expect(e.path.resolution.getValue(date)).toEqual(constant.path.resolution.getValue(date));
expect(e.path.leadTime.getValue(date)).toEqual(constant.path.leadTime.getValue(date));
expect(e.path.trailTime.getValue(date)).toEqual(constant.path.trailTime.getValue(date));
expect(e.path.material.color.getValue(date)).toEqual(constant.path.material.color.getValue(date));
expect(e.point.show.getValue(date)).toEqual(constant.point.show.getValue(date));
expect(e.point.pixelSize.getValue(date)).toEqual(constant.point.pixelSize.getValue(date));
expect(e.point.color.getValue(date)).toEqual(constant.point.color.getValue(date));
expect(e.point.outlineColor.getValue(date)).toEqual(constant.point.outlineColor.getValue(date));
expect(e.point.outlineWidth.getValue(date)).toEqual(constant.point.outlineWidth.getValue(date));
expect(e.point.scaleByDistance.getValue(date)).toEqual(constant.point.scaleByDistance.getValue(date));
expect(e.point.translucencyByDistance.getValue(date)).toEqual(constant.point.translucencyByDistance.getValue(date));
expect(e.polygon.show.getValue(date)).toEqual(constant.polygon.show.getValue(date));
expect(e.polygon.hierarchy.getValue(date)).toEqual([dataSource.entities.getById('ConstantPosition1').position.getValue(date), dataSource.entities.getById('ConstantPosition2').position.getValue(date)]);
expect(e.polygon.height.getValue(date)).toEqual(constant.polygon.height.getValue(date));
expect(e.polygon.extrudedHeight.getValue(date)).toEqual(constant.polygon.extrudedHeight.getValue(date));
expect(e.polygon.stRotation.getValue(date)).toEqual(constant.polygon.stRotation.getValue(date));
expect(e.polygon.granularity.getValue(date)).toEqual(constant.polygon.granularity.getValue(date));
expect(e.polygon.fill.getValue(date)).toEqual(constant.polygon.fill.getValue(date));
expect(e.polygon.material.color.getValue(date)).toEqual(constant.polygon.material.color.getValue(date));
expect(e.polygon.outline.getValue(date)).toEqual(constant.polygon.outline.getValue(date));
expect(e.polygon.outlineColor.getValue(date)).toEqual(constant.polygon.outlineColor.getValue(date));
expect(e.polygon.outlineWidth.getValue(date)).toEqual(constant.polygon.outlineWidth.getValue(date));
expect(e.polygon.perPositionHeight.getValue(date)).toEqual(constant.polygon.perPositionHeight.getValue(date));
expect(e.polygon.closeTop.getValue(date)).toEqual(constant.polygon.closeTop.getValue(date));
expect(e.polygon.closeBottom.getValue(date)).toEqual(constant.polygon.closeBottom.getValue(date));
expect(e.polyline.show.getValue(date)).toEqual(constant.polyline.show.getValue(date));
expect(e.polyline.positions.getValue(date)).toEqual([dataSource.entities.getById('ConstantPosition1').position.getValue(date), dataSource.entities.getById('ConstantPosition2').position.getValue(date)]);
expect(e.polyline.width.getValue(date)).toEqual(constant.polyline.width.getValue(date));
expect(e.polyline.granularity.getValue(date)).toEqual(constant.polyline.granularity.getValue(date));
expect(e.polyline.material.color.getValue(date)).toEqual(constant.polyline.material.color.getValue(date));
expect(e.polyline.followSurface.getValue(date)).toEqual(constant.polyline.followSurface.getValue(date));
expect(e.rectangle.show.getValue(date)).toEqual(constant.rectangle.show.getValue(date));
expect(e.rectangle.coordinates.getValue(date)).toEqual(constant.rectangle.coordinates.getValue(date));
expect(e.rectangle.height.getValue(date)).toEqual(constant.rectangle.height.getValue(date));
expect(e.rectangle.extrudedHeight.getValue(date)).toEqual(constant.rectangle.extrudedHeight.getValue(date));
expect(e.rectangle.rotation.getValue(date)).toEqual(constant.rectangle.rotation.getValue(date));
expect(e.rectangle.stRotation.getValue(date)).toEqual(constant.rectangle.stRotation.getValue(date));
expect(e.rectangle.granularity.getValue(date)).toEqual(constant.rectangle.granularity.getValue(date));
expect(e.rectangle.fill.getValue(date)).toEqual(constant.rectangle.fill.getValue(date));
expect(e.rectangle.material.color.getValue(date)).toEqual(constant.rectangle.material.color.getValue(date));
expect(e.rectangle.outline.getValue(date)).toEqual(constant.rectangle.outline.getValue(date));
expect(e.rectangle.outlineColor.getValue(date)).toEqual(constant.rectangle.outlineColor.getValue(date));
expect(e.rectangle.outlineWidth.getValue(date)).toEqual(constant.rectangle.outlineWidth.getValue(date));
expect(e.rectangle.closeTop.getValue(date)).toEqual(constant.rectangle.closeTop.getValue(date));
expect(e.rectangle.closeBottom.getValue(date)).toEqual(constant.rectangle.closeBottom.getValue(date));
expect(e.wall.show.getValue(date)).toEqual(constant.wall.show.getValue(date));
expect(e.wall.positions.getValue(date)).toEqual([dataSource.entities.getById('ConstantPosition1').position.getValue(date), dataSource.entities.getById('ConstantPosition2').position.getValue(date)]);
expect(e.wall.minimumHeights.getValue(date)).toEqual([dataSource.entities.getById('ConstantDouble1').billboard.scale.getValue(date), dataSource.entities.getById('ConstantDouble2').billboard.scale.getValue(date)]);
expect(e.wall.maximumHeights.getValue(date)).toEqual([dataSource.entities.getById('ConstantDouble1').billboard.scale.getValue(date), dataSource.entities.getById('ConstantDouble2').billboard.scale.getValue(date)]);
expect(e.wall.granularity.getValue(date)).toEqual(constant.wall.granularity.getValue(date));
expect(e.wall.fill.getValue(date)).toEqual(constant.wall.fill.getValue(date));
expect(e.wall.material.color.getValue(date)).toEqual(constant.wall.material.color.getValue(date));
expect(e.wall.outline.getValue(date)).toEqual(constant.wall.outline.getValue(date));
expect(e.wall.outlineColor.getValue(date)).toEqual(constant.wall.outlineColor.getValue(date));
expect(e.wall.outlineWidth.getValue(date)).toEqual(constant.wall.outlineWidth.getValue(date));
expect(e = dataSource.entities.getById('reference2078')).toBeDefined();
expect(e.box.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_image').box.material.image.getValue(date));
expect(e.box.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_image').box.material.repeat.getValue(date));
expect(e.box.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_image').box.material.color.getValue(date));
expect(e.box.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_image').box.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2079')).toBeDefined();
expect(e.box.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_grid').box.material.color.getValue(date));
expect(e.box.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_grid').box.material.cellAlpha.getValue(date));
expect(e.box.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_grid').box.material.lineCount.getValue(date));
expect(e.box.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_grid').box.material.lineThickness.getValue(date));
expect(e.box.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_grid').box.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2080')).toBeDefined();
expect(e.box.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_stripe').box.material.orientation.getValue(date));
expect(e.box.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_stripe').box.material.evenColor.getValue(date));
expect(e.box.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_stripe').box.material.oddColor.getValue(date));
expect(e.box.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_stripe').box.material.offset.getValue(date));
expect(e.box.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_box_material_stripe').box.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2081')).toBeDefined();
expect(e.corridor.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_image').corridor.material.image.getValue(date));
expect(e.corridor.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_image').corridor.material.repeat.getValue(date));
expect(e.corridor.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_image').corridor.material.color.getValue(date));
expect(e.corridor.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_image').corridor.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2082')).toBeDefined();
expect(e.corridor.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_grid').corridor.material.color.getValue(date));
expect(e.corridor.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_grid').corridor.material.cellAlpha.getValue(date));
expect(e.corridor.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_grid').corridor.material.lineCount.getValue(date));
expect(e.corridor.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_grid').corridor.material.lineThickness.getValue(date));
expect(e.corridor.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_grid').corridor.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2083')).toBeDefined();
expect(e.corridor.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_stripe').corridor.material.orientation.getValue(date));
expect(e.corridor.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_stripe').corridor.material.evenColor.getValue(date));
expect(e.corridor.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_stripe').corridor.material.oddColor.getValue(date));
expect(e.corridor.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_stripe').corridor.material.offset.getValue(date));
expect(e.corridor.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_corridor_material_stripe').corridor.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2084')).toBeDefined();
expect(e.cylinder.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_image').cylinder.material.image.getValue(date));
expect(e.cylinder.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_image').cylinder.material.repeat.getValue(date));
expect(e.cylinder.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_image').cylinder.material.color.getValue(date));
expect(e.cylinder.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_image').cylinder.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2085')).toBeDefined();
expect(e.cylinder.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_grid').cylinder.material.color.getValue(date));
expect(e.cylinder.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_grid').cylinder.material.cellAlpha.getValue(date));
expect(e.cylinder.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_grid').cylinder.material.lineCount.getValue(date));
expect(e.cylinder.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_grid').cylinder.material.lineThickness.getValue(date));
expect(e.cylinder.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_grid').cylinder.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2086')).toBeDefined();
expect(e.cylinder.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_stripe').cylinder.material.orientation.getValue(date));
expect(e.cylinder.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_stripe').cylinder.material.evenColor.getValue(date));
expect(e.cylinder.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_stripe').cylinder.material.oddColor.getValue(date));
expect(e.cylinder.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_stripe').cylinder.material.offset.getValue(date));
expect(e.cylinder.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_cylinder_material_stripe').cylinder.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2087')).toBeDefined();
expect(e.ellipse.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_image').ellipse.material.image.getValue(date));
expect(e.ellipse.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_image').ellipse.material.repeat.getValue(date));
expect(e.ellipse.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_image').ellipse.material.color.getValue(date));
expect(e.ellipse.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_image').ellipse.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2088')).toBeDefined();
expect(e.ellipse.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_grid').ellipse.material.color.getValue(date));
expect(e.ellipse.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_grid').ellipse.material.cellAlpha.getValue(date));
expect(e.ellipse.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_grid').ellipse.material.lineCount.getValue(date));
expect(e.ellipse.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_grid').ellipse.material.lineThickness.getValue(date));
expect(e.ellipse.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_grid').ellipse.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2089')).toBeDefined();
expect(e.ellipse.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_stripe').ellipse.material.orientation.getValue(date));
expect(e.ellipse.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_stripe').ellipse.material.evenColor.getValue(date));
expect(e.ellipse.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_stripe').ellipse.material.oddColor.getValue(date));
expect(e.ellipse.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_stripe').ellipse.material.offset.getValue(date));
expect(e.ellipse.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_ellipse_material_stripe').ellipse.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2090')).toBeDefined();
expect(e.ellipsoid.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_image').ellipsoid.material.image.getValue(date));
expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_image').ellipsoid.material.repeat.getValue(date));
expect(e.ellipsoid.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_image').ellipsoid.material.color.getValue(date));
expect(e.ellipsoid.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_image').ellipsoid.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2091')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_grid').ellipsoid.material.color.getValue(date));
expect(e.ellipsoid.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_grid').ellipsoid.material.cellAlpha.getValue(date));
expect(e.ellipsoid.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_grid').ellipsoid.material.lineCount.getValue(date));
expect(e.ellipsoid.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_grid').ellipsoid.material.lineThickness.getValue(date));
expect(e.ellipsoid.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_grid').ellipsoid.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2092')).toBeDefined();
expect(e.ellipsoid.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_stripe').ellipsoid.material.orientation.getValue(date));
expect(e.ellipsoid.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_stripe').ellipsoid.material.evenColor.getValue(date));
expect(e.ellipsoid.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_stripe').ellipsoid.material.oddColor.getValue(date));
expect(e.ellipsoid.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_stripe').ellipsoid.material.offset.getValue(date));
expect(e.ellipsoid.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_ellipsoid_material_stripe').ellipsoid.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2093')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineOutline').path.material.color.getValue(date));
expect(e.path.material.outlineColor.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineOutline').path.material.outlineColor.getValue(date));
expect(e.path.material.outlineWidth.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineOutline').path.material.outlineWidth.getValue(date));
expect(e = dataSource.entities.getById('reference2094')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineArrow').path.material.color.getValue(date));
expect(e = dataSource.entities.getById('reference2095')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineGlow').path.material.color.getValue(date));
expect(e.path.material.glowPower.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_polylineGlow').path.material.glowPower.getValue(date));
expect(e = dataSource.entities.getById('reference2096')).toBeDefined();
expect(e.path.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_image').path.material.image.getValue(date));
expect(e.path.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_image').path.material.repeat.getValue(date));
expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_image').path.material.color.getValue(date));
expect(e.path.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_image').path.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2097')).toBeDefined();
expect(e.path.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_grid').path.material.color.getValue(date));
expect(e.path.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_grid').path.material.cellAlpha.getValue(date));
expect(e.path.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_grid').path.material.lineCount.getValue(date));
expect(e.path.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_grid').path.material.lineThickness.getValue(date));
expect(e.path.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_grid').path.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2098')).toBeDefined();
expect(e.path.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_stripe').path.material.orientation.getValue(date));
expect(e.path.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_stripe').path.material.evenColor.getValue(date));
expect(e.path.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_stripe').path.material.oddColor.getValue(date));
expect(e.path.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_stripe').path.material.offset.getValue(date));
expect(e.path.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_path_material_stripe').path.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2099')).toBeDefined();
expect(e.polygon.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_image').polygon.material.image.getValue(date));
expect(e.polygon.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_image').polygon.material.repeat.getValue(date));
expect(e.polygon.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_image').polygon.material.color.getValue(date));
expect(e.polygon.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_image').polygon.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2100')).toBeDefined();
expect(e.polygon.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_grid').polygon.material.color.getValue(date));
expect(e.polygon.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_grid').polygon.material.cellAlpha.getValue(date));
expect(e.polygon.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_grid').polygon.material.lineCount.getValue(date));
expect(e.polygon.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_grid').polygon.material.lineThickness.getValue(date));
expect(e.polygon.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_grid').polygon.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2101')).toBeDefined();
expect(e.polygon.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_stripe').polygon.material.orientation.getValue(date));
expect(e.polygon.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_stripe').polygon.material.evenColor.getValue(date));
expect(e.polygon.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_stripe').polygon.material.oddColor.getValue(date));
expect(e.polygon.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_stripe').polygon.material.offset.getValue(date));
expect(e.polygon.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_polygon_material_stripe').polygon.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2102')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineOutline').polyline.material.color.getValue(date));
expect(e.polyline.material.outlineColor.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineOutline').polyline.material.outlineColor.getValue(date));
expect(e.polyline.material.outlineWidth.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineOutline').polyline.material.outlineWidth.getValue(date));
expect(e = dataSource.entities.getById('reference2103')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineArrow').polyline.material.color.getValue(date));
expect(e = dataSource.entities.getById('reference2104')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineGlow').polyline.material.color.getValue(date));
expect(e.polyline.material.glowPower.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_polylineGlow').polyline.material.glowPower.getValue(date));
expect(e = dataSource.entities.getById('reference2105')).toBeDefined();
expect(e.polyline.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_image').polyline.material.image.getValue(date));
expect(e.polyline.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_image').polyline.material.repeat.getValue(date));
expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_image').polyline.material.color.getValue(date));
expect(e.polyline.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_image').polyline.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2106')).toBeDefined();
expect(e.polyline.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_grid').polyline.material.color.getValue(date));
expect(e.polyline.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_grid').polyline.material.cellAlpha.getValue(date));
expect(e.polyline.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_grid').polyline.material.lineCount.getValue(date));
expect(e.polyline.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_grid').polyline.material.lineThickness.getValue(date));
expect(e.polyline.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_grid').polyline.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2107')).toBeDefined();
expect(e.polyline.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_stripe').polyline.material.orientation.getValue(date));
expect(e.polyline.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_stripe').polyline.material.evenColor.getValue(date));
expect(e.polyline.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_stripe').polyline.material.oddColor.getValue(date));
expect(e.polyline.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_stripe').polyline.material.offset.getValue(date));
expect(e.polyline.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_polyline_material_stripe').polyline.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2108')).toBeDefined();
expect(e.rectangle.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_image').rectangle.material.image.getValue(date));
expect(e.rectangle.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_image').rectangle.material.repeat.getValue(date));
expect(e.rectangle.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_image').rectangle.material.color.getValue(date));
expect(e.rectangle.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_image').rectangle.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2109')).toBeDefined();
expect(e.rectangle.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_grid').rectangle.material.color.getValue(date));
expect(e.rectangle.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_grid').rectangle.material.cellAlpha.getValue(date));
expect(e.rectangle.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_grid').rectangle.material.lineCount.getValue(date));
expect(e.rectangle.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_grid').rectangle.material.lineThickness.getValue(date));
expect(e.rectangle.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_grid').rectangle.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2110')).toBeDefined();
expect(e.rectangle.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_stripe').rectangle.material.orientation.getValue(date));
expect(e.rectangle.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_stripe').rectangle.material.evenColor.getValue(date));
expect(e.rectangle.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_stripe').rectangle.material.oddColor.getValue(date));
expect(e.rectangle.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_stripe').rectangle.material.offset.getValue(date));
expect(e.rectangle.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_rectangle_material_stripe').rectangle.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2111')).toBeDefined();
expect(e.wall.material.image.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_image').wall.material.image.getValue(date));
expect(e.wall.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_image').wall.material.repeat.getValue(date));
expect(e.wall.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_image').wall.material.color.getValue(date));
expect(e.wall.material.transparent.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_image').wall.material.transparent.getValue(date));
expect(e = dataSource.entities.getById('reference2112')).toBeDefined();
expect(e.wall.material.color.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_grid').wall.material.color.getValue(date));
expect(e.wall.material.cellAlpha.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_grid').wall.material.cellAlpha.getValue(date));
expect(e.wall.material.lineCount.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_grid').wall.material.lineCount.getValue(date));
expect(e.wall.material.lineThickness.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_grid').wall.material.lineThickness.getValue(date));
expect(e.wall.material.lineOffset.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_grid').wall.material.lineOffset.getValue(date));
expect(e = dataSource.entities.getById('reference2113')).toBeDefined();
expect(e.wall.material.orientation.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_stripe').wall.material.orientation.getValue(date));
expect(e.wall.material.evenColor.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_stripe').wall.material.evenColor.getValue(date));
expect(e.wall.material.oddColor.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_stripe').wall.material.oddColor.getValue(date));
expect(e.wall.material.offset.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_stripe').wall.material.offset.getValue(date));
expect(e.wall.material.repeat.getValue(date)).toEqual(dataSource.entities.getById('material_wall_material_stripe').wall.material.repeat.getValue(date));
expect(e = dataSource.entities.getById('reference2114')).toBeDefined();
expect(e = dataSource.entities.getById('reference2115')).toBeDefined();
expect(e = dataSource.entities.getById('reference2116')).toBeDefined();
expect(e = dataSource.entities.getById('reference2117')).toBeDefined();
expect(e = dataSource.entities.getById('reference2118')).toBeDefined();
expect(e = dataSource.entities.getById('reference2119')).toBeDefined();
expect(e = dataSource.entities.getById('reference2120')).toBeDefined();
expect(e = dataSource.entities.getById('reference2121')).toBeDefined();
expect(e = dataSource.entities.getById('reference2122')).toBeDefined();
expect(e = dataSource.entities.getById('reference2123')).toBeDefined();
expect(e = dataSource.entities.getById('reference2124')).toBeDefined();
expect(e = dataSource.entities.getById('reference2125')).toBeDefined();
expect(e = dataSource.entities.getById('reference2126')).toBeDefined();
expect(e = dataSource.entities.getById('reference2127')).toBeDefined();
expect(e = dataSource.entities.getById('reference2128')).toBeDefined();
expect(e = dataSource.entities.getById('reference2129')).toBeDefined();
expect(e = dataSource.entities.getById('reference2130')).toBeDefined();
expect(e = dataSource.entities.getById('reference2131')).toBeDefined();
expect(e = dataSource.entities.getById('reference2132')).toBeDefined();
expect(e = dataSource.entities.getById('reference2133')).toBeDefined();
expect(e = dataSource.entities.getById('reference2134')).toBeDefined();
expect(e = dataSource.entities.getById('reference2135')).toBeDefined();
expect(e = dataSource.entities.getById('reference2136')).toBeDefined();
expect(e = dataSource.entities.getById('reference2137')).toBeDefined();
expect(e = dataSource.entities.getById('reference2138')).toBeDefined();
expect(e = dataSource.entities.getById('reference2139')).toBeDefined();
expect(e = dataSource.entities.getById('reference2140')).toBeDefined();
expect(e = dataSource.entities.getById('reference2141')).toBeDefined();
expect(e = dataSource.entities.getById('reference2142')).toBeDefined();
expect(e = dataSource.entities.getById('reference2143')).toBeDefined();
expect(e = dataSource.entities.getById('reference2144')).toBeDefined();
expect(e = dataSource.entities.getById('reference2145')).toBeDefined();
expect(e = dataSource.entities.getById('reference2146')).toBeDefined();
expect(e = dataSource.entities.getById('reference2147')).toBeDefined();
expect(e = dataSource.entities.getById('reference2148')).toBeDefined();
expect(e = dataSource.entities.getById('reference2149')).toBeDefined();
expect(e = dataSource.entities.getById('reference2150')).toBeDefined();
expect(e = dataSource.entities.getById('reference2151')).toBeDefined();
expect(e = dataSource.entities.getById('reference2152')).toBeDefined();
expect(e = dataSource.entities.getById('reference2153')).toBeDefined();
expect(e = dataSource.entities.getById('reference2154')).toBeDefined();
expect(e = dataSource.entities.getById('reference2155')).toBeDefined();
expect(e = dataSource.entities.getById('reference2156')).toBeDefined();
expect(e = dataSource.entities.getById('reference2157')).toBeDefined();
expect(e = dataSource.entities.getById('reference2158')).toBeDefined();
expect(e = dataSource.entities.getById('reference2159')).toBeDefined();
expect(e = dataSource.entities.getById('reference2160')).toBeDefined();
expect(e = dataSource.entities.getById('reference2161')).toBeDefined();
expect(e = dataSource.entities.getById('Sampled')).toBeDefined();
expect(e.position.getValue(documentStartDate)).toEqual(new Cartesian3(2162, 2163, 2164));
expect(e.position.getValue(documentStopDate)).toEqual(new Cartesian3(2165, 2166, 2167));
expect(e.orientation.getValue(documentStartDate)).toEqualEpsilon(new Quaternion(0.49988469969616, 0.500115167515292, 0.500345635334423, 0.499654231877029), 1e-14);
expect(e.orientation.getValue(documentStopDate)).toEqualEpsilon(new Quaternion(0.499884912010944, 0.500114955688813, 0.500344999366683, 0.499654868333074), 1e-14);
expect(e.viewFrom.getValue(documentStartDate)).toEqual(new Cartesian3(2176, 2177, 2178));
expect(e.viewFrom.getValue(documentStopDate)).toEqual(new Cartesian3(2179, 2180, 2181));
expect(e.billboard.scale.getValue(documentStartDate)).toEqual(2182.0);
expect(e.billboard.scale.getValue(documentStopDate)).toEqual(2183.0);
expect(e.billboard.pixelOffset.getValue(documentStartDate)).toEqual(new Cartesian2(2184, 2185));
expect(e.billboard.pixelOffset.getValue(documentStopDate)).toEqual(new Cartesian2(2186, 2187));
expect(e.billboard.eyeOffset.getValue(documentStartDate)).toEqual(new Cartesian3(2188, 2189, 2190));
expect(e.billboard.eyeOffset.getValue(documentStopDate)).toEqual(new Cartesian3(2191, 2192, 2193));
expect(e.billboard.color.getValue(documentStartDate)).toEqual(Color.fromBytes(155, 156, 157, 154));
expect(e.billboard.color.getValue(documentStopDate)).toEqual(Color.fromBytes(159, 160, 161, 158));
expect(e.billboard.rotation.getValue(documentStartDate)).toEqual(2202.0);
expect(e.billboard.rotation.getValue(documentStopDate)).toEqual(2203.0);
expect(e.billboard.alignedAxis.getValue(documentStartDate)).toEqual(new Cartesian3(2204, 2205, 2206));
expect(e.billboard.alignedAxis.getValue(documentStopDate)).toEqual(new Cartesian3(2207, 2208, 2209));
expect(e.billboard.width.getValue(documentStartDate)).toEqual(2210.0);
expect(e.billboard.width.getValue(documentStopDate)).toEqual(2211.0);
expect(e.billboard.height.getValue(documentStartDate)).toEqual(2212.0);
expect(e.billboard.height.getValue(documentStopDate)).toEqual(2213.0);
expect(e.billboard.scaleByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2214, 2215, 2216, 2217));
expect(e.billboard.scaleByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2218, 2219, 2220, 2221));
expect(e.billboard.translucencyByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2222, 2223, 2224, 2225));
expect(e.billboard.translucencyByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2226, 2227, 2228, 2229));
expect(e.billboard.pixelOffsetScaleByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2230, 2231, 2232, 2233));
expect(e.billboard.pixelOffsetScaleByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2234, 2235, 2236, 2237));
expect(e.billboard.imageSubRegion.getValue(documentStartDate)).toEqual(new BoundingRectangle(2238, 2239, 2240, 2241));
expect(e.billboard.imageSubRegion.getValue(documentStopDate)).toEqual(new BoundingRectangle(2242, 2243, 2244, 2245));
expect(e.box.dimensions.getValue(documentStartDate)).toEqual(new Cartesian3(2246, 2247, 2248));
expect(e.box.dimensions.getValue(documentStopDate)).toEqual(new Cartesian3(2249, 2250, 2251));
expect(e.box.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(213, 214, 215, 212));
expect(e.box.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(217, 218, 219, 216));
expect(e.box.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(221, 222, 223, 220));
expect(e.box.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(225, 226, 227, 224));
expect(e.box.outlineWidth.getValue(documentStartDate)).toEqual(2268.0);
expect(e.box.outlineWidth.getValue(documentStopDate)).toEqual(2269.0);
expect(e.corridor.width.getValue(documentStartDate)).toEqual(2270.0);
expect(e.corridor.width.getValue(documentStopDate)).toEqual(2271.0);
expect(e.corridor.height.getValue(documentStartDate)).toEqual(2272.0);
expect(e.corridor.height.getValue(documentStopDate)).toEqual(2273.0);
expect(e.corridor.extrudedHeight.getValue(documentStartDate)).toEqual(2274.0);
expect(e.corridor.extrudedHeight.getValue(documentStopDate)).toEqual(2275.0);
expect(e.corridor.granularity.getValue(documentStartDate)).toEqual(2276.0);
expect(e.corridor.granularity.getValue(documentStopDate)).toEqual(2277.0);
expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(239, 240, 241, 238));
expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(243, 244, 245, 242));
expect(e.corridor.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(247, 248, 249, 246));
expect(e.corridor.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(251, 252, 253, 250));
expect(e.corridor.outlineWidth.getValue(documentStartDate)).toEqual(2294.0);
expect(e.corridor.outlineWidth.getValue(documentStopDate)).toEqual(2295.0);
expect(e.cylinder.length.getValue(documentStartDate)).toEqual(2296.0);
expect(e.cylinder.length.getValue(documentStopDate)).toEqual(2297.0);
expect(e.cylinder.topRadius.getValue(documentStartDate)).toEqual(2298.0);
expect(e.cylinder.topRadius.getValue(documentStopDate)).toEqual(2299.0);
expect(e.cylinder.bottomRadius.getValue(documentStartDate)).toEqual(2300.0);
expect(e.cylinder.bottomRadius.getValue(documentStopDate)).toEqual(2301.0);
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(8, 9, 10, 7));
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(12, 13, 14, 11));
expect(e.cylinder.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(16, 17, 18, 15));
expect(e.cylinder.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(20, 21, 22, 19));
expect(e.cylinder.outlineWidth.getValue(documentStartDate)).toEqual(2318.0);
expect(e.cylinder.outlineWidth.getValue(documentStopDate)).toEqual(2319.0);
expect(e.cylinder.numberOfVerticalLines.getValue(documentStartDate)).toEqual(2320.0);
expect(e.cylinder.numberOfVerticalLines.getValue(documentStopDate)).toEqual(2321.0);
expect(e.cylinder.slices.getValue(documentStartDate)).toEqual(2322.0);
expect(e.cylinder.slices.getValue(documentStopDate)).toEqual(2323.0);
expect(e.ellipse.semiMajorAxis.getValue(documentStartDate)).toEqual(2324.0);
expect(e.ellipse.semiMajorAxis.getValue(documentStopDate)).toEqual(2325.0);
expect(e.ellipse.semiMinorAxis.getValue(documentStartDate)).toEqual(2326.0);
expect(e.ellipse.semiMinorAxis.getValue(documentStopDate)).toEqual(2327.0);
expect(e.ellipse.height.getValue(documentStartDate)).toEqual(2328.0);
expect(e.ellipse.height.getValue(documentStopDate)).toEqual(2329.0);
expect(e.ellipse.extrudedHeight.getValue(documentStartDate)).toEqual(2330.0);
expect(e.ellipse.extrudedHeight.getValue(documentStopDate)).toEqual(2331.0);
expect(e.ellipse.rotation.getValue(documentStartDate)).toEqual(2332.0);
expect(e.ellipse.rotation.getValue(documentStopDate)).toEqual(2333.0);
expect(e.ellipse.stRotation.getValue(documentStartDate)).toEqual(2334.0);
expect(e.ellipse.stRotation.getValue(documentStopDate)).toEqual(2335.0);
expect(e.ellipse.granularity.getValue(documentStartDate)).toEqual(2336.0);
expect(e.ellipse.granularity.getValue(documentStopDate)).toEqual(2337.0);
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(44, 45, 46, 43));
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(48, 49, 50, 47));
expect(e.ellipse.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(52, 53, 54, 51));
expect(e.ellipse.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(56, 57, 58, 55));
expect(e.ellipse.outlineWidth.getValue(documentStartDate)).toEqual(2354.0);
expect(e.ellipse.outlineWidth.getValue(documentStopDate)).toEqual(2355.0);
expect(e.ellipse.numberOfVerticalLines.getValue(documentStartDate)).toEqual(2356.0);
expect(e.ellipse.numberOfVerticalLines.getValue(documentStopDate)).toEqual(2357.0);
expect(e.ellipsoid.radii.getValue(documentStartDate)).toEqual(new Cartesian3(2358, 2359, 2360));
expect(e.ellipsoid.radii.getValue(documentStopDate)).toEqual(new Cartesian3(2361, 2362, 2363));
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(70, 71, 72, 69));
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(74, 75, 76, 73));
expect(e.ellipsoid.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(78, 79, 80, 77));
expect(e.ellipsoid.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(82, 83, 84, 81));
expect(e.ellipsoid.outlineWidth.getValue(documentStartDate)).toEqual(2380.0);
expect(e.ellipsoid.outlineWidth.getValue(documentStopDate)).toEqual(2381.0);
expect(e.ellipsoid.stackPartitions.getValue(documentStartDate)).toEqual(2382.0);
expect(e.ellipsoid.stackPartitions.getValue(documentStopDate)).toEqual(2383.0);
expect(e.ellipsoid.slicePartitions.getValue(documentStartDate)).toEqual(2384.0);
expect(e.ellipsoid.slicePartitions.getValue(documentStopDate)).toEqual(2385.0);
expect(e.ellipsoid.subdivisions.getValue(documentStartDate)).toEqual(2386.0);
expect(e.ellipsoid.subdivisions.getValue(documentStopDate)).toEqual(2387.0);
expect(e.label.scale.getValue(documentStartDate)).toEqual(2388.0);
expect(e.label.scale.getValue(documentStopDate)).toEqual(2389.0);
expect(e.label.pixelOffset.getValue(documentStartDate)).toEqual(new Cartesian2(2390, 2391));
expect(e.label.pixelOffset.getValue(documentStopDate)).toEqual(new Cartesian2(2392, 2393));
expect(e.label.eyeOffset.getValue(documentStartDate)).toEqual(new Cartesian3(2394, 2395, 2396));
expect(e.label.eyeOffset.getValue(documentStopDate)).toEqual(new Cartesian3(2397, 2398, 2399));
expect(e.label.fillColor.getValue(documentStartDate)).toEqual(Color.fromBytes(106, 107, 108, 105));
expect(e.label.fillColor.getValue(documentStopDate)).toEqual(Color.fromBytes(110, 111, 112, 109));
expect(e.label.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(114, 115, 116, 113));
expect(e.label.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(118, 119, 120, 117));
expect(e.label.outlineWidth.getValue(documentStartDate)).toEqual(2416.0);
expect(e.label.outlineWidth.getValue(documentStopDate)).toEqual(2417.0);
expect(e.label.translucencyByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2418, 2419, 2420, 2421));
expect(e.label.translucencyByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2422, 2423, 2424, 2425));
expect(e.label.pixelOffsetScaleByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2426, 2427, 2428, 2429));
expect(e.label.pixelOffsetScaleByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2430, 2431, 2432, 2433));
expect(e.model.scale.getValue(documentStartDate)).toEqual(2434.0);
expect(e.model.scale.getValue(documentStopDate)).toEqual(2435.0);
expect(e.model.minimumPixelSize.getValue(documentStartDate)).toEqual(2436.0);
expect(e.model.minimumPixelSize.getValue(documentStopDate)).toEqual(2437.0);
expect(e.model.maximumScale.getValue(documentStartDate)).toEqual(2438.0);
expect(e.model.maximumScale.getValue(documentStopDate)).toEqual(2439.0);
expect(e.path.width.getValue(documentStartDate)).toEqual(2440.0);
expect(e.path.width.getValue(documentStopDate)).toEqual(2441.0);
expect(e.path.resolution.getValue(documentStartDate)).toEqual(2442.0);
expect(e.path.resolution.getValue(documentStopDate)).toEqual(2443.0);
expect(e.path.leadTime.getValue(documentStartDate)).toEqual(2444.0);
expect(e.path.leadTime.getValue(documentStopDate)).toEqual(2445.0);
expect(e.path.trailTime.getValue(documentStartDate)).toEqual(2446.0);
expect(e.path.trailTime.getValue(documentStopDate)).toEqual(2447.0);
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(154, 155, 156, 153));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(158, 159, 160, 157));
expect(e.point.pixelSize.getValue(documentStartDate)).toEqual(2456.0);
expect(e.point.pixelSize.getValue(documentStopDate)).toEqual(2457.0);
expect(e.point.color.getValue(documentStartDate)).toEqual(Color.fromBytes(164, 165, 166, 163));
expect(e.point.color.getValue(documentStopDate)).toEqual(Color.fromBytes(168, 169, 170, 167));
expect(e.point.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(172, 173, 174, 171));
expect(e.point.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(176, 177, 178, 175));
expect(e.point.outlineWidth.getValue(documentStartDate)).toEqual(2474.0);
expect(e.point.outlineWidth.getValue(documentStopDate)).toEqual(2475.0);
expect(e.point.scaleByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2476, 2477, 2478, 2479));
expect(e.point.scaleByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2480, 2481, 2482, 2483));
expect(e.point.translucencyByDistance.getValue(documentStartDate)).toEqual(new NearFarScalar(2484, 2485, 2486, 2487));
expect(e.point.translucencyByDistance.getValue(documentStopDate)).toEqual(new NearFarScalar(2488, 2489, 2490, 2491));
expect(e.polygon.height.getValue(documentStartDate)).toEqual(2492.0);
expect(e.polygon.height.getValue(documentStopDate)).toEqual(2493.0);
expect(e.polygon.extrudedHeight.getValue(documentStartDate)).toEqual(2494.0);
expect(e.polygon.extrudedHeight.getValue(documentStopDate)).toEqual(2495.0);
expect(e.polygon.stRotation.getValue(documentStartDate)).toEqual(2496.0);
expect(e.polygon.stRotation.getValue(documentStopDate)).toEqual(2497.0);
expect(e.polygon.granularity.getValue(documentStartDate)).toEqual(2498.0);
expect(e.polygon.granularity.getValue(documentStopDate)).toEqual(2499.0);
expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(206, 207, 208, 205));
expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(210, 211, 212, 209));
expect(e.polygon.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(214, 215, 216, 213));
expect(e.polygon.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(218, 219, 220, 217));
expect(e.polygon.outlineWidth.getValue(documentStartDate)).toEqual(2516.0);
expect(e.polygon.outlineWidth.getValue(documentStopDate)).toEqual(2517.0);
expect(e.polyline.width.getValue(documentStartDate)).toEqual(2518.0);
expect(e.polyline.width.getValue(documentStopDate)).toEqual(2519.0);
expect(e.polyline.granularity.getValue(documentStartDate)).toEqual(2520.0);
expect(e.polyline.granularity.getValue(documentStopDate)).toEqual(2521.0);
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(228, 229, 230, 227));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(232, 233, 234, 231));
expect(e.rectangle.coordinates.getValue(documentStartDate)).toEqual(new Rectangle(1.01791386021654, 0.447117533421645, 1.44711753342165, 0.876321206626749));
expect(e.rectangle.coordinates.getValue(documentStopDate)).toEqual(new Rectangle(0.305524879831852, 1.30552487983185, 0.734728553036955, 0.163932226242059));
expect(e.rectangle.height.getValue(documentStartDate)).toEqual(2538.0);
expect(e.rectangle.height.getValue(documentStopDate)).toEqual(2539.0);
expect(e.rectangle.extrudedHeight.getValue(documentStartDate)).toEqual(2540.0);
expect(e.rectangle.extrudedHeight.getValue(documentStopDate)).toEqual(2541.0);
expect(e.rectangle.rotation.getValue(documentStartDate)).toEqual(2542.0);
expect(e.rectangle.rotation.getValue(documentStopDate)).toEqual(2543.0);
expect(e.rectangle.stRotation.getValue(documentStartDate)).toEqual(2544.0);
expect(e.rectangle.stRotation.getValue(documentStopDate)).toEqual(2545.0);
expect(e.rectangle.granularity.getValue(documentStartDate)).toEqual(2546.0);
expect(e.rectangle.granularity.getValue(documentStopDate)).toEqual(2547.0);
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(254, 0, 1, 253));
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(3, 4, 5, 2));
expect(e.rectangle.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(7, 8, 9, 6));
expect(e.rectangle.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(11, 12, 13, 10));
expect(e.rectangle.outlineWidth.getValue(documentStartDate)).toEqual(2564.0);
expect(e.rectangle.outlineWidth.getValue(documentStopDate)).toEqual(2565.0);
expect(e.wall.granularity.getValue(documentStartDate)).toEqual(2566.0);
expect(e.wall.granularity.getValue(documentStopDate)).toEqual(2567.0);
expect(e.wall.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(19, 20, 21, 18));
expect(e.wall.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(23, 24, 25, 22));
expect(e.wall.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(27, 28, 29, 26));
expect(e.wall.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(31, 32, 33, 30));
expect(e.wall.outlineWidth.getValue(documentStartDate)).toEqual(2584.0);
expect(e.wall.outlineWidth.getValue(documentStopDate)).toEqual(2585.0);
expect(e = dataSource.entities.getById('sampled2824')).toBeDefined();
expect(e.position.getValue(documentStartDate)).toEqual(Cartesian3.fromRadians(0.708204422775989, 0.137408095981092, 2827));
expect(e.position.getValue(documentStopDate)).toEqual(Cartesian3.fromRadians(0.566611769186196, 1.5666117691862, 2830));
expect(e = dataSource.entities.getById('sampled2831')).toBeDefined();
expect(e.position.getValue(documentStartDate)).toEqual(Cartesian3.fromDegrees(42, 43, 2834));
expect(e.position.getValue(documentStopDate)).toEqual(Cartesian3.fromDegrees(0, 1, 2837));
expect(e = dataSource.entities.getById('sampled2838')).toBeDefined();
expect(e.position.getValue(documentStartDate)).toEqual(new Cartesian3(2839, 2840, 2841));
expect(e.position.getValue(documentStopDate)).toEqual(new Cartesian3(2845, 2846, 2847));
expect(e = dataSource.entities.getById('sampled2851')).toBeDefined();
expect(e.billboard.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.188235294117647, 0.192156862745098, 0.196078431372549, 0.184313725490196), 1e-14);
expect(e.billboard.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.203921568627451, 0.207843137254902, 0.211764705882353, 0.2), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2860')).toBeDefined();
expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.223529411764706, 0.227450980392157, 0.231372549019608, 0.219607843137255), 1e-14);
expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.23921568627451, 0.243137254901961, 0.247058823529412, 0.235294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2869')).toBeDefined();
expect(e.box.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(2870, 2871));
expect(e.box.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(2872, 2873));
expect(e.box.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(70, 71, 72, 69));
expect(e.box.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(74, 75, 76, 73));
expect(e = dataSource.entities.getById('sampledmaterial2882')).toBeDefined();
expect(e.box.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(79, 80, 81, 78));
expect(e.box.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(83, 84, 85, 82));
expect(e.box.material.cellAlpha.getValue(documentStartDate)).toEqual(2891.0);
expect(e.box.material.cellAlpha.getValue(documentStopDate)).toEqual(2892.0);
expect(e.box.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(2893, 2894));
expect(e.box.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(2895, 2896));
expect(e.box.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(2897, 2898));
expect(e.box.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(2899, 2900));
expect(e.box.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(2901, 2902));
expect(e.box.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(2903, 2904));
expect(e = dataSource.entities.getById('sampledmaterial2905')).toBeDefined();
expect(e.box.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(102, 103, 104, 101));
expect(e.box.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(106, 107, 108, 105));
expect(e.box.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(110, 111, 112, 109));
expect(e.box.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(114, 115, 116, 113));
expect(e.box.material.offset.getValue(documentStartDate)).toEqual(2922.0);
expect(e.box.material.offset.getValue(documentStopDate)).toEqual(2923.0);
expect(e.box.material.repeat.getValue(documentStartDate)).toEqual(2924.0);
expect(e.box.material.repeat.getValue(documentStopDate)).toEqual(2925.0);
expect(e = dataSource.entities.getById('sampledmaterial2926')).toBeDefined();
expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.482352941176471, 0.486274509803922, 0.490196078431373, 0.47843137254902), 1e-14);
expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.498039215686275, 0.501960784313725, 0.505882352941176, 0.494117647058824), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2935')).toBeDefined();
expect(e.box.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.517647058823529, 0.52156862745098, 0.525490196078431, 0.513725490196078), 1e-14);
expect(e.box.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.533333333333333, 0.537254901960784, 0.541176470588235, 0.529411764705882), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2944')).toBeDefined();
expect(e.box.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.552941176470588, 0.556862745098039, 0.56078431372549, 0.549019607843137), 1e-14);
expect(e.box.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.568627450980392, 0.572549019607843, 0.576470588235294, 0.564705882352941), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2953')).toBeDefined();
expect(e.box.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.588235294117647, 0.592156862745098, 0.596078431372549, 0.584313725490196), 1e-14);
expect(e.box.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.603921568627451, 0.607843137254902, 0.611764705882353, 0.6), 1e-14);
expect(e = dataSource.entities.getById('sampled2962')).toBeDefined();
expect(e.box.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.623529411764706, 0.627450980392157, 0.631372549019608, 0.619607843137255), 1e-14);
expect(e.box.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.63921568627451, 0.643137254901961, 0.647058823529412, 0.635294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2971')).toBeDefined();
expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.658823529411765, 0.662745098039216, 0.666666666666667, 0.654901960784314), 1e-14);
expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.674509803921569, 0.67843137254902, 0.682352941176471, 0.670588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial2980')).toBeDefined();
expect(e.corridor.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(2981, 2982));
expect(e.corridor.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(2983, 2984));
expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(181, 182, 183, 180));
expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(185, 186, 187, 184));
expect(e = dataSource.entities.getById('sampledmaterial2993')).toBeDefined();
expect(e.corridor.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(190, 191, 192, 189));
expect(e.corridor.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(194, 195, 196, 193));
expect(e.corridor.material.cellAlpha.getValue(documentStartDate)).toEqual(3002.0);
expect(e.corridor.material.cellAlpha.getValue(documentStopDate)).toEqual(3003.0);
expect(e.corridor.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3004, 3005));
expect(e.corridor.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3006, 3007));
expect(e.corridor.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3008, 3009));
expect(e.corridor.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3010, 3011));
expect(e.corridor.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3012, 3013));
expect(e.corridor.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3014, 3015));
expect(e = dataSource.entities.getById('sampledmaterial3016')).toBeDefined();
expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(213, 214, 215, 212));
expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(217, 218, 219, 216));
expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(221, 222, 223, 220));
expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(225, 226, 227, 224));
expect(e.corridor.material.offset.getValue(documentStartDate)).toEqual(3033.0);
expect(e.corridor.material.offset.getValue(documentStopDate)).toEqual(3034.0);
expect(e.corridor.material.repeat.getValue(documentStartDate)).toEqual(3035.0);
expect(e.corridor.material.repeat.getValue(documentStopDate)).toEqual(3036.0);
expect(e = dataSource.entities.getById('sampledmaterial3037')).toBeDefined();
expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.917647058823529, 0.92156862745098, 0.925490196078431, 0.913725490196078), 1e-14);
expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.933333333333333, 0.937254901960784, 0.941176470588235, 0.929411764705882), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3046')).toBeDefined();
expect(e.corridor.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.952941176470588, 0.956862745098039, 0.96078431372549, 0.949019607843137), 1e-14);
expect(e.corridor.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.968627450980392, 0.972549019607843, 0.976470588235294, 0.964705882352941), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3055')).toBeDefined();
expect(e.corridor.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.988235294117647, 0.992156862745098, 0.996078431372549, 0.984313725490196), 1e-14);
expect(e.corridor.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.00392156862745098, 0.00784313725490196, 0.0117647058823529, 0), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3064')).toBeDefined();
expect(e.corridor.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0235294117647059, 0.0274509803921569, 0.0313725490196078, 0.0196078431372549), 1e-14);
expect(e.corridor.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.0392156862745098, 0.0431372549019608, 0.0470588235294118, 0.0352941176470588), 1e-14);
expect(e = dataSource.entities.getById('sampled3073')).toBeDefined();
expect(e.corridor.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0588235294117647, 0.0627450980392157, 0.0666666666666667, 0.0549019607843137), 1e-14);
expect(e.corridor.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.0745098039215686, 0.0784313725490196, 0.0823529411764706, 0.0705882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3082')).toBeDefined();
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0941176470588235, 0.0980392156862745, 0.101960784313725, 0.0901960784313725), 1e-14);
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3091')).toBeDefined();
expect(e.cylinder.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3092, 3093));
expect(e.cylinder.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3094, 3095));
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(37, 38, 39, 36));
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(41, 42, 43, 40));
expect(e = dataSource.entities.getById('sampledmaterial3104')).toBeDefined();
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(46, 47, 48, 45));
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(50, 51, 52, 49));
expect(e.cylinder.material.cellAlpha.getValue(documentStartDate)).toEqual(3113.0);
expect(e.cylinder.material.cellAlpha.getValue(documentStopDate)).toEqual(3114.0);
expect(e.cylinder.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3115, 3116));
expect(e.cylinder.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3117, 3118));
expect(e.cylinder.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3119, 3120));
expect(e.cylinder.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3121, 3122));
expect(e.cylinder.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3123, 3124));
expect(e.cylinder.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3125, 3126));
expect(e = dataSource.entities.getById('sampledmaterial3127')).toBeDefined();
expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(69, 70, 71, 68));
expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(73, 74, 75, 72));
expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(77, 78, 79, 76));
expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(81, 82, 83, 80));
expect(e.cylinder.material.offset.getValue(documentStartDate)).toEqual(3144.0);
expect(e.cylinder.material.offset.getValue(documentStopDate)).toEqual(3145.0);
expect(e.cylinder.material.repeat.getValue(documentStartDate)).toEqual(3146.0);
expect(e.cylinder.material.repeat.getValue(documentStopDate)).toEqual(3147.0);
expect(e = dataSource.entities.getById('sampledmaterial3148')).toBeDefined();
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.352941176470588, 0.356862745098039, 0.36078431372549, 0.349019607843137), 1e-14);
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.368627450980392, 0.372549019607843, 0.376470588235294, 0.364705882352941), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3157')).toBeDefined();
expect(e.cylinder.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.388235294117647, 0.392156862745098, 0.396078431372549, 0.384313725490196), 1e-14);
expect(e.cylinder.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.403921568627451, 0.407843137254902, 0.411764705882353, 0.4), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3166')).toBeDefined();
expect(e.cylinder.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.423529411764706, 0.427450980392157, 0.431372549019608, 0.419607843137255), 1e-14);
expect(e.cylinder.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.43921568627451, 0.443137254901961, 0.447058823529412, 0.435294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3175')).toBeDefined();
expect(e.cylinder.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.458823529411765, 0.462745098039216, 0.466666666666667, 0.454901960784314), 1e-14);
expect(e.cylinder.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.474509803921569, 0.47843137254902, 0.482352941176471, 0.470588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampled3184')).toBeDefined();
expect(e.cylinder.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.494117647058824, 0.498039215686275, 0.501960784313725, 0.490196078431373), 1e-14);
expect(e.cylinder.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.509803921568627, 0.513725490196078, 0.517647058823529, 0.505882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3193')).toBeDefined();
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.529411764705882, 0.533333333333333, 0.537254901960784, 0.525490196078431), 1e-14);
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.545098039215686, 0.549019607843137, 0.552941176470588, 0.541176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3202')).toBeDefined();
expect(e.ellipse.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3203, 3204));
expect(e.ellipse.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3205, 3206));
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(148, 149, 150, 147));
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(152, 153, 154, 151));
expect(e = dataSource.entities.getById('sampledmaterial3215')).toBeDefined();
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(157, 158, 159, 156));
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(161, 162, 163, 160));
expect(e.ellipse.material.cellAlpha.getValue(documentStartDate)).toEqual(3224.0);
expect(e.ellipse.material.cellAlpha.getValue(documentStopDate)).toEqual(3225.0);
expect(e.ellipse.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3226, 3227));
expect(e.ellipse.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3228, 3229));
expect(e.ellipse.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3230, 3231));
expect(e.ellipse.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3232, 3233));
expect(e.ellipse.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3234, 3235));
expect(e.ellipse.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3236, 3237));
expect(e = dataSource.entities.getById('sampledmaterial3238')).toBeDefined();
expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(180, 181, 182, 179));
expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(184, 185, 186, 183));
expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(188, 189, 190, 187));
expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(192, 193, 194, 191));
expect(e.ellipse.material.offset.getValue(documentStartDate)).toEqual(3255.0);
expect(e.ellipse.material.offset.getValue(documentStopDate)).toEqual(3256.0);
expect(e.ellipse.material.repeat.getValue(documentStartDate)).toEqual(3257.0);
expect(e.ellipse.material.repeat.getValue(documentStopDate)).toEqual(3258.0);
expect(e = dataSource.entities.getById('sampledmaterial3259')).toBeDefined();
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.788235294117647, 0.792156862745098, 0.796078431372549, 0.784313725490196), 1e-14);
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.803921568627451, 0.807843137254902, 0.811764705882353, 0.8), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3268')).toBeDefined();
expect(e.ellipse.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.823529411764706, 0.827450980392157, 0.831372549019608, 0.819607843137255), 1e-14);
expect(e.ellipse.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.83921568627451, 0.843137254901961, 0.847058823529412, 0.835294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3277')).toBeDefined();
expect(e.ellipse.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.858823529411765, 0.862745098039216, 0.866666666666667, 0.854901960784314), 1e-14);
expect(e.ellipse.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.874509803921569, 0.87843137254902, 0.882352941176471, 0.870588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3286')).toBeDefined();
expect(e.ellipse.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.894117647058824, 0.898039215686275, 0.901960784313726, 0.890196078431373), 1e-14);
expect(e.ellipse.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.909803921568627, 0.913725490196078, 0.917647058823529, 0.905882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampled3295')).toBeDefined();
expect(e.ellipse.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.929411764705882, 0.933333333333333, 0.937254901960784, 0.925490196078431), 1e-14);
expect(e.ellipse.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.945098039215686, 0.949019607843137, 0.952941176470588, 0.941176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3304')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.964705882352941, 0.968627450980392, 0.972549019607843, 0.96078431372549), 1e-14);
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.980392156862745, 0.984313725490196, 0.988235294117647, 0.976470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3313')).toBeDefined();
expect(e.ellipsoid.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3314, 3315));
expect(e.ellipsoid.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3316, 3317));
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(4, 5, 6, 3));
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(8, 9, 10, 7));
expect(e = dataSource.entities.getById('sampledmaterial3326')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(13, 14, 15, 12));
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(17, 18, 19, 16));
expect(e.ellipsoid.material.cellAlpha.getValue(documentStartDate)).toEqual(3335.0);
expect(e.ellipsoid.material.cellAlpha.getValue(documentStopDate)).toEqual(3336.0);
expect(e.ellipsoid.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3337, 3338));
expect(e.ellipsoid.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3339, 3340));
expect(e.ellipsoid.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3341, 3342));
expect(e.ellipsoid.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3343, 3344));
expect(e.ellipsoid.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3345, 3346));
expect(e.ellipsoid.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3347, 3348));
expect(e = dataSource.entities.getById('sampledmaterial3349')).toBeDefined();
expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(36, 37, 38, 35));
expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(40, 41, 42, 39));
expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(44, 45, 46, 43));
expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(48, 49, 50, 47));
expect(e.ellipsoid.material.offset.getValue(documentStartDate)).toEqual(3366.0);
expect(e.ellipsoid.material.offset.getValue(documentStopDate)).toEqual(3367.0);
expect(e.ellipsoid.material.repeat.getValue(documentStartDate)).toEqual(3368.0);
expect(e.ellipsoid.material.repeat.getValue(documentStopDate)).toEqual(3369.0);
expect(e = dataSource.entities.getById('sampledmaterial3370')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.223529411764706, 0.227450980392157, 0.231372549019608, 0.219607843137255), 1e-14);
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.23921568627451, 0.243137254901961, 0.247058823529412, 0.235294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3379')).toBeDefined();
expect(e.ellipsoid.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.258823529411765, 0.262745098039216, 0.266666666666667, 0.254901960784314), 1e-14);
expect(e.ellipsoid.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.274509803921569, 0.27843137254902, 0.282352941176471, 0.270588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3388')).toBeDefined();
expect(e.ellipsoid.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.294117647058824, 0.298039215686275, 0.301960784313725, 0.290196078431373), 1e-14);
expect(e.ellipsoid.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.309803921568627, 0.313725490196078, 0.317647058823529, 0.305882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3397')).toBeDefined();
expect(e.ellipsoid.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.329411764705882, 0.333333333333333, 0.337254901960784, 0.325490196078431), 1e-14);
expect(e.ellipsoid.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.345098039215686, 0.349019607843137, 0.352941176470588, 0.341176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampled3406')).toBeDefined();
expect(e.ellipsoid.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.364705882352941, 0.368627450980392, 0.372549019607843, 0.36078431372549), 1e-14);
expect(e.ellipsoid.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.380392156862745, 0.384313725490196, 0.388235294117647, 0.376470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampled3415')).toBeDefined();
expect(e.label.fillColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.4, 0.403921568627451, 0.407843137254902, 0.396078431372549), 1e-14);
expect(e.label.fillColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.415686274509804, 0.419607843137255, 0.423529411764706, 0.411764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampled3424')).toBeDefined();
expect(e.label.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.435294117647059, 0.43921568627451, 0.443137254901961, 0.431372549019608), 1e-14);
expect(e.label.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.450980392156863, 0.454901960784314, 0.458823529411765, 0.447058823529412), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3433')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.470588235294118, 0.474509803921569, 0.47843137254902, 0.466666666666667), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.486274509803922, 0.490196078431373, 0.494117647058824, 0.482352941176471), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3442')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(129, 130, 131, 128));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(133, 134, 135, 132));
expect(e.path.material.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(137, 138, 139, 136));
expect(e.path.material.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(141, 142, 143, 140));
expect(e.path.material.outlineWidth.getValue(documentStartDate)).toEqual(3459.0);
expect(e.path.material.outlineWidth.getValue(documentStopDate)).toEqual(3460.0);
expect(e = dataSource.entities.getById('sampledmaterial3461')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(148, 149, 150, 147));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(152, 153, 154, 151));
expect(e = dataSource.entities.getById('sampledmaterial3470')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(157, 158, 159, 156));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(161, 162, 163, 160));
expect(e.path.material.glowPower.getValue(documentStartDate)).toEqual(3479.0);
expect(e.path.material.glowPower.getValue(documentStopDate)).toEqual(3480.0);
expect(e = dataSource.entities.getById('sampledmaterial3481')).toBeDefined();
expect(e.path.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3482, 3483));
expect(e.path.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3484, 3485));
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(172, 173, 174, 171));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(176, 177, 178, 175));
expect(e = dataSource.entities.getById('sampledmaterial3494')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(181, 182, 183, 180));
expect(e.path.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(185, 186, 187, 184));
expect(e.path.material.cellAlpha.getValue(documentStartDate)).toEqual(3503.0);
expect(e.path.material.cellAlpha.getValue(documentStopDate)).toEqual(3504.0);
expect(e.path.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3505, 3506));
expect(e.path.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3507, 3508));
expect(e.path.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3509, 3510));
expect(e.path.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3511, 3512));
expect(e.path.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3513, 3514));
expect(e.path.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3515, 3516));
expect(e = dataSource.entities.getById('sampledmaterial3517')).toBeDefined();
expect(e.path.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(204, 205, 206, 203));
expect(e.path.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(208, 209, 210, 207));
expect(e.path.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(212, 213, 214, 211));
expect(e.path.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(216, 217, 218, 215));
expect(e.path.material.offset.getValue(documentStartDate)).toEqual(3534.0);
expect(e.path.material.offset.getValue(documentStopDate)).toEqual(3535.0);
expect(e.path.material.repeat.getValue(documentStartDate)).toEqual(3536.0);
expect(e.path.material.repeat.getValue(documentStopDate)).toEqual(3537.0);
expect(e = dataSource.entities.getById('sampledmaterial3538')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.882352941176471, 0.886274509803922, 0.890196078431373, 0.87843137254902), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.898039215686275, 0.901960784313726, 0.905882352941176, 0.894117647058824), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3547')).toBeDefined();
expect(e.path.material.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.917647058823529, 0.92156862745098, 0.925490196078431, 0.913725490196078), 1e-14);
expect(e.path.material.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.933333333333333, 0.937254901960784, 0.941176470588235, 0.929411764705882), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3556')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.952941176470588, 0.956862745098039, 0.96078431372549, 0.949019607843137), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.968627450980392, 0.972549019607843, 0.976470588235294, 0.964705882352941), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3565')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.988235294117647, 0.992156862745098, 0.996078431372549, 0.984313725490196), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.00392156862745098, 0.00784313725490196, 0.0117647058823529, 0), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3574')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0235294117647059, 0.0274509803921569, 0.0313725490196078, 0.0196078431372549), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.0392156862745098, 0.0431372549019608, 0.0470588235294118, 0.0352941176470588), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3583')).toBeDefined();
expect(e.path.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0588235294117647, 0.0627450980392157, 0.0666666666666667, 0.0549019607843137), 1e-14);
expect(e.path.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.0745098039215686, 0.0784313725490196, 0.0823529411764706, 0.0705882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3592')).toBeDefined();
expect(e.path.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0941176470588235, 0.0980392156862745, 0.101960784313725, 0.0901960784313725), 1e-14);
expect(e.path.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3601')).toBeDefined();
expect(e.path.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.129411764705882, 0.133333333333333, 0.137254901960784, 0.125490196078431), 1e-14);
expect(e.path.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.145098039215686, 0.149019607843137, 0.152941176470588, 0.141176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampled3610')).toBeDefined();
expect(e.point.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.164705882352941, 0.168627450980392, 0.172549019607843, 0.16078431372549), 1e-14);
expect(e.point.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.180392156862745, 0.184313725490196, 0.188235294117647, 0.176470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampled3619')).toBeDefined();
expect(e.point.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.2, 0.203921568627451, 0.207843137254902, 0.196078431372549), 1e-14);
expect(e.point.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.215686274509804, 0.219607843137255, 0.223529411764706, 0.211764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3628')).toBeDefined();
expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.235294117647059, 0.23921568627451, 0.243137254901961, 0.231372549019608), 1e-14);
expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.250980392156863, 0.254901960784314, 0.258823529411765, 0.247058823529412), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3637')).toBeDefined();
expect(e.polygon.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3638, 3639));
expect(e.polygon.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3640, 3641));
expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(73, 74, 75, 72));
expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(77, 78, 79, 76));
expect(e = dataSource.entities.getById('sampledmaterial3650')).toBeDefined();
expect(e.polygon.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(82, 83, 84, 81));
expect(e.polygon.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(86, 87, 88, 85));
expect(e.polygon.material.cellAlpha.getValue(documentStartDate)).toEqual(3659.0);
expect(e.polygon.material.cellAlpha.getValue(documentStopDate)).toEqual(3660.0);
expect(e.polygon.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3661, 3662));
expect(e.polygon.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3663, 3664));
expect(e.polygon.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3665, 3666));
expect(e.polygon.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3667, 3668));
expect(e.polygon.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3669, 3670));
expect(e.polygon.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3671, 3672));
expect(e = dataSource.entities.getById('sampledmaterial3673')).toBeDefined();
expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(105, 106, 107, 104));
expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(109, 110, 111, 108));
expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(113, 114, 115, 112));
expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(117, 118, 119, 116));
expect(e.polygon.material.offset.getValue(documentStartDate)).toEqual(3690.0);
expect(e.polygon.material.offset.getValue(documentStopDate)).toEqual(3691.0);
expect(e.polygon.material.repeat.getValue(documentStartDate)).toEqual(3692.0);
expect(e.polygon.material.repeat.getValue(documentStopDate)).toEqual(3693.0);
expect(e = dataSource.entities.getById('sampledmaterial3694')).toBeDefined();
expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.494117647058824, 0.498039215686275, 0.501960784313725, 0.490196078431373), 1e-14);
expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.509803921568627, 0.513725490196078, 0.517647058823529, 0.505882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3703')).toBeDefined();
expect(e.polygon.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.529411764705882, 0.533333333333333, 0.537254901960784, 0.525490196078431), 1e-14);
expect(e.polygon.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.545098039215686, 0.549019607843137, 0.552941176470588, 0.541176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3712')).toBeDefined();
expect(e.polygon.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.564705882352941, 0.568627450980392, 0.572549019607843, 0.56078431372549), 1e-14);
expect(e.polygon.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.580392156862745, 0.584313725490196, 0.588235294117647, 0.576470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3721')).toBeDefined();
expect(e.polygon.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.6, 0.603921568627451, 0.607843137254902, 0.596078431372549), 1e-14);
expect(e.polygon.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.615686274509804, 0.619607843137255, 0.623529411764706, 0.611764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampled3730')).toBeDefined();
expect(e.polygon.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.635294117647059, 0.63921568627451, 0.643137254901961, 0.631372549019608), 1e-14);
expect(e.polygon.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.650980392156863, 0.654901960784314, 0.658823529411765, 0.647058823529412), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3739')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.670588235294118, 0.674509803921569, 0.67843137254902, 0.666666666666667), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.686274509803922, 0.690196078431373, 0.694117647058824, 0.682352941176471), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3748')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(180, 181, 182, 179));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(184, 185, 186, 183));
expect(e.polyline.material.outlineColor.getValue(documentStartDate)).toEqual(Color.fromBytes(188, 189, 190, 187));
expect(e.polyline.material.outlineColor.getValue(documentStopDate)).toEqual(Color.fromBytes(192, 193, 194, 191));
expect(e.polyline.material.outlineWidth.getValue(documentStartDate)).toEqual(3765.0);
expect(e.polyline.material.outlineWidth.getValue(documentStopDate)).toEqual(3766.0);
expect(e = dataSource.entities.getById('sampledmaterial3767')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(199, 200, 201, 198));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(203, 204, 205, 202));
expect(e = dataSource.entities.getById('sampledmaterial3776')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(208, 209, 210, 207));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(212, 213, 214, 211));
expect(e.polyline.material.glowPower.getValue(documentStartDate)).toEqual(3785.0);
expect(e.polyline.material.glowPower.getValue(documentStopDate)).toEqual(3786.0);
expect(e = dataSource.entities.getById('sampledmaterial3787')).toBeDefined();
expect(e.polyline.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3788, 3789));
expect(e.polyline.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3790, 3791));
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(223, 224, 225, 222));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(227, 228, 229, 226));
expect(e = dataSource.entities.getById('sampledmaterial3800')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(232, 233, 234, 231));
expect(e.polyline.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(236, 237, 238, 235));
expect(e.polyline.material.cellAlpha.getValue(documentStartDate)).toEqual(3809.0);
expect(e.polyline.material.cellAlpha.getValue(documentStopDate)).toEqual(3810.0);
expect(e.polyline.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3811, 3812));
expect(e.polyline.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3813, 3814));
expect(e.polyline.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3815, 3816));
expect(e.polyline.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3817, 3818));
expect(e.polyline.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3819, 3820));
expect(e.polyline.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3821, 3822));
expect(e = dataSource.entities.getById('sampledmaterial3823')).toBeDefined();
expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(0, 1, 2, 254));
expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(4, 5, 6, 3));
expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(8, 9, 10, 7));
expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(12, 13, 14, 11));
expect(e.polyline.material.offset.getValue(documentStartDate)).toEqual(3840.0);
expect(e.polyline.material.offset.getValue(documentStopDate)).toEqual(3841.0);
expect(e.polyline.material.repeat.getValue(documentStartDate)).toEqual(3842.0);
expect(e.polyline.material.repeat.getValue(documentStopDate)).toEqual(3843.0);
expect(e = dataSource.entities.getById('sampledmaterial3844')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0823529411764706, 0.0862745098039216, 0.0901960784313725, 0.0784313725490196), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.0980392156862745, 0.101960784313725, 0.105882352941176, 0.0941176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3853')).toBeDefined();
expect(e.polyline.material.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.117647058823529, 0.12156862745098, 0.125490196078431, 0.113725490196078), 1e-14);
expect(e.polyline.material.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.133333333333333, 0.137254901960784, 0.141176470588235, 0.129411764705882), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3862')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.152941176470588, 0.156862745098039, 0.16078431372549, 0.149019607843137), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.168627450980392, 0.172549019607843, 0.176470588235294, 0.164705882352941), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3871')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.188235294117647, 0.192156862745098, 0.196078431372549, 0.184313725490196), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.203921568627451, 0.207843137254902, 0.211764705882353, 0.2), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3880')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.223529411764706, 0.227450980392157, 0.231372549019608, 0.219607843137255), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.23921568627451, 0.243137254901961, 0.247058823529412, 0.235294117647059), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3889')).toBeDefined();
expect(e.polyline.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.258823529411765, 0.262745098039216, 0.266666666666667, 0.254901960784314), 1e-14);
expect(e.polyline.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.274509803921569, 0.27843137254902, 0.282352941176471, 0.270588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3898')).toBeDefined();
expect(e.polyline.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.294117647058824, 0.298039215686275, 0.301960784313725, 0.290196078431373), 1e-14);
expect(e.polyline.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.309803921568627, 0.313725490196078, 0.317647058823529, 0.305882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3907')).toBeDefined();
expect(e.polyline.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.329411764705882, 0.333333333333333, 0.337254901960784, 0.325490196078431), 1e-14);
expect(e.polyline.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.345098039215686, 0.349019607843137, 0.352941176470588, 0.341176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampled3916')).toBeDefined();
expect(e.rectangle.coordinates.getValue(documentStartDate)).toEqual(Rectangle.fromDegrees(2, 3, 4, 5));
expect(e.rectangle.coordinates.getValue(documentStopDate)).toEqual(Rectangle.fromDegrees(6, 7, 8, 9));
expect(e = dataSource.entities.getById('sampledmaterial3925')).toBeDefined();
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.4, 0.403921568627451, 0.407843137254902, 0.396078431372549), 1e-14);
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.415686274509804, 0.419607843137255, 0.423529411764706, 0.411764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial3934')).toBeDefined();
expect(e.rectangle.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(3935, 3936));
expect(e.rectangle.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(3937, 3938));
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(115, 116, 117, 114));
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(119, 120, 121, 118));
expect(e = dataSource.entities.getById('sampledmaterial3947')).toBeDefined();
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(124, 125, 126, 123));
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(128, 129, 130, 127));
expect(e.rectangle.material.cellAlpha.getValue(documentStartDate)).toEqual(3956.0);
expect(e.rectangle.material.cellAlpha.getValue(documentStopDate)).toEqual(3957.0);
expect(e.rectangle.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(3958, 3959));
expect(e.rectangle.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(3960, 3961));
expect(e.rectangle.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(3962, 3963));
expect(e.rectangle.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(3964, 3965));
expect(e.rectangle.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(3966, 3967));
expect(e.rectangle.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(3968, 3969));
expect(e = dataSource.entities.getById('sampledmaterial3970')).toBeDefined();
expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(147, 148, 149, 146));
expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(151, 152, 153, 150));
expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(155, 156, 157, 154));
expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(159, 160, 161, 158));
expect(e.rectangle.material.offset.getValue(documentStartDate)).toEqual(3987.0);
expect(e.rectangle.material.offset.getValue(documentStopDate)).toEqual(3988.0);
expect(e.rectangle.material.repeat.getValue(documentStartDate)).toEqual(3989.0);
expect(e.rectangle.material.repeat.getValue(documentStopDate)).toEqual(3990.0);
expect(e = dataSource.entities.getById('sampledmaterial3991')).toBeDefined();
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.658823529411765, 0.662745098039216, 0.666666666666667, 0.654901960784314), 1e-14);
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.674509803921569, 0.67843137254902, 0.682352941176471, 0.670588235294118), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4000')).toBeDefined();
expect(e.rectangle.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.694117647058824, 0.698039215686274, 0.701960784313725, 0.690196078431373), 1e-14);
expect(e.rectangle.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.709803921568627, 0.713725490196078, 0.717647058823529, 0.705882352941177), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4009')).toBeDefined();
expect(e.rectangle.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.729411764705882, 0.733333333333333, 0.737254901960784, 0.725490196078431), 1e-14);
expect(e.rectangle.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.745098039215686, 0.749019607843137, 0.752941176470588, 0.741176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4018')).toBeDefined();
expect(e.rectangle.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.764705882352941, 0.768627450980392, 0.772549019607843, 0.76078431372549), 1e-14);
expect(e.rectangle.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.780392156862745, 0.784313725490196, 0.788235294117647, 0.776470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampled4027')).toBeDefined();
expect(e.rectangle.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.8, 0.803921568627451, 0.807843137254902, 0.796078431372549), 1e-14);
expect(e.rectangle.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.815686274509804, 0.819607843137255, 0.823529411764706, 0.811764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4036')).toBeDefined();
expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.835294117647059, 0.83921568627451, 0.843137254901961, 0.831372549019608), 1e-14);
expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.850980392156863, 0.854901960784314, 0.858823529411765, 0.847058823529412), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4045')).toBeDefined();
expect(e.wall.material.repeat.getValue(documentStartDate)).toEqual(new Cartesian2(4046, 4047));
expect(e.wall.material.repeat.getValue(documentStopDate)).toEqual(new Cartesian2(4048, 4049));
expect(e.wall.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(226, 227, 228, 225));
expect(e.wall.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(230, 231, 232, 229));
expect(e = dataSource.entities.getById('sampledmaterial4058')).toBeDefined();
expect(e.wall.material.color.getValue(documentStartDate)).toEqual(Color.fromBytes(235, 236, 237, 234));
expect(e.wall.material.color.getValue(documentStopDate)).toEqual(Color.fromBytes(239, 240, 241, 238));
expect(e.wall.material.cellAlpha.getValue(documentStartDate)).toEqual(4067.0);
expect(e.wall.material.cellAlpha.getValue(documentStopDate)).toEqual(4068.0);
expect(e.wall.material.lineCount.getValue(documentStartDate)).toEqual(new Cartesian2(4069, 4070));
expect(e.wall.material.lineCount.getValue(documentStopDate)).toEqual(new Cartesian2(4071, 4072));
expect(e.wall.material.lineThickness.getValue(documentStartDate)).toEqual(new Cartesian2(4073, 4074));
expect(e.wall.material.lineThickness.getValue(documentStopDate)).toEqual(new Cartesian2(4075, 4076));
expect(e.wall.material.lineOffset.getValue(documentStartDate)).toEqual(new Cartesian2(4077, 4078));
expect(e.wall.material.lineOffset.getValue(documentStopDate)).toEqual(new Cartesian2(4079, 4080));
expect(e = dataSource.entities.getById('sampledmaterial4081')).toBeDefined();
expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqual(Color.fromBytes(3, 4, 5, 2));
expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqual(Color.fromBytes(7, 8, 9, 6));
expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqual(Color.fromBytes(11, 12, 13, 10));
expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqual(Color.fromBytes(15, 16, 17, 14));
expect(e.wall.material.offset.getValue(documentStartDate)).toEqual(4098.0);
expect(e.wall.material.offset.getValue(documentStopDate)).toEqual(4099.0);
expect(e.wall.material.repeat.getValue(documentStartDate)).toEqual(4100.0);
expect(e.wall.material.repeat.getValue(documentStopDate)).toEqual(4101.0);
expect(e = dataSource.entities.getById('sampledmaterial4102')).toBeDefined();
expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.0941176470588235, 0.0980392156862745, 0.101960784313725, 0.0901960784313725), 1e-14);
expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.109803921568627, 0.113725490196078, 0.117647058823529, 0.105882352941176), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4111')).toBeDefined();
expect(e.wall.material.color.getValue(documentStartDate)).toEqualEpsilon(new Color(0.129411764705882, 0.133333333333333, 0.137254901960784, 0.125490196078431), 1e-14);
expect(e.wall.material.color.getValue(documentStopDate)).toEqualEpsilon(new Color(0.145098039215686, 0.149019607843137, 0.152941176470588, 0.141176470588235), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4120')).toBeDefined();
expect(e.wall.material.evenColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.164705882352941, 0.168627450980392, 0.172549019607843, 0.16078431372549), 1e-14);
expect(e.wall.material.evenColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.180392156862745, 0.184313725490196, 0.188235294117647, 0.176470588235294), 1e-14);
expect(e = dataSource.entities.getById('sampledmaterial4129')).toBeDefined();
expect(e.wall.material.oddColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.2, 0.203921568627451, 0.207843137254902, 0.196078431372549), 1e-14);
expect(e.wall.material.oddColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.215686274509804, 0.219607843137255, 0.223529411764706, 0.211764705882353), 1e-14);
expect(e = dataSource.entities.getById('sampled4138')).toBeDefined();
expect(e.wall.outlineColor.getValue(documentStartDate)).toEqualEpsilon(new Color(0.235294117647059, 0.23921568627451, 0.243137254901961, 0.231372549019608), 1e-14);
expect(e.wall.outlineColor.getValue(documentStopDate)).toEqualEpsilon(new Color(0.250980392156863, 0.254901960784314, 0.258823529411765, 0.247058823529412), 1e-14);
expect(e = dataSource.entities.getById('sampled4147')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4156')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4165')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4178')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4201')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4222')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4231')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4240')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4249')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4258')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4267')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4280')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4303')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4324')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4333')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4342')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4351')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4360')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4369')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4382')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4405')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4426')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4435')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4444')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4453')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4462')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4471')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4484')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4507')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4528')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4537')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4546')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4555')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4564')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4573')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4586')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4609')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4630')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4639')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4648')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4657')).toBeDefined();
expect(e = dataSource.entities.getById('sampled4666')).toBeDefined();
expect(e = dataSource.entities.getById('sampled4675')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4684')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4693')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4706')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4729')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4750')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4759')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4768')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4777')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4786')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4795')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4808')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4831')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4852')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4861')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4870')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4879')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4888')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4897')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4910')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4933')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4954')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4963')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4972')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4981')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4990')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial4999')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5012')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5035')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5056')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5065')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5074')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5083')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5092')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5101')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5114')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5137')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5158')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5167')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5176')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5185')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5194')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5203')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5212')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5221')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5234')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5257')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5278')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5287')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5296')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5305')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5314')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5323')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5336')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5359')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5380')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5389')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5398')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5407')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5416')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5425')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5438')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5461')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5482')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5491')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5500')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5509')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5518')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5527')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5540')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5563')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5584')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5593')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5602')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5611')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5620')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5629')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5642')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5665')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5686')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5695')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5704')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5713')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5722')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5731')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5740')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5753')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5776')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5797')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5806')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5815')).toBeDefined();
expect(e = dataSource.entities.getById('sampledmaterial5824')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5833')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5842')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5851')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5856')).toBeDefined();
expect(e = dataSource.entities.getById('sampled5863')).toBeDefined();
});
});
});
|
const express = require('express')
const app = express()
const fs = require('fs')
// Adds a 1 sec delay for all requests
app.use((req, res, next) => setTimeout(next, 1000))
let testFile = './files/testoutput.txt'
// clear out file if it already exists
try {
fs.unlinkSync(testFile);
//file removed
} catch(err) {
console.error(err)
}
app.get('/', function (req, res) {
let result = []
let data = 'TO BE REPLACED'
if (fs.existsSync(testFile)) {
data = fs.readFileSync(testFile, 'utf8')
}
result.push(data)
res.send(result.join("<br />"))
})
const server = app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
const startGracefulShutdown = () => {
console.log('Starting shutdown of express...');
server.close(function () {
console.log('Express shut down.');
});
}
process.on('SIGTERM', startGracefulShutdown);
process.on('SIGINT', startGracefulShutdown);
|
var scene;
var gameStatus = {};
var mainState = ( function () {
var preload = function () {
scene = this;
gameStatus.capsulaID = utils.preloadCapsuleIdFromURL();
utils.preloadSharedAssets(scene);
gameStatus.colors = colors[gameStatus.capsulaID.split('_')[0]];
scene.load.image('cell', 'sopa-de-letras/assets/cell.png');
scene.load.image('word holder', 'sopa-de-letras/assets/word holder.png');
DragBox.preload('sopa-de-letras/assets/');
}
var create = function () {
gameStatus.emitter = new Phaser.Events.EventEmitter();
utils.createBackground();
gameStatus.sopa = Sopa.gimmieSopa();
Found.create();
VictoryCriteria.create();
// SopaEditor.edit();
let json = banco.sopa[gameStatus.capsulaID];
gameStatus.sopa.feed(json);
gameStatus.emitter.on('word enclosed', () => {
for (let i=0; i<Found.holders.length; i++) {
let holder = Found.holders[i];
if (Found.holders[i].sprite.alpha === 1 && !holder.disclosed) return;
}
utils.createResults('¡Muy bien!', '¡Muy bien!',
colors.global.wrong, colors.global.right, true,
mainState.width, mainState.height, scene);
}, this);
gameStatus.emitter.emit('create');
}
var update = function (time, deltaTime) {
gameStatus.deltaTime = deltaTime / 1000;
gameStatus.emitter.emit('update');
};
return { type: Phaser.WEBGL,
width: 360,
height: 600,
transparent: true,
plugins: {
global: [ NineSlice.Plugin.DefaultCfg ]
},
scene: {
preload : preload,
create : create,
update : update
}
};
})();
var game = new Phaser.Game(mainState);
// width = 360. accessible from game.world.width
// height = 600 acccessible from game.world.height
|
class FormulaParsingError(Exception):
def __init__(self, error, formula):
self.error = error
self.formula = formula
def __str__(self):
position = self.error['column'] - 1
return 'Error while parsing the formula:\n\n{}\n{}\n\n'.format(self.formula," "*position + "^") + \
'Unexpected "' + self.error['unexpected'] + \
'", expected one of: \"' + "\", \"".join(self.error['expected']) + '\"'
|
import Vue from 'vue';
import Router from 'vue-router';
import Signin from '@/components/Signin';
import Signup from '@/components/Signup';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Signin',
component: Signin,
},
{
path: '/signup',
name: 'Signup',
component: Signup,
},
],
});
|
from django.urls import reverse
from nautobot.tenancy.models import Tenant, TenantGroup
from nautobot.utilities.testing import APITestCase, APIViewTestCases
class AppTest(APITestCase):
def test_root(self):
url = reverse("tenancy-api:api-root")
response = self.client.get("{}?format=api".format(url), **self.header)
self.assertEqual(response.status_code, 200)
class TenantGroupTest(APIViewTestCases.APIViewTestCase):
model = TenantGroup
brief_fields = ["_depth", "id", "name", "slug", "tenant_count", "url"]
bulk_update_data = {
"description": "New description",
}
@classmethod
def setUpTestData(cls):
parent_tenant_groups = (
TenantGroup.objects.create(name="Parent Tenant Group 1", slug="parent-tenant-group-1"),
TenantGroup.objects.create(name="Parent Tenant Group 2", slug="parent-tenant-group-2"),
)
TenantGroup.objects.create(name="Tenant Group 1", slug="tenant-group-1", parent=parent_tenant_groups[0])
TenantGroup.objects.create(name="Tenant Group 2", slug="tenant-group-2", parent=parent_tenant_groups[0])
TenantGroup.objects.create(name="Tenant Group 3", slug="tenant-group-3", parent=parent_tenant_groups[0])
cls.create_data = [
{
"name": "Tenant Group 4",
"slug": "tenant-group-4",
"parent": parent_tenant_groups[1].pk,
},
{
"name": "Tenant Group 5",
"slug": "tenant-group-5",
"parent": parent_tenant_groups[1].pk,
},
{
"name": "Tenant Group 6",
"slug": "tenant-group-6",
"parent": parent_tenant_groups[1].pk,
},
]
class TenantTest(APIViewTestCases.APIViewTestCase):
model = Tenant
brief_fields = ["id", "name", "slug", "url"]
bulk_update_data = {
"description": "New description",
}
@classmethod
def setUpTestData(cls):
tenant_groups = (
TenantGroup.objects.create(name="Tenant Group 1", slug="tenant-group-1"),
TenantGroup.objects.create(name="Tenant Group 2", slug="tenant-group-2"),
)
Tenant.objects.create(name="Tenant 1", slug="tenant-1", group=tenant_groups[0])
Tenant.objects.create(name="Tenant 2", slug="tenant-2", group=tenant_groups[0])
Tenant.objects.create(name="Tenant 3", slug="tenant-3", group=tenant_groups[0])
cls.create_data = [
{
"name": "Tenant 4",
"slug": "tenant-4",
"group": tenant_groups[1].pk,
},
{
"name": "Tenant 5",
"slug": "tenant-5",
"group": tenant_groups[1].pk,
},
{
"name": "Tenant 6",
"slug": "tenant-6",
"group": tenant_groups[1].pk,
},
]
|
# -*- coding: utf-8 -*-
# Copyright 2016 Messente Communications OÜ
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from messente.api.sms.api import api
from messente.api.sms.api import utils
from messente.api.sms.api.error import ApiError
from messente.api.sms.api.error import ERROR_CODES
from messente.api.sms.api.response import Response
error_map = ERROR_CODES.copy()
error_map.update({
"ERROR 104": "Country was not found.",
"ERROR 105": "This country is not supported",
"ERROR 106": "Invalid format provided. Only json or xml is allowed."
})
class PricingResponse(Response):
def __init__(self, *args, **kwargs):
Response.__init__(self, *args, **kwargs)
def _get_error_map(self):
return error_map
class PricingAPI(api.API):
"""
Documentation:
http://messente.com/documentation/tools/pricing-api
"""
def __init__(self, **kwargs):
api.API.__init__(self, "pricing", **kwargs)
def get_country_prices(self, country_code, **kwargs):
response_format = kwargs.pop("format", "json")
if response_format not in ["json", "xml"]:
raise ApiError(
"Invalid response_format requested: %s" % response_format
)
r = PricingResponse(
self.call_api(
"prices",
{
"country": country_code,
"format": response_format,
}
),
format=response_format,
)
self.log_response(r)
return r
def get_pricelist(self, output_file=None):
r = PricingResponse(self.call_api("pricelist"))
self.log_response(r)
if output_file:
if utils.write_file(output_file, r.get_raw_text()):
self.log.info("Price list saved to: %s", output_file)
else:
self.log.error("Could not save price list")
return r
|
const os = require("os");
// Configurable
const appVersion = '0.9 (Beta)'
const productionMode = false // turn to true when compiling!
const backendLocation = 'http://127.0.0.1:21168'
const expressPort = 8787
// ** Do not touch **
const operatingSystem = os.platform() === 'win32' ? 'windows' : 'linux'
module.exports = {appVersion, backendLocation, expressPort, operatingSystem, productionMode}
|
app.controller('generateCv', function($scope,$http) {
$("#skills").tagsinput();
$( "#skills" ).change(function() {
$("#skills_input").val($("#skills").val());
});
$scope.getLocation = function()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude + '&sensor=true', function(data){
console.log(data.results[0].formatted_address);
$scope.generateCv.address = data.results[0].formatted_address;
});
});
}
}
});
|
#ifndef RecoBTau_JetTagComputerESProducer_h
#define RecoBTau_JetTagComputerESProducer_h
#include <string>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
#include <memory>
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "RecoBTau/JetTagComputer/interface/JetTagComputerRecord.h"
#include "RecoBTau/JetTagComputer/interface/JetTagComputer.h"
template <typename ConcreteJetTagComputer>
class JetTagComputerESProducer: public edm::ESProducer {
private:
// check that the template parameter inherits from JetTagComputer
static_assert((boost::is_convertible<ConcreteJetTagComputer*,JetTagComputer*>::value));
public:
JetTagComputerESProducer(const edm::ParameterSet & pset) : m_pset(pset) {
setWhatProduced(this, m_pset.getParameter<std::string>("@module_label") );
}
~JetTagComputerESProducer() override {
}
std::unique_ptr<JetTagComputer> produce(const JetTagComputerRecord & record) {
std::unique_ptr<JetTagComputer> jetTagComputer = std::make_unique<ConcreteJetTagComputer>(m_pset);
jetTagComputer->initialize(record);
jetTagComputer->setupDone();
return jetTagComputer;
}
private:
edm::ParameterSet m_pset;
};
#endif // RecoBTau_JetTagComputerESProducer_h
|
/*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:12:06 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/Frameworks/Intents.framework/Intents
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <Intents/Intents-Structs.h>
#import <libobjc.A.dylib/INJSONSerializable.h>
#import <libobjc.A.dylib/NSCopying.h>
#import <libobjc.A.dylib/NSSecureCoding.h>
@class INHomeFilter, NSString, NSNumber;
@interface INAnnouncementRecord : NSObject <INJSONSerializable, NSCopying, NSSecureCoding> {
INHomeFilter* _originator;
NSString* _identifier;
NSNumber* _duration;
}
@property (nonatomic,copy,readonly) INHomeFilter * originator; //@synthesize originator=_originator - In the implementation block
@property (nonatomic,copy,readonly) NSString * identifier; //@synthesize identifier=_identifier - In the implementation block
@property (nonatomic,copy,readonly) NSNumber * duration; //@synthesize duration=_duration - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(BOOL)supportsSecureCoding;
+(id)_intents_decodeWithJSONDecoder:(id)arg1 codableDescription:(id)arg2 from:(id)arg3 ;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)copyWithZone:(NSZone*)arg1 ;
-(NSString *)description;
-(void)encodeWithCoder:(id)arg1 ;
-(id)initWithCoder:(id)arg1 ;
-(NSString *)identifier;
-(NSNumber *)duration;
-(id)_dictionaryRepresentation;
-(INHomeFilter *)originator;
-(id)_intents_encodeWithJSONEncoder:(id)arg1 codableDescription:(id)arg2 ;
-(id)descriptionAtIndent:(unsigned long long)arg1 ;
-(id)initWithOriginator:(id)arg1 identifier:(id)arg2 duration:(id)arg3 ;
@end
|
var dir_2d8fc72a4c2e0737a6aae978c40afcfc =
[
[ "onlab", "dir_9bac2c40513587c991a2fa818689ab99.html", "dir_9bac2c40513587c991a2fa818689ab99" ]
];
|
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import permissions, serializers, viewsets
from rest_framework.exceptions import ValidationError
from api.base import TranslatedModelSerializer
from permissions.api_permissions.drf_permissions import (
GeneralRolePermission,
ServiceSectorRolePermission,
UnitRolePermission,
)
from permissions.models import GeneralRole, ServiceSectorRole, UnitRole
from spaces.models import ServiceSector, Unit, UnitGroup
User = get_user_model()
class BaseRoleSerializer(TranslatedModelSerializer):
user_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source="user"
)
def create(self, validated_data):
request = self.context.get("request", None)
validated_data["assigner"] = request.user if request else None
return super().create(validated_data)
class UnitRoleSerializer(BaseRoleSerializer):
unit_group_id = serializers.PrimaryKeyRelatedField(
queryset=UnitGroup.objects.all(), source="unit_group", required=False
)
unit_id = serializers.PrimaryKeyRelatedField(
queryset=Unit.objects.all(), source="unit", required=False
)
user_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source="user"
)
class Meta:
model = UnitRole
fields = ["unit_id", "unit_group_id", "user_id", "role"]
extra_kwargs = {
"unit_id": {
"help_text": "Id of unit this role is related to. Either 'unit_id' or 'unit_group_id'"
" must be specified.",
},
"unit_group_id": {
"help_text": "Id of unit group this role is related to. Either 'unit_id' or 'unit_group_id'"
" must be specified.",
},
"user_id": {
"help_text": "Id of user this role is assigned to",
},
"role": {
"help_text": "Code of the role choice that contains certain permissions. "
"Choices depends on configuration. Default choices are "
"'admin', 'manager' and 'viewer'.",
},
}
def validate(self, data):
if "unit" not in data and "unit_group" not in data:
raise ValidationError(
_("Either 'unit_group_id' or 'unit_id' must be specified.")
)
return data
class ServiceSectorRoleSerializer(BaseRoleSerializer):
service_sector_id = serializers.PrimaryKeyRelatedField(
queryset=ServiceSector.objects.all(), source="service_sector"
)
user_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source="user"
)
class Meta:
model = ServiceSectorRole
fields = ["service_sector_id", "user_id", "role"]
extra_kwargs = {
"service_sector_id": {
"help_text": "Id of service sector this role is related to",
},
"user_id": {
"help_text": "Id of user this role is assigned to",
},
"role": {
"help_text": "Code of the role choice that contains certain permissions. "
"Choices depends on configuration. By default only choice is 'admin'.",
},
}
class GeneralRoleSerializer(BaseRoleSerializer):
user_id = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), source="user"
)
class Meta:
model = GeneralRole
fields = ["user_id", "role"]
extra_kwargs = {
"user_id": {
"help_text": "Id of user this role is assigned to",
},
"role": {
"help_text": "Code of the role choice that contains certain permissions. "
"Choices depends on configuration. Default choices are "
"'admin', 'manager' and 'viewer'.",
},
}
class UnitRoleViewSet(viewsets.ModelViewSet):
serializer_class = UnitRoleSerializer
permission_classes = (
[permissions.IsAuthenticated & UnitRolePermission]
if not settings.TMP_PERMISSIONS_DISABLED
else [permissions.AllowAny]
)
queryset = UnitRole.objects.all()
class ServiceSectorRoleViewSet(viewsets.ModelViewSet):
serializer_class = ServiceSectorRoleSerializer
permission_classes = (
[permissions.IsAuthenticated & ServiceSectorRolePermission]
if not settings.TMP_PERMISSIONS_DISABLED
else [permissions.AllowAny]
)
queryset = ServiceSectorRole.objects.all()
class GeneralRoleViewSet(viewsets.ModelViewSet):
serializer_class = GeneralRoleSerializer
permission_classes = (
[permissions.IsAuthenticated & GeneralRolePermission]
if not settings.TMP_PERMISSIONS_DISABLED
else [permissions.AllowAny]
)
queryset = GeneralRole.objects.all()
|
/* Include files */
#include <stddef.h>
#include "blas.h"
#include "UAV_Fleet_sfun.h"
#include "c2_UAV_Fleet.h"
#define CHARTINSTANCE_CHARTNUMBER (chartInstance->chartNumber)
#define CHARTINSTANCE_INSTANCENUMBER (chartInstance->instanceNumber)
#include "UAV_Fleet_sfun_debug_macros.h"
#define _SF_MEX_LISTEN_FOR_CTRL_C(S) sf_mex_listen_for_ctrl_c(sfGlobalDebugInstanceStruct,S);
/* Type Definitions */
/* Named Constants */
#define CALL_EVENT (-1)
/* Variable Declarations */
/* Variable Definitions */
static const char * c2_debug_family_names[11] = { "nAC", "nWPs", "nargin",
"nargout", "uavID", "functionID", "dataUAV", "status", "dataFleet", "fcnFleet",
"waypointsFleet" };
/* Function Declarations */
static void initialize_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance);
static void initialize_params_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance);
static void enable_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance);
static void disable_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance);
static void c2_update_debugger_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance);
static const mxArray *get_sim_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance);
static void set_sim_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance, const mxArray *c2_st);
static void finalize_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance);
static void sf_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance);
static void initSimStructsc2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance);
static void init_script_number_translation(uint32_T c2_machineNumber, uint32_T
c2_chartNumber);
static const mxArray *c2_sf_marshallOut(void *chartInstanceVoid, void *c2_inData);
static void c2_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_b_waypointsFleet, const char_T *c2_identifier, real_T c2_y
[600]);
static void c2_b_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[600]);
static void c2_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData);
static const mxArray *c2_b_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static void c2_c_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_fcnFleet, const char_T *c2_identifier, real_T c2_y[2]);
static void c2_d_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[2]);
static void c2_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData);
static const mxArray *c2_c_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static void c2_e_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_dataFleet, const char_T *c2_identifier, real_T c2_y[600]);
static void c2_f_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[600]);
static void c2_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData);
static const mxArray *c2_d_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static const mxArray *c2_e_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static const mxArray *c2_f_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static real_T c2_g_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId);
static void c2_d_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData);
static void c2_info_helper(const mxArray **c2_info);
static const mxArray *c2_emlrt_marshallOut(char * c2_u);
static const mxArray *c2_b_emlrt_marshallOut(uint32_T c2_u);
static const mxArray *c2_g_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData);
static int32_T c2_h_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId);
static void c2_e_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData);
static uint8_T c2_i_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_b_is_active_c2_UAV_Fleet, const char_T *c2_identifier);
static uint8_T c2_j_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId);
static void init_dsm_address_info(SFc2_UAV_FleetInstanceStruct *chartInstance);
/* Function Definitions */
static void initialize_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
chartInstance->c2_sfEvent = CALL_EVENT;
_sfTime_ = (real_T)ssGetT(chartInstance->S);
chartInstance->c2_waypointsFleet_not_empty = FALSE;
chartInstance->c2_is_active_c2_UAV_Fleet = 0U;
}
static void initialize_params_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance)
{
}
static void enable_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
_sfTime_ = (real_T)ssGetT(chartInstance->S);
}
static void disable_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
_sfTime_ = (real_T)ssGetT(chartInstance->S);
}
static void c2_update_debugger_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance)
{
}
static const mxArray *get_sim_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance)
{
const mxArray *c2_st;
const mxArray *c2_y = NULL;
int32_T c2_i0;
real_T c2_u[600];
const mxArray *c2_b_y = NULL;
int32_T c2_i1;
real_T c2_b_u[2];
const mxArray *c2_c_y = NULL;
int32_T c2_i2;
real_T c2_c_u[600];
const mxArray *c2_d_y = NULL;
uint8_T c2_hoistedGlobal;
uint8_T c2_d_u;
const mxArray *c2_e_y = NULL;
real_T (*c2_fcnFleet)[2];
real_T (*c2_dataFleet)[600];
c2_fcnFleet = (real_T (*)[2])ssGetOutputPortSignal(chartInstance->S, 2);
c2_dataFleet = (real_T (*)[600])ssGetOutputPortSignal(chartInstance->S, 1);
c2_st = NULL;
c2_st = NULL;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_createcellarray(4), FALSE);
for (c2_i0 = 0; c2_i0 < 600; c2_i0++) {
c2_u[c2_i0] = (*c2_dataFleet)[c2_i0];
}
c2_b_y = NULL;
sf_mex_assign(&c2_b_y, sf_mex_create("y", c2_u, 0, 0U, 1U, 0U, 3, 3, 100, 2),
FALSE);
sf_mex_setcell(c2_y, 0, c2_b_y);
for (c2_i1 = 0; c2_i1 < 2; c2_i1++) {
c2_b_u[c2_i1] = (*c2_fcnFleet)[c2_i1];
}
c2_c_y = NULL;
sf_mex_assign(&c2_c_y, sf_mex_create("y", c2_b_u, 0, 0U, 1U, 0U, 1, 2), FALSE);
sf_mex_setcell(c2_y, 1, c2_c_y);
for (c2_i2 = 0; c2_i2 < 600; c2_i2++) {
c2_c_u[c2_i2] = chartInstance->c2_waypointsFleet[c2_i2];
}
c2_d_y = NULL;
if (!chartInstance->c2_waypointsFleet_not_empty) {
sf_mex_assign(&c2_d_y, sf_mex_create("y", NULL, 0, 0U, 1U, 0U, 2, 0, 0),
FALSE);
} else {
sf_mex_assign(&c2_d_y, sf_mex_create("y", c2_c_u, 0, 0U, 1U, 0U, 3, 3, 100,
2), FALSE);
}
sf_mex_setcell(c2_y, 2, c2_d_y);
c2_hoistedGlobal = chartInstance->c2_is_active_c2_UAV_Fleet;
c2_d_u = c2_hoistedGlobal;
c2_e_y = NULL;
sf_mex_assign(&c2_e_y, sf_mex_create("y", &c2_d_u, 3, 0U, 0U, 0U, 0), FALSE);
sf_mex_setcell(c2_y, 3, c2_e_y);
sf_mex_assign(&c2_st, c2_y, FALSE);
return c2_st;
}
static void set_sim_state_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance, const mxArray *c2_st)
{
const mxArray *c2_u;
real_T c2_dv0[600];
int32_T c2_i3;
real_T c2_dv1[2];
int32_T c2_i4;
real_T c2_dv2[600];
int32_T c2_i5;
real_T (*c2_dataFleet)[600];
real_T (*c2_fcnFleet)[2];
c2_fcnFleet = (real_T (*)[2])ssGetOutputPortSignal(chartInstance->S, 2);
c2_dataFleet = (real_T (*)[600])ssGetOutputPortSignal(chartInstance->S, 1);
chartInstance->c2_doneDoubleBufferReInit = TRUE;
c2_u = sf_mex_dup(c2_st);
c2_e_emlrt_marshallIn(chartInstance, sf_mex_dup(sf_mex_getcell(c2_u, 0)),
"dataFleet", c2_dv0);
for (c2_i3 = 0; c2_i3 < 600; c2_i3++) {
(*c2_dataFleet)[c2_i3] = c2_dv0[c2_i3];
}
c2_c_emlrt_marshallIn(chartInstance, sf_mex_dup(sf_mex_getcell(c2_u, 1)),
"fcnFleet", c2_dv1);
for (c2_i4 = 0; c2_i4 < 2; c2_i4++) {
(*c2_fcnFleet)[c2_i4] = c2_dv1[c2_i4];
}
c2_emlrt_marshallIn(chartInstance, sf_mex_dup(sf_mex_getcell(c2_u, 2)),
"waypointsFleet", c2_dv2);
for (c2_i5 = 0; c2_i5 < 600; c2_i5++) {
chartInstance->c2_waypointsFleet[c2_i5] = c2_dv2[c2_i5];
}
chartInstance->c2_is_active_c2_UAV_Fleet = c2_i_emlrt_marshallIn(chartInstance,
sf_mex_dup(sf_mex_getcell(c2_u, 3)), "is_active_c2_UAV_Fleet");
sf_mex_destroy(&c2_u);
c2_update_debugger_state_c2_UAV_Fleet(chartInstance);
sf_mex_destroy(&c2_st);
}
static void finalize_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
}
static void sf_c2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
int32_T c2_i6;
int32_T c2_i7;
int32_T c2_i8;
uint16_T c2_hoistedGlobal;
uint16_T c2_b_hoistedGlobal;
real_T c2_c_hoistedGlobal;
uint16_T c2_uavID;
uint16_T c2_functionID;
int32_T c2_i9;
real_T c2_dataUAV[30];
real_T c2_status;
uint32_T c2_debug_family_var_map[11];
real_T c2_nAC;
real_T c2_nWPs;
real_T c2_nargin = 4.0;
real_T c2_nargout = 2.0;
real_T c2_dataFleet[600];
real_T c2_fcnFleet[2];
int32_T c2_i10;
int32_T c2_i11;
int32_T c2_i12;
real_T c2_x[30];
int32_T c2_k;
int32_T c2_b_k;
real_T c2_y[30];
int32_T c2_b_uavID;
int32_T c2_i13;
int32_T c2_i14;
int32_T c2_i15;
static char_T c2_cv0[10] = { 's', 't', 'a', 't', 'u', 's', ' ', '=', ' ', '1'
};
char_T c2_u[10];
const mxArray *c2_b_y = NULL;
int32_T c2_i16;
int32_T c2_i17;
int32_T c2_i18;
uint16_T *c2_c_uavID;
uint16_T *c2_b_functionID;
real_T *c2_b_status;
real_T (*c2_b_dataFleet)[600];
real_T (*c2_b_fcnFleet)[2];
real_T (*c2_b_dataUAV)[30];
c2_b_status = (real_T *)ssGetInputPortSignal(chartInstance->S, 3);
c2_b_fcnFleet = (real_T (*)[2])ssGetOutputPortSignal(chartInstance->S, 2);
c2_b_dataFleet = (real_T (*)[600])ssGetOutputPortSignal(chartInstance->S, 1);
c2_b_dataUAV = (real_T (*)[30])ssGetInputPortSignal(chartInstance->S, 2);
c2_b_functionID = (uint16_T *)ssGetInputPortSignal(chartInstance->S, 1);
c2_c_uavID = (uint16_T *)ssGetInputPortSignal(chartInstance->S, 0);
_SFD_SYMBOL_SCOPE_PUSH(0U, 0U);
_sfTime_ = (real_T)ssGetT(chartInstance->S);
_SFD_CC_CALL(CHART_ENTER_SFUNCTION_TAG, 1U, chartInstance->c2_sfEvent);
_SFD_DATA_RANGE_CHECK((real_T)*c2_c_uavID, 0U);
_SFD_DATA_RANGE_CHECK((real_T)*c2_b_functionID, 1U);
for (c2_i6 = 0; c2_i6 < 30; c2_i6++) {
_SFD_DATA_RANGE_CHECK((*c2_b_dataUAV)[c2_i6], 2U);
}
for (c2_i7 = 0; c2_i7 < 600; c2_i7++) {
_SFD_DATA_RANGE_CHECK((*c2_b_dataFleet)[c2_i7], 3U);
}
for (c2_i8 = 0; c2_i8 < 2; c2_i8++) {
_SFD_DATA_RANGE_CHECK((*c2_b_fcnFleet)[c2_i8], 4U);
}
_SFD_DATA_RANGE_CHECK(*c2_b_status, 5U);
chartInstance->c2_sfEvent = CALL_EVENT;
_SFD_CC_CALL(CHART_ENTER_DURING_FUNCTION_TAG, 1U, chartInstance->c2_sfEvent);
c2_hoistedGlobal = *c2_c_uavID;
c2_b_hoistedGlobal = *c2_b_functionID;
c2_c_hoistedGlobal = *c2_b_status;
c2_uavID = c2_hoistedGlobal;
c2_functionID = c2_b_hoistedGlobal;
for (c2_i9 = 0; c2_i9 < 30; c2_i9++) {
c2_dataUAV[c2_i9] = (*c2_b_dataUAV)[c2_i9];
}
c2_status = c2_c_hoistedGlobal;
_SFD_SYMBOL_SCOPE_PUSH_EML(0U, 11U, 11U, c2_debug_family_names,
c2_debug_family_var_map);
_SFD_SYMBOL_SCOPE_ADD_EML(&c2_nAC, 0U, c2_d_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c2_nWPs, 1U, c2_d_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c2_nargin, 2U, c2_d_sf_marshallOut,
c2_d_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c2_nargout, 3U, c2_d_sf_marshallOut,
c2_d_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML(&c2_uavID, 4U, c2_f_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c2_functionID, 5U, c2_f_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(c2_dataUAV, 6U, c2_e_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c2_status, 7U, c2_d_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(c2_dataFleet, 8U, c2_c_sf_marshallOut,
c2_c_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(c2_fcnFleet, 9U, c2_b_sf_marshallOut,
c2_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(chartInstance->c2_waypointsFleet, 10U,
c2_sf_marshallOut, c2_sf_marshallIn);
CV_EML_FCN(0, 0);
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 3);
c2_nAC = 2.0;
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 4);
c2_nWPs = 10.0;
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 7);
for (c2_i10 = 0; c2_i10 < 2; c2_i10++) {
c2_fcnFleet[c2_i10] = 0.0;
}
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 9);
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 11);
if (CV_EML_IF(0, 1, 0, !chartInstance->c2_waypointsFleet_not_empty)) {
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 12);
for (c2_i11 = 0; c2_i11 < 600; c2_i11++) {
chartInstance->c2_waypointsFleet[c2_i11] = 0.0;
}
chartInstance->c2_waypointsFleet_not_empty = TRUE;
}
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 15);
switch (c2_functionID) {
case 1U:
CV_EML_SWITCH(0, 1, 0, 1);
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 17);
if (CV_EML_IF(0, 1, 1, (real_T)c2_uavID <= c2_nAC)) {
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 18);
for (c2_i12 = 0; c2_i12 < 30; c2_i12++) {
c2_x[c2_i12] = c2_dataUAV[c2_i12];
}
for (c2_k = 1; c2_k < 31; c2_k++) {
c2_b_k = c2_k;
c2_y[_SFD_EML_ARRAY_BOUNDS_CHECK("", (int32_T)_SFD_INTEGER_CHECK("",
(real_T)c2_b_k), 1, 30, 1, 0) - 1] = c2_x[_SFD_EML_ARRAY_BOUNDS_CHECK(
"", (int32_T)_SFD_INTEGER_CHECK("", (real_T)c2_b_k), 1, 30, 1, 0) - 1];
}
c2_b_uavID = (uint16_T)_SFD_EML_ARRAY_BOUNDS_CHECK("waypointsFleet",
(int32_T)(uint16_T)_SFD_INTEGER_CHECK("uavID", (real_T)c2_uavID), 1, 2,
3, 0) - 1;
for (c2_i13 = 0; c2_i13 < 10; c2_i13++) {
for (c2_i14 = 0; c2_i14 < 3; c2_i14++) {
chartInstance->c2_waypointsFleet[(c2_i14 + 3 * c2_i13) + 300 *
c2_b_uavID] = c2_y[c2_i14 + 3 * c2_i13];
}
}
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 19);
if (CV_EML_IF(0, 1, 2, c2_status == 1.0)) {
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 20);
c2_fcnFleet[(uint16_T)_SFD_EML_ARRAY_BOUNDS_CHECK("fcnFleet", (int32_T)
(uint16_T)_SFD_INTEGER_CHECK("uavID", (real_T)c2_uavID), 1, 2, 1, 0) -
1] = (real_T)c2_functionID;
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 21);
for (c2_i15 = 0; c2_i15 < 10; c2_i15++) {
c2_u[c2_i15] = c2_cv0[c2_i15];
}
c2_b_y = NULL;
sf_mex_assign(&c2_b_y, sf_mex_create("y", c2_u, 10, 0U, 1U, 0U, 2, 1, 10),
FALSE);
sf_mex_call_debug("disp", 0U, 1U, 14, c2_b_y);
}
}
break;
default:
CV_EML_SWITCH(0, 1, 0, 0);
break;
}
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, 33);
for (c2_i16 = 0; c2_i16 < 600; c2_i16++) {
c2_dataFleet[c2_i16] = chartInstance->c2_waypointsFleet[c2_i16];
}
_SFD_EML_CALL(0U, chartInstance->c2_sfEvent, -33);
_SFD_SYMBOL_SCOPE_POP();
for (c2_i17 = 0; c2_i17 < 600; c2_i17++) {
(*c2_b_dataFleet)[c2_i17] = c2_dataFleet[c2_i17];
}
for (c2_i18 = 0; c2_i18 < 2; c2_i18++) {
(*c2_b_fcnFleet)[c2_i18] = c2_fcnFleet[c2_i18];
}
_SFD_CC_CALL(EXIT_OUT_OF_FUNCTION_TAG, 1U, chartInstance->c2_sfEvent);
_SFD_SYMBOL_SCOPE_POP();
_SFD_CHECK_FOR_STATE_INCONSISTENCY(_UAV_FleetMachineNumber_,
chartInstance->chartNumber, chartInstance->instanceNumber);
}
static void initSimStructsc2_UAV_Fleet(SFc2_UAV_FleetInstanceStruct
*chartInstance)
{
}
static void init_script_number_translation(uint32_T c2_machineNumber, uint32_T
c2_chartNumber)
{
}
static const mxArray *c2_sf_marshallOut(void *chartInstanceVoid, void *c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
int32_T c2_i19;
int32_T c2_i20;
int32_T c2_i21;
int32_T c2_i22;
int32_T c2_i23;
real_T c2_b_inData[600];
int32_T c2_i24;
int32_T c2_i25;
int32_T c2_i26;
int32_T c2_i27;
int32_T c2_i28;
real_T c2_u[600];
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
c2_i19 = 0;
for (c2_i20 = 0; c2_i20 < 2; c2_i20++) {
c2_i21 = 0;
for (c2_i22 = 0; c2_i22 < 100; c2_i22++) {
for (c2_i23 = 0; c2_i23 < 3; c2_i23++) {
c2_b_inData[(c2_i23 + c2_i21) + c2_i19] = (*(real_T (*)[600])c2_inData)
[(c2_i23 + c2_i21) + c2_i19];
}
c2_i21 += 3;
}
c2_i19 += 300;
}
c2_i24 = 0;
for (c2_i25 = 0; c2_i25 < 2; c2_i25++) {
c2_i26 = 0;
for (c2_i27 = 0; c2_i27 < 100; c2_i27++) {
for (c2_i28 = 0; c2_i28 < 3; c2_i28++) {
c2_u[(c2_i28 + c2_i26) + c2_i24] = c2_b_inData[(c2_i28 + c2_i26) +
c2_i24];
}
c2_i26 += 3;
}
c2_i24 += 300;
}
c2_y = NULL;
if (!chartInstance->c2_waypointsFleet_not_empty) {
sf_mex_assign(&c2_y, sf_mex_create("y", NULL, 0, 0U, 1U, 0U, 2, 0, 0), FALSE);
} else {
sf_mex_assign(&c2_y, sf_mex_create("y", c2_u, 0, 0U, 1U, 0U, 3, 3, 100, 2),
FALSE);
}
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static void c2_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_b_waypointsFleet, const char_T *c2_identifier, real_T c2_y
[600])
{
emlrtMsgIdentifier c2_thisId;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_b_waypointsFleet),
&c2_thisId, c2_y);
sf_mex_destroy(&c2_b_waypointsFleet);
}
static void c2_b_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[600])
{
real_T c2_dv3[600];
int32_T c2_i29;
if (mxIsEmpty(c2_u)) {
chartInstance->c2_waypointsFleet_not_empty = FALSE;
} else {
chartInstance->c2_waypointsFleet_not_empty = TRUE;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), c2_dv3, 1, 0, 0U, 1, 0U, 3, 3,
100, 2);
for (c2_i29 = 0; c2_i29 < 600; c2_i29++) {
c2_y[c2_i29] = c2_dv3[c2_i29];
}
}
sf_mex_destroy(&c2_u);
}
static void c2_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData)
{
const mxArray *c2_b_waypointsFleet;
const char_T *c2_identifier;
emlrtMsgIdentifier c2_thisId;
real_T c2_y[600];
int32_T c2_i30;
int32_T c2_i31;
int32_T c2_i32;
int32_T c2_i33;
int32_T c2_i34;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_b_waypointsFleet = sf_mex_dup(c2_mxArrayInData);
c2_identifier = c2_varName;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_b_waypointsFleet),
&c2_thisId, c2_y);
sf_mex_destroy(&c2_b_waypointsFleet);
c2_i30 = 0;
for (c2_i31 = 0; c2_i31 < 2; c2_i31++) {
c2_i32 = 0;
for (c2_i33 = 0; c2_i33 < 100; c2_i33++) {
for (c2_i34 = 0; c2_i34 < 3; c2_i34++) {
(*(real_T (*)[600])c2_outData)[(c2_i34 + c2_i32) + c2_i30] = c2_y
[(c2_i34 + c2_i32) + c2_i30];
}
c2_i32 += 3;
}
c2_i30 += 300;
}
sf_mex_destroy(&c2_mxArrayInData);
}
static const mxArray *c2_b_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
int32_T c2_i35;
real_T c2_b_inData[2];
int32_T c2_i36;
real_T c2_u[2];
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
for (c2_i35 = 0; c2_i35 < 2; c2_i35++) {
c2_b_inData[c2_i35] = (*(real_T (*)[2])c2_inData)[c2_i35];
}
for (c2_i36 = 0; c2_i36 < 2; c2_i36++) {
c2_u[c2_i36] = c2_b_inData[c2_i36];
}
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", c2_u, 0, 0U, 1U, 0U, 1, 2), FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static void c2_c_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_fcnFleet, const char_T *c2_identifier, real_T c2_y[2])
{
emlrtMsgIdentifier c2_thisId;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_d_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_fcnFleet), &c2_thisId, c2_y);
sf_mex_destroy(&c2_fcnFleet);
}
static void c2_d_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[2])
{
real_T c2_dv4[2];
int32_T c2_i37;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), c2_dv4, 1, 0, 0U, 1, 0U, 1, 2);
for (c2_i37 = 0; c2_i37 < 2; c2_i37++) {
c2_y[c2_i37] = c2_dv4[c2_i37];
}
sf_mex_destroy(&c2_u);
}
static void c2_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData)
{
const mxArray *c2_fcnFleet;
const char_T *c2_identifier;
emlrtMsgIdentifier c2_thisId;
real_T c2_y[2];
int32_T c2_i38;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_fcnFleet = sf_mex_dup(c2_mxArrayInData);
c2_identifier = c2_varName;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_d_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_fcnFleet), &c2_thisId, c2_y);
sf_mex_destroy(&c2_fcnFleet);
for (c2_i38 = 0; c2_i38 < 2; c2_i38++) {
(*(real_T (*)[2])c2_outData)[c2_i38] = c2_y[c2_i38];
}
sf_mex_destroy(&c2_mxArrayInData);
}
static const mxArray *c2_c_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
int32_T c2_i39;
int32_T c2_i40;
int32_T c2_i41;
int32_T c2_i42;
int32_T c2_i43;
real_T c2_b_inData[600];
int32_T c2_i44;
int32_T c2_i45;
int32_T c2_i46;
int32_T c2_i47;
int32_T c2_i48;
real_T c2_u[600];
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
c2_i39 = 0;
for (c2_i40 = 0; c2_i40 < 2; c2_i40++) {
c2_i41 = 0;
for (c2_i42 = 0; c2_i42 < 100; c2_i42++) {
for (c2_i43 = 0; c2_i43 < 3; c2_i43++) {
c2_b_inData[(c2_i43 + c2_i41) + c2_i39] = (*(real_T (*)[600])c2_inData)
[(c2_i43 + c2_i41) + c2_i39];
}
c2_i41 += 3;
}
c2_i39 += 300;
}
c2_i44 = 0;
for (c2_i45 = 0; c2_i45 < 2; c2_i45++) {
c2_i46 = 0;
for (c2_i47 = 0; c2_i47 < 100; c2_i47++) {
for (c2_i48 = 0; c2_i48 < 3; c2_i48++) {
c2_u[(c2_i48 + c2_i46) + c2_i44] = c2_b_inData[(c2_i48 + c2_i46) +
c2_i44];
}
c2_i46 += 3;
}
c2_i44 += 300;
}
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", c2_u, 0, 0U, 1U, 0U, 3, 3, 100, 2),
FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static void c2_e_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_dataFleet, const char_T *c2_identifier, real_T c2_y[600])
{
emlrtMsgIdentifier c2_thisId;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_f_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_dataFleet), &c2_thisId,
c2_y);
sf_mex_destroy(&c2_dataFleet);
}
static void c2_f_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId, real_T c2_y[600])
{
real_T c2_dv5[600];
int32_T c2_i49;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), c2_dv5, 1, 0, 0U, 1, 0U, 3, 3,
100, 2);
for (c2_i49 = 0; c2_i49 < 600; c2_i49++) {
c2_y[c2_i49] = c2_dv5[c2_i49];
}
sf_mex_destroy(&c2_u);
}
static void c2_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData)
{
const mxArray *c2_dataFleet;
const char_T *c2_identifier;
emlrtMsgIdentifier c2_thisId;
real_T c2_y[600];
int32_T c2_i50;
int32_T c2_i51;
int32_T c2_i52;
int32_T c2_i53;
int32_T c2_i54;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_dataFleet = sf_mex_dup(c2_mxArrayInData);
c2_identifier = c2_varName;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_f_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_dataFleet), &c2_thisId,
c2_y);
sf_mex_destroy(&c2_dataFleet);
c2_i50 = 0;
for (c2_i51 = 0; c2_i51 < 2; c2_i51++) {
c2_i52 = 0;
for (c2_i53 = 0; c2_i53 < 100; c2_i53++) {
for (c2_i54 = 0; c2_i54 < 3; c2_i54++) {
(*(real_T (*)[600])c2_outData)[(c2_i54 + c2_i52) + c2_i50] = c2_y
[(c2_i54 + c2_i52) + c2_i50];
}
c2_i52 += 3;
}
c2_i50 += 300;
}
sf_mex_destroy(&c2_mxArrayInData);
}
static const mxArray *c2_d_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
real_T c2_u;
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
c2_u = *(real_T *)c2_inData;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", &c2_u, 0, 0U, 0U, 0U, 0), FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static const mxArray *c2_e_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
int32_T c2_i55;
real_T c2_b_inData[30];
int32_T c2_i56;
real_T c2_u[30];
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
for (c2_i55 = 0; c2_i55 < 30; c2_i55++) {
c2_b_inData[c2_i55] = (*(real_T (*)[30])c2_inData)[c2_i55];
}
for (c2_i56 = 0; c2_i56 < 30; c2_i56++) {
c2_u[c2_i56] = c2_b_inData[c2_i56];
}
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", c2_u, 0, 0U, 1U, 0U, 1, 30), FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static const mxArray *c2_f_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
uint16_T c2_u;
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
c2_u = *(uint16_T *)c2_inData;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", &c2_u, 5, 0U, 0U, 0U, 0), FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static real_T c2_g_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId)
{
real_T c2_y;
real_T c2_d0;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), &c2_d0, 1, 0, 0U, 0, 0U, 0);
c2_y = c2_d0;
sf_mex_destroy(&c2_u);
return c2_y;
}
static void c2_d_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData)
{
const mxArray *c2_nargout;
const char_T *c2_identifier;
emlrtMsgIdentifier c2_thisId;
real_T c2_y;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_nargout = sf_mex_dup(c2_mxArrayInData);
c2_identifier = c2_varName;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_y = c2_g_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_nargout), &c2_thisId);
sf_mex_destroy(&c2_nargout);
*(real_T *)c2_outData = c2_y;
sf_mex_destroy(&c2_mxArrayInData);
}
const mxArray *sf_c2_UAV_Fleet_get_eml_resolved_functions_info(void)
{
const mxArray *c2_nameCaptureInfo = NULL;
c2_nameCaptureInfo = NULL;
sf_mex_assign(&c2_nameCaptureInfo, sf_mex_createstruct("structure", 2, 27, 1),
FALSE);
c2_info_helper(&c2_nameCaptureInfo);
sf_mex_emlrtNameCapturePostProcessR2012a(&c2_nameCaptureInfo);
return c2_nameCaptureInfo;
}
static void c2_info_helper(const mxArray **c2_info)
{
const mxArray *c2_rhs0 = NULL;
const mxArray *c2_lhs0 = NULL;
const mxArray *c2_rhs1 = NULL;
const mxArray *c2_lhs1 = NULL;
const mxArray *c2_rhs2 = NULL;
const mxArray *c2_lhs2 = NULL;
const mxArray *c2_rhs3 = NULL;
const mxArray *c2_lhs3 = NULL;
const mxArray *c2_rhs4 = NULL;
const mxArray *c2_lhs4 = NULL;
const mxArray *c2_rhs5 = NULL;
const mxArray *c2_lhs5 = NULL;
const mxArray *c2_rhs6 = NULL;
const mxArray *c2_lhs6 = NULL;
const mxArray *c2_rhs7 = NULL;
const mxArray *c2_lhs7 = NULL;
const mxArray *c2_rhs8 = NULL;
const mxArray *c2_lhs8 = NULL;
const mxArray *c2_rhs9 = NULL;
const mxArray *c2_lhs9 = NULL;
const mxArray *c2_rhs10 = NULL;
const mxArray *c2_lhs10 = NULL;
const mxArray *c2_rhs11 = NULL;
const mxArray *c2_lhs11 = NULL;
const mxArray *c2_rhs12 = NULL;
const mxArray *c2_lhs12 = NULL;
const mxArray *c2_rhs13 = NULL;
const mxArray *c2_lhs13 = NULL;
const mxArray *c2_rhs14 = NULL;
const mxArray *c2_lhs14 = NULL;
const mxArray *c2_rhs15 = NULL;
const mxArray *c2_lhs15 = NULL;
const mxArray *c2_rhs16 = NULL;
const mxArray *c2_lhs16 = NULL;
const mxArray *c2_rhs17 = NULL;
const mxArray *c2_lhs17 = NULL;
const mxArray *c2_rhs18 = NULL;
const mxArray *c2_lhs18 = NULL;
const mxArray *c2_rhs19 = NULL;
const mxArray *c2_lhs19 = NULL;
const mxArray *c2_rhs20 = NULL;
const mxArray *c2_lhs20 = NULL;
const mxArray *c2_rhs21 = NULL;
const mxArray *c2_lhs21 = NULL;
const mxArray *c2_rhs22 = NULL;
const mxArray *c2_lhs22 = NULL;
const mxArray *c2_rhs23 = NULL;
const mxArray *c2_lhs23 = NULL;
const mxArray *c2_rhs24 = NULL;
const mxArray *c2_lhs24 = NULL;
const mxArray *c2_rhs25 = NULL;
const mxArray *c2_lhs25 = NULL;
const mxArray *c2_rhs26 = NULL;
const mxArray *c2_lhs26 = NULL;
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "context", "context", 0);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("reshape"), "name", "name", 0);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 0);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m"), "resolved",
"resolved", 0);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1286840368U), "fileTimeLo",
"fileTimeLo", 0);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 0);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 0);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 0);
sf_mex_assign(&c2_rhs0, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs0, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs0), "rhs", "rhs", 0);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs0), "lhs", "lhs", 0);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m"), "context",
"context", 1);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 1);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 1);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 1);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 1);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 1);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 1);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 1);
sf_mex_assign(&c2_rhs1, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs1, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs1), "rhs", "rhs", 1);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs1), "lhs", "lhs", 1);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m!reshape_varargin_to_size"),
"context", "context", 2);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 2);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 2);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 2);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 2);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 2);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 2);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 2);
sf_mex_assign(&c2_rhs2, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs2, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs2), "rhs", "rhs", 2);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs2), "lhs", "lhs", 2);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m!varargin_nempty"),
"context", "context", 3);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 3);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 3);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 3);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 3);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 3);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 3);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 3);
sf_mex_assign(&c2_rhs3, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs3, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs3), "rhs", "rhs", 3);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs3), "lhs", "lhs", 3);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m!reshape_varargin_to_size"),
"context", "context", 4);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_assert_valid_size_arg"),
"name", "name", 4);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 4);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"),
"resolved", "resolved", 4);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1368204630U), "fileTimeLo",
"fileTimeLo", 4);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 4);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 4);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 4);
sf_mex_assign(&c2_rhs4, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs4, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs4), "rhs", "rhs", 4);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs4), "lhs", "lhs", 4);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"),
"context", "context", 5);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"coder.internal.isBuiltInNumeric"), "name", "name", 5);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 5);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"),
"resolved", "resolved", 5);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1363732556U), "fileTimeLo",
"fileTimeLo", 5);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 5);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 5);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 5);
sf_mex_assign(&c2_rhs5, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs5, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs5), "rhs", "rhs", 5);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs5), "lhs", "lhs", 5);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isintegral"),
"context", "context", 6);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("isinf"), "name", "name", 6);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 6);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isinf.m"), "resolved",
"resolved", 6);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1363731856U), "fileTimeLo",
"fileTimeLo", 6);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 6);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 6);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 6);
sf_mex_assign(&c2_rhs6, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs6, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs6), "rhs", "rhs", 6);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs6), "lhs", "lhs", 6);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/isinf.m"), "context",
"context", 7);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"coder.internal.isBuiltInNumeric"), "name", "name", 7);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 7);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"),
"resolved", "resolved", 7);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1363732556U), "fileTimeLo",
"fileTimeLo", 7);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 7);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 7);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 7);
sf_mex_assign(&c2_rhs7, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs7, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs7), "rhs", "rhs", 7);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs7), "lhs", "lhs", 7);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"),
"context", "context", 8);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_is_integer_class"), "name",
"name", 8);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 8);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_is_integer_class.m"),
"resolved", "resolved", 8);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1286840382U), "fileTimeLo",
"fileTimeLo", 8);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 8);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 8);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 8);
sf_mex_assign(&c2_rhs8, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs8, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs8), "rhs", "rhs", 8);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs8), "lhs", "lhs", 8);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"),
"context", "context", 9);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("intmax"), "name", "name", 9);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 9);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved",
"resolved", 9);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1362283482U), "fileTimeLo",
"fileTimeLo", 9);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 9);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 9);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 9);
sf_mex_assign(&c2_rhs9, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs9, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs9), "rhs", "rhs", 9);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs9), "lhs", "lhs", 9);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"),
"context", "context", 10);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("intmin"), "name", "name", 10);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 10);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmin.m"), "resolved",
"resolved", 10);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1362283482U), "fileTimeLo",
"fileTimeLo", 10);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 10);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 10);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 10);
sf_mex_assign(&c2_rhs10, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs10, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs10), "rhs", "rhs",
10);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs10), "lhs", "lhs",
10);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!isinbounds"),
"context", "context", 11);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("coder.internal.indexIntRelop"),
"name", "name", 11);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 11);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m"),
"resolved", "resolved", 11);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1326749922U), "fileTimeLo",
"fileTimeLo", 11);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 11);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 11);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 11);
sf_mex_assign(&c2_rhs11, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs11, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs11), "rhs", "rhs",
11);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs11), "lhs", "lhs",
11);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m!float_class_contains_indexIntClass"),
"context", "context", 12);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_float_model"), "name",
"name", 12);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 12);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_float_model.m"),
"resolved", "resolved", 12);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1326749596U), "fileTimeLo",
"fileTimeLo", 12);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 12);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 12);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 12);
sf_mex_assign(&c2_rhs12, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs12, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs12), "rhs", "rhs",
12);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs12), "lhs", "lhs",
12);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/indexIntRelop.m!is_signed_indexIntClass"),
"context", "context", 13);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("intmin"), "name", "name", 13);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 13);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmin.m"), "resolved",
"resolved", 13);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1362283482U), "fileTimeLo",
"fileTimeLo", 13);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 13);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 13);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 13);
sf_mex_assign(&c2_rhs13, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs13, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs13), "rhs", "rhs",
13);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs13), "lhs", "lhs",
13);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m!numel_for_size"),
"context", "context", 14);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("mtimes"), "name", "name", 14);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 14);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m"), "resolved",
"resolved", 14);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1363731878U), "fileTimeLo",
"fileTimeLo", 14);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 14);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 14);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 14);
sf_mex_assign(&c2_rhs14, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs14, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs14), "rhs", "rhs",
14);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs14), "lhs", "lhs",
14);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m!common_checks"),
"context", "context", 15);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"coder.internal.isBuiltInNumeric"), "name", "name", 15);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 15);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXE]$matlabroot$/toolbox/shared/coder/coder/+coder/+internal/isBuiltInNumeric.m"),
"resolved", "resolved", 15);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1363732556U), "fileTimeLo",
"fileTimeLo", 15);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 15);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 15);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 15);
sf_mex_assign(&c2_rhs15, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs15, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs15), "rhs", "rhs",
15);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs15), "lhs", "lhs",
15);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"),
"context", "context", 16);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 16);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 16);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 16);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 16);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 16);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 16);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 16);
sf_mex_assign(&c2_rhs16, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs16, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs16), "rhs", "rhs",
16);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs16), "lhs", "lhs",
16);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_assert_valid_size_arg.m"),
"context", "context", 17);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("intmax"), "name", "name", 17);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 17);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved",
"resolved", 17);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1362283482U), "fileTimeLo",
"fileTimeLo", 17);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 17);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 17);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 17);
sf_mex_assign(&c2_rhs17, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs17, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs17), "rhs", "rhs",
17);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs17), "lhs", "lhs",
17);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m!reshape_varargin_to_size"),
"context", "context", 18);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_prod"), "name",
"name", 18);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("coder.internal.indexInt"),
"dominantType", "dominantType", 18);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"),
"resolved", "resolved", 18);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1286840380U), "fileTimeLo",
"fileTimeLo", 18);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 18);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 18);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 18);
sf_mex_assign(&c2_rhs18, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs18, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs18), "rhs", "rhs",
18);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs18), "lhs", "lhs",
18);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "context",
"context", 19);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 19);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 19);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 19);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 19);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 19);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 19);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 19);
sf_mex_assign(&c2_rhs19, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs19, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs19), "rhs", "rhs",
19);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs19), "lhs", "lhs",
19);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "context",
"context", 20);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"eml_int_forloop_overflow_check"), "name", "name", 20);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 20);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m"),
"resolved", "resolved", 20);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1346531940U), "fileTimeLo",
"fileTimeLo", 20);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 20);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 20);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 20);
sf_mex_assign(&c2_rhs20, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs20, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs20), "rhs", "rhs",
20);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs20), "lhs", "lhs",
20);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m!eml_int_forloop_overflow_check_helper"),
"context", "context", 21);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("intmax"), "name", "name", 21);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 21);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/intmax.m"), "resolved",
"resolved", 21);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1362283482U), "fileTimeLo",
"fileTimeLo", 21);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 21);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 21);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 21);
sf_mex_assign(&c2_rhs21, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs21, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs21), "rhs", "rhs",
21);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs21), "lhs", "lhs",
21);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_prod.m"), "context",
"context", 22);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_times"), "name",
"name", 22);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("coder.internal.indexInt"),
"dominantType", "dominantType", 22);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_times.m"),
"resolved", "resolved", 22);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1286840380U), "fileTimeLo",
"fileTimeLo", 22);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 22);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 22);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 22);
sf_mex_assign(&c2_rhs22, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs22, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs22), "rhs", "rhs",
22);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs22), "lhs", "lhs",
22);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_times.m"),
"context", "context", 23);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_index_class"), "name",
"name", 23);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 23);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_index_class.m"),
"resolved", "resolved", 23);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1323192178U), "fileTimeLo",
"fileTimeLo", 23);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 23);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 23);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 23);
sf_mex_assign(&c2_rhs23, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs23, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs23), "rhs", "rhs",
23);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs23), "lhs", "lhs",
23);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m"), "context",
"context", 24);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("eml_scalar_eg"), "name",
"name", 24);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("double"), "dominantType",
"dominantType", 24);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m"), "resolved",
"resolved", 24);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1286840396U), "fileTimeLo",
"fileTimeLo", 24);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 24);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 24);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 24);
sf_mex_assign(&c2_rhs24, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs24, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs24), "rhs", "rhs",
24);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs24), "lhs", "lhs",
24);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elmat/reshape.m"), "context",
"context", 25);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"eml_int_forloop_overflow_check"), "name", "name", 25);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "dominantType",
"dominantType", 25);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_int_forloop_overflow_check.m"),
"resolved", "resolved", 25);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(1346531940U), "fileTimeLo",
"fileTimeLo", 25);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "fileTimeHi",
"fileTimeHi", 25);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeLo",
"mFileTimeLo", 25);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(0U), "mFileTimeHi",
"mFileTimeHi", 25);
sf_mex_assign(&c2_rhs25, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs25, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs25), "rhs", "rhs",
25);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs25), "lhs", "lhs",
25);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(""), "context", "context", 26);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("disp"), "name", "name", 26);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut("char"), "dominantType",
"dominantType", 26);
sf_mex_addfield(*c2_info, c2_emlrt_marshallOut(
"[IXMB]$matlabroot$/toolbox/matlab/lang/disp"), "resolved", "resolved", 26);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(MAX_uint32_T), "fileTimeLo",
"fileTimeLo", 26);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(MAX_uint32_T), "fileTimeHi",
"fileTimeHi", 26);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(MAX_uint32_T), "mFileTimeLo",
"mFileTimeLo", 26);
sf_mex_addfield(*c2_info, c2_b_emlrt_marshallOut(MAX_uint32_T), "mFileTimeHi",
"mFileTimeHi", 26);
sf_mex_assign(&c2_rhs26, sf_mex_createcellarray(0), FALSE);
sf_mex_assign(&c2_lhs26, sf_mex_createcellarray(0), FALSE);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_rhs26), "rhs", "rhs",
26);
sf_mex_addfield(*c2_info, sf_mex_duplicatearraysafe(&c2_lhs26), "lhs", "lhs",
26);
sf_mex_destroy(&c2_rhs0);
sf_mex_destroy(&c2_lhs0);
sf_mex_destroy(&c2_rhs1);
sf_mex_destroy(&c2_lhs1);
sf_mex_destroy(&c2_rhs2);
sf_mex_destroy(&c2_lhs2);
sf_mex_destroy(&c2_rhs3);
sf_mex_destroy(&c2_lhs3);
sf_mex_destroy(&c2_rhs4);
sf_mex_destroy(&c2_lhs4);
sf_mex_destroy(&c2_rhs5);
sf_mex_destroy(&c2_lhs5);
sf_mex_destroy(&c2_rhs6);
sf_mex_destroy(&c2_lhs6);
sf_mex_destroy(&c2_rhs7);
sf_mex_destroy(&c2_lhs7);
sf_mex_destroy(&c2_rhs8);
sf_mex_destroy(&c2_lhs8);
sf_mex_destroy(&c2_rhs9);
sf_mex_destroy(&c2_lhs9);
sf_mex_destroy(&c2_rhs10);
sf_mex_destroy(&c2_lhs10);
sf_mex_destroy(&c2_rhs11);
sf_mex_destroy(&c2_lhs11);
sf_mex_destroy(&c2_rhs12);
sf_mex_destroy(&c2_lhs12);
sf_mex_destroy(&c2_rhs13);
sf_mex_destroy(&c2_lhs13);
sf_mex_destroy(&c2_rhs14);
sf_mex_destroy(&c2_lhs14);
sf_mex_destroy(&c2_rhs15);
sf_mex_destroy(&c2_lhs15);
sf_mex_destroy(&c2_rhs16);
sf_mex_destroy(&c2_lhs16);
sf_mex_destroy(&c2_rhs17);
sf_mex_destroy(&c2_lhs17);
sf_mex_destroy(&c2_rhs18);
sf_mex_destroy(&c2_lhs18);
sf_mex_destroy(&c2_rhs19);
sf_mex_destroy(&c2_lhs19);
sf_mex_destroy(&c2_rhs20);
sf_mex_destroy(&c2_lhs20);
sf_mex_destroy(&c2_rhs21);
sf_mex_destroy(&c2_lhs21);
sf_mex_destroy(&c2_rhs22);
sf_mex_destroy(&c2_lhs22);
sf_mex_destroy(&c2_rhs23);
sf_mex_destroy(&c2_lhs23);
sf_mex_destroy(&c2_rhs24);
sf_mex_destroy(&c2_lhs24);
sf_mex_destroy(&c2_rhs25);
sf_mex_destroy(&c2_lhs25);
sf_mex_destroy(&c2_rhs26);
sf_mex_destroy(&c2_lhs26);
}
static const mxArray *c2_emlrt_marshallOut(char * c2_u)
{
const mxArray *c2_y = NULL;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", c2_u, 15, 0U, 0U, 0U, 2, 1, strlen
(c2_u)), FALSE);
return c2_y;
}
static const mxArray *c2_b_emlrt_marshallOut(uint32_T c2_u)
{
const mxArray *c2_y = NULL;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", &c2_u, 7, 0U, 0U, 0U, 0), FALSE);
return c2_y;
}
static const mxArray *c2_g_sf_marshallOut(void *chartInstanceVoid, void
*c2_inData)
{
const mxArray *c2_mxArrayOutData = NULL;
int32_T c2_u;
const mxArray *c2_y = NULL;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_mxArrayOutData = NULL;
c2_u = *(int32_T *)c2_inData;
c2_y = NULL;
sf_mex_assign(&c2_y, sf_mex_create("y", &c2_u, 6, 0U, 0U, 0U, 0), FALSE);
sf_mex_assign(&c2_mxArrayOutData, c2_y, FALSE);
return c2_mxArrayOutData;
}
static int32_T c2_h_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId)
{
int32_T c2_y;
int32_T c2_i57;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), &c2_i57, 1, 6, 0U, 0, 0U, 0);
c2_y = c2_i57;
sf_mex_destroy(&c2_u);
return c2_y;
}
static void c2_e_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c2_mxArrayInData, const char_T *c2_varName, void *c2_outData)
{
const mxArray *c2_b_sfEvent;
const char_T *c2_identifier;
emlrtMsgIdentifier c2_thisId;
int32_T c2_y;
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)chartInstanceVoid;
c2_b_sfEvent = sf_mex_dup(c2_mxArrayInData);
c2_identifier = c2_varName;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_y = c2_h_emlrt_marshallIn(chartInstance, sf_mex_dup(c2_b_sfEvent),
&c2_thisId);
sf_mex_destroy(&c2_b_sfEvent);
*(int32_T *)c2_outData = c2_y;
sf_mex_destroy(&c2_mxArrayInData);
}
static uint8_T c2_i_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_b_is_active_c2_UAV_Fleet, const char_T *c2_identifier)
{
uint8_T c2_y;
emlrtMsgIdentifier c2_thisId;
c2_thisId.fIdentifier = c2_identifier;
c2_thisId.fParent = NULL;
c2_y = c2_j_emlrt_marshallIn(chartInstance, sf_mex_dup
(c2_b_is_active_c2_UAV_Fleet), &c2_thisId);
sf_mex_destroy(&c2_b_is_active_c2_UAV_Fleet);
return c2_y;
}
static uint8_T c2_j_emlrt_marshallIn(SFc2_UAV_FleetInstanceStruct *chartInstance,
const mxArray *c2_u, const emlrtMsgIdentifier *c2_parentId)
{
uint8_T c2_y;
uint8_T c2_u0;
sf_mex_import(c2_parentId, sf_mex_dup(c2_u), &c2_u0, 1, 3, 0U, 0, 0U, 0);
c2_y = c2_u0;
sf_mex_destroy(&c2_u);
return c2_y;
}
static void init_dsm_address_info(SFc2_UAV_FleetInstanceStruct *chartInstance)
{
}
/* SFunction Glue Code */
#ifdef utFree
#undef utFree
#endif
#ifdef utMalloc
#undef utMalloc
#endif
#ifdef __cplusplus
extern "C" void *utMalloc(size_t size);
extern "C" void utFree(void*);
#else
extern void *utMalloc(size_t size);
extern void utFree(void*);
#endif
void sf_c2_UAV_Fleet_get_check_sum(mxArray *plhs[])
{
((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2742754605U);
((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2932174349U);
((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2413505563U);
((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(422321554U);
}
mxArray *sf_c2_UAV_Fleet_get_autoinheritance_info(void)
{
const char *autoinheritanceFields[] = { "checksum", "inputs", "parameters",
"outputs", "locals" };
mxArray *mxAutoinheritanceInfo = mxCreateStructMatrix(1,1,5,
autoinheritanceFields);
{
mxArray *mxChecksum = mxCreateString("lRt1fjA1xEerF9ae13RQeH");
mxSetField(mxAutoinheritanceInfo,0,"checksum",mxChecksum);
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,4,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(5));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,1,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(5));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,1,"type",mxType);
}
mxSetField(mxData,1,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(30);
pr[1] = (double)(1);
mxSetField(mxData,2,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,2,"type",mxType);
}
mxSetField(mxData,2,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,3,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,3,"type",mxType);
}
mxSetField(mxData,3,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"inputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"parameters",mxCreateDoubleMatrix(0,0,
mxREAL));
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,2,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,3,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(3);
pr[1] = (double)(100);
pr[2] = (double)(2);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(2);
pr[1] = (double)(1);
mxSetField(mxData,1,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,1,"type",mxType);
}
mxSetField(mxData,1,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"outputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"locals",mxCreateDoubleMatrix(0,0,mxREAL));
}
return(mxAutoinheritanceInfo);
}
mxArray *sf_c2_UAV_Fleet_third_party_uses_info(void)
{
mxArray * mxcell3p = mxCreateCellMatrix(1,0);
return(mxcell3p);
}
mxArray *sf_c2_UAV_Fleet_updateBuildInfo_args_info(void)
{
mxArray *mxBIArgs = mxCreateCellMatrix(1,0);
return mxBIArgs;
}
static const mxArray *sf_get_sim_state_info_c2_UAV_Fleet(void)
{
const char *infoFields[] = { "chartChecksum", "varInfo" };
mxArray *mxInfo = mxCreateStructMatrix(1, 1, 2, infoFields);
const char *infoEncStr[] = {
"100 S1x4'type','srcId','name','auxInfo'{{M[1],M[5],T\"dataFleet\",},{M[1],M[9],T\"fcnFleet\",},{M[4],M[0],T\"waypointsFleet\",S'l','i','p'{{M1x2[189 203],M[0],}}},{M[8],M[0],T\"is_active_c2_UAV_Fleet\",}}"
};
mxArray *mxVarInfo = sf_mex_decode_encoded_mx_struct_array(infoEncStr, 4, 10);
mxArray *mxChecksum = mxCreateDoubleMatrix(1, 4, mxREAL);
sf_c2_UAV_Fleet_get_check_sum(&mxChecksum);
mxSetField(mxInfo, 0, infoFields[0], mxChecksum);
mxSetField(mxInfo, 0, infoFields[1], mxVarInfo);
return mxInfo;
}
static void chart_debug_initialization(SimStruct *S, unsigned int
fullDebuggerInitialization)
{
if (!sim_mode_is_rtw_gen(S)) {
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *) ((ChartInfoStruct *)
(ssGetUserData(S)))->chartInstance;
if (ssIsFirstInitCond(S) && fullDebuggerInitialization==1) {
/* do this only if simulation is starting */
{
unsigned int chartAlreadyPresent;
chartAlreadyPresent = sf_debug_initialize_chart
(sfGlobalDebugInstanceStruct,
_UAV_FleetMachineNumber_,
2,
1,
1,
6,
0,
0,
0,
0,
0,
&(chartInstance->chartNumber),
&(chartInstance->instanceNumber),
ssGetPath(S),
(void *)S);
if (chartAlreadyPresent==0) {
/* this is the first instance */
init_script_number_translation(_UAV_FleetMachineNumber_,
chartInstance->chartNumber);
sf_debug_set_chart_disable_implicit_casting
(sfGlobalDebugInstanceStruct,_UAV_FleetMachineNumber_,
chartInstance->chartNumber,1);
sf_debug_set_chart_event_thresholds(sfGlobalDebugInstanceStruct,
_UAV_FleetMachineNumber_,
chartInstance->chartNumber,
0,
0,
0);
_SFD_SET_DATA_PROPS(0,1,1,0,"uavID");
_SFD_SET_DATA_PROPS(1,1,1,0,"functionID");
_SFD_SET_DATA_PROPS(2,1,1,0,"dataUAV");
_SFD_SET_DATA_PROPS(3,2,0,1,"dataFleet");
_SFD_SET_DATA_PROPS(4,2,0,1,"fcnFleet");
_SFD_SET_DATA_PROPS(5,1,1,0,"status");
_SFD_STATE_INFO(0,0,2);
_SFD_CH_SUBSTATE_COUNT(0);
_SFD_CH_SUBSTATE_DECOMP(0);
}
_SFD_CV_INIT_CHART(0,0,0,0);
{
_SFD_CV_INIT_STATE(0,0,0,0,0,0,NULL,NULL);
}
_SFD_CV_INIT_TRANS(0,0,NULL,NULL,0,NULL);
/* Initialization of MATLAB Function Model Coverage */
_SFD_CV_INIT_EML(0,1,1,3,0,0,1,0,0,0,0);
_SFD_CV_INIT_EML_FCN(0,0,"eML_blk_kernel",0,-1,701);
_SFD_CV_INIT_EML_IF(0,1,0,207,233,-1,279);
_SFD_CV_INIT_EML_IF(0,1,1,365,381,-1,603);
_SFD_CV_INIT_EML_IF(0,1,2,471,484,-1,591);
{
static int caseStart[] = { 626, 303 };
static int caseExprEnd[] = { 635, 309 };
_SFD_CV_INIT_EML_SWITCH(0,1,0,281,299,662,2,&(caseStart[0]),
&(caseExprEnd[0]));
}
_SFD_SET_DATA_COMPILED_PROPS(0,SF_UINT16,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c2_f_sf_marshallOut,(MexInFcnForType)NULL);
_SFD_SET_DATA_COMPILED_PROPS(1,SF_UINT16,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c2_f_sf_marshallOut,(MexInFcnForType)NULL);
{
unsigned int dimVector[1];
dimVector[0]= 30;
_SFD_SET_DATA_COMPILED_PROPS(2,SF_DOUBLE,1,&(dimVector[0]),0,0,0,0.0,
1.0,0,0,(MexFcnForType)c2_e_sf_marshallOut,(MexInFcnForType)NULL);
}
{
unsigned int dimVector[3];
dimVector[0]= 3;
dimVector[1]= 100;
dimVector[2]= 2;
_SFD_SET_DATA_COMPILED_PROPS(3,SF_DOUBLE,3,&(dimVector[0]),0,0,0,0.0,
1.0,0,0,(MexFcnForType)c2_c_sf_marshallOut,(MexInFcnForType)
c2_c_sf_marshallIn);
}
{
unsigned int dimVector[1];
dimVector[0]= 2;
_SFD_SET_DATA_COMPILED_PROPS(4,SF_DOUBLE,1,&(dimVector[0]),0,0,0,0.0,
1.0,0,0,(MexFcnForType)c2_b_sf_marshallOut,(MexInFcnForType)
c2_b_sf_marshallIn);
}
_SFD_SET_DATA_COMPILED_PROPS(5,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c2_d_sf_marshallOut,(MexInFcnForType)NULL);
{
uint16_T *c2_uavID;
uint16_T *c2_functionID;
real_T *c2_status;
real_T (*c2_dataUAV)[30];
real_T (*c2_dataFleet)[600];
real_T (*c2_fcnFleet)[2];
c2_status = (real_T *)ssGetInputPortSignal(chartInstance->S, 3);
c2_fcnFleet = (real_T (*)[2])ssGetOutputPortSignal(chartInstance->S, 2);
c2_dataFleet = (real_T (*)[600])ssGetOutputPortSignal(chartInstance->S,
1);
c2_dataUAV = (real_T (*)[30])ssGetInputPortSignal(chartInstance->S, 2);
c2_functionID = (uint16_T *)ssGetInputPortSignal(chartInstance->S, 1);
c2_uavID = (uint16_T *)ssGetInputPortSignal(chartInstance->S, 0);
_SFD_SET_DATA_VALUE_PTR(0U, c2_uavID);
_SFD_SET_DATA_VALUE_PTR(1U, c2_functionID);
_SFD_SET_DATA_VALUE_PTR(2U, *c2_dataUAV);
_SFD_SET_DATA_VALUE_PTR(3U, *c2_dataFleet);
_SFD_SET_DATA_VALUE_PTR(4U, *c2_fcnFleet);
_SFD_SET_DATA_VALUE_PTR(5U, c2_status);
}
}
} else {
sf_debug_reset_current_state_configuration(sfGlobalDebugInstanceStruct,
_UAV_FleetMachineNumber_,chartInstance->chartNumber,
chartInstance->instanceNumber);
}
}
}
static const char* sf_get_instance_specialization(void)
{
return "iDNrCgaHfRvaXoFBbZkWX";
}
static void sf_opaque_initialize_c2_UAV_Fleet(void *chartInstanceVar)
{
chart_debug_initialization(((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar
)->S,0);
initialize_params_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*)
chartInstanceVar);
initialize_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
}
static void sf_opaque_enable_c2_UAV_Fleet(void *chartInstanceVar)
{
enable_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
}
static void sf_opaque_disable_c2_UAV_Fleet(void *chartInstanceVar)
{
disable_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
}
static void sf_opaque_gateway_c2_UAV_Fleet(void *chartInstanceVar)
{
sf_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
}
extern const mxArray* sf_internal_get_sim_state_c2_UAV_Fleet(SimStruct* S)
{
ChartInfoStruct *chartInfo = (ChartInfoStruct*) ssGetUserData(S);
mxArray *plhs[1] = { NULL };
mxArray *prhs[4];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_raw2high");
prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
prhs[2] = (mxArray*) get_sim_state_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*)
chartInfo->chartInstance); /* raw sim ctx */
prhs[3] = (mxArray*) sf_get_sim_state_info_c2_UAV_Fleet();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_raw2high'.\n");
}
return plhs[0];
}
extern void sf_internal_set_sim_state_c2_UAV_Fleet(SimStruct* S, const mxArray
*st)
{
ChartInfoStruct *chartInfo = (ChartInfoStruct*) ssGetUserData(S);
mxArray *plhs[1] = { NULL };
mxArray *prhs[4];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_high2raw");
prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
prhs[2] = mxDuplicateArray(st); /* high level simctx */
prhs[3] = (mxArray*) sf_get_sim_state_info_c2_UAV_Fleet();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_high2raw'.\n");
}
set_sim_state_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*)
chartInfo->chartInstance, mxDuplicateArray(plhs[0]));
mxDestroyArray(plhs[0]);
}
static const mxArray* sf_opaque_get_sim_state_c2_UAV_Fleet(SimStruct* S)
{
return sf_internal_get_sim_state_c2_UAV_Fleet(S);
}
static void sf_opaque_set_sim_state_c2_UAV_Fleet(SimStruct* S, const mxArray *st)
{
sf_internal_set_sim_state_c2_UAV_Fleet(S, st);
}
static void sf_opaque_terminate_c2_UAV_Fleet(void *chartInstanceVar)
{
if (chartInstanceVar!=NULL) {
SimStruct *S = ((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar)->S;
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
sf_clear_rtw_identifier(S);
unload_UAV_Fleet_optimization_info();
}
finalize_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
utFree((void *)chartInstanceVar);
ssSetUserData(S,NULL);
}
}
static void sf_opaque_init_subchart_simstructs(void *chartInstanceVar)
{
initSimStructsc2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*) chartInstanceVar);
}
extern unsigned int sf_machine_global_initializer_called(void);
static void mdlProcessParameters_c2_UAV_Fleet(SimStruct *S)
{
int i;
for (i=0;i<ssGetNumRunTimeParams(S);i++) {
if (ssGetSFcnParamTunable(S,i)) {
ssUpdateDlgParamAsRunTimeParam(S,i);
}
}
if (sf_machine_global_initializer_called()) {
initialize_params_c2_UAV_Fleet((SFc2_UAV_FleetInstanceStruct*)
(((ChartInfoStruct *)ssGetUserData(S))->chartInstance));
}
}
static void mdlSetWorkWidths_c2_UAV_Fleet(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
mxArray *infoStruct = load_UAV_Fleet_optimization_info();
int_T chartIsInlinable =
(int_T)sf_is_chart_inlinable(S,sf_get_instance_specialization(),infoStruct,
2);
ssSetStateflowIsInlinable(S,chartIsInlinable);
ssSetRTWCG(S,sf_rtw_info_uint_prop(S,sf_get_instance_specialization(),
infoStruct,2,"RTWCG"));
ssSetEnableFcnIsTrivial(S,1);
ssSetDisableFcnIsTrivial(S,1);
ssSetNotMultipleInlinable(S,sf_rtw_info_uint_prop(S,
sf_get_instance_specialization(),infoStruct,2,
"gatewayCannotBeInlinedMultipleTimes"));
sf_update_buildInfo(S,sf_get_instance_specialization(),infoStruct,2);
if (chartIsInlinable) {
ssSetInputPortOptimOpts(S, 0, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 1, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 2, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 3, SS_REUSABLE_AND_LOCAL);
sf_mark_chart_expressionable_inputs(S,sf_get_instance_specialization(),
infoStruct,2,4);
sf_mark_chart_reusable_outputs(S,sf_get_instance_specialization(),
infoStruct,2,2);
}
{
unsigned int outPortIdx;
for (outPortIdx=1; outPortIdx<=2; ++outPortIdx) {
ssSetOutputPortOptimizeInIR(S, outPortIdx, 1U);
}
}
{
unsigned int inPortIdx;
for (inPortIdx=0; inPortIdx < 4; ++inPortIdx) {
ssSetInputPortOptimizeInIR(S, inPortIdx, 1U);
}
}
sf_set_rtw_dwork_info(S,sf_get_instance_specialization(),infoStruct,2);
ssSetHasSubFunctions(S,!(chartIsInlinable));
} else {
}
ssSetOptions(S,ssGetOptions(S)|SS_OPTION_WORKS_WITH_CODE_REUSE);
ssSetChecksum0(S,(1401663050U));
ssSetChecksum1(S,(110814892U));
ssSetChecksum2(S,(4202039452U));
ssSetChecksum3(S,(2466848576U));
ssSetmdlDerivatives(S, NULL);
ssSetExplicitFCSSCtrl(S,1);
ssSupportsMultipleExecInstances(S,1);
}
static void mdlRTW_c2_UAV_Fleet(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S)) {
ssWriteRTWStrParam(S, "StateflowChartType", "Embedded MATLAB");
}
}
static void mdlStart_c2_UAV_Fleet(SimStruct *S)
{
SFc2_UAV_FleetInstanceStruct *chartInstance;
chartInstance = (SFc2_UAV_FleetInstanceStruct *)utMalloc(sizeof
(SFc2_UAV_FleetInstanceStruct));
memset(chartInstance, 0, sizeof(SFc2_UAV_FleetInstanceStruct));
if (chartInstance==NULL) {
sf_mex_error_message("Could not allocate memory for chart instance.");
}
chartInstance->chartInfo.chartInstance = chartInstance;
chartInstance->chartInfo.isEMLChart = 1;
chartInstance->chartInfo.chartInitialized = 0;
chartInstance->chartInfo.sFunctionGateway = sf_opaque_gateway_c2_UAV_Fleet;
chartInstance->chartInfo.initializeChart = sf_opaque_initialize_c2_UAV_Fleet;
chartInstance->chartInfo.terminateChart = sf_opaque_terminate_c2_UAV_Fleet;
chartInstance->chartInfo.enableChart = sf_opaque_enable_c2_UAV_Fleet;
chartInstance->chartInfo.disableChart = sf_opaque_disable_c2_UAV_Fleet;
chartInstance->chartInfo.getSimState = sf_opaque_get_sim_state_c2_UAV_Fleet;
chartInstance->chartInfo.setSimState = sf_opaque_set_sim_state_c2_UAV_Fleet;
chartInstance->chartInfo.getSimStateInfo = sf_get_sim_state_info_c2_UAV_Fleet;
chartInstance->chartInfo.zeroCrossings = NULL;
chartInstance->chartInfo.outputs = NULL;
chartInstance->chartInfo.derivatives = NULL;
chartInstance->chartInfo.mdlRTW = mdlRTW_c2_UAV_Fleet;
chartInstance->chartInfo.mdlStart = mdlStart_c2_UAV_Fleet;
chartInstance->chartInfo.mdlSetWorkWidths = mdlSetWorkWidths_c2_UAV_Fleet;
chartInstance->chartInfo.extModeExec = NULL;
chartInstance->chartInfo.restoreLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.restoreBeforeLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.storeCurrentConfiguration = NULL;
chartInstance->S = S;
ssSetUserData(S,(void *)(&(chartInstance->chartInfo)));/* register the chart instance with simstruct */
init_dsm_address_info(chartInstance);
if (!sim_mode_is_rtw_gen(S)) {
}
sf_opaque_init_subchart_simstructs(chartInstance->chartInfo.chartInstance);
chart_debug_initialization(S,1);
}
void c2_UAV_Fleet_method_dispatcher(SimStruct *S, int_T method, void *data)
{
switch (method) {
case SS_CALL_MDL_START:
mdlStart_c2_UAV_Fleet(S);
break;
case SS_CALL_MDL_SET_WORK_WIDTHS:
mdlSetWorkWidths_c2_UAV_Fleet(S);
break;
case SS_CALL_MDL_PROCESS_PARAMETERS:
mdlProcessParameters_c2_UAV_Fleet(S);
break;
default:
/* Unhandled method */
sf_mex_error_message("Stateflow Internal Error:\n"
"Error calling c2_UAV_Fleet_method_dispatcher.\n"
"Can't handle method %d.\n", method);
break;
}
}
|
// pages/data_hi/data_hi.js
//小程序只有一个实例 App
//const前端定义变量的方式,所谓常量已经过定义不能变化的量
const app=getApp();
console.log(app);
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log(options);
console.log(app.content)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
tapName: function (event) {
console.log(event);
app.content = event.target.dataes.hi
// wx.navigateTo({
// url: `../../PHP/PHP?name+${event.target.dataes.hi}`,
// success:function(){
// console.log('123234456')
// }
// })
}
})
|
import React, { Component } from "react";
import { PropTypes } from "prop-types";
import cn from "classnames";
import Moment from "moment/moment";
import { getFullName } from "../actions/utils";
import { DATE_TIME_FORMAT } from "@constants";
import { humanFileSize } from "../../common/utils/listing";
class ChatMessage extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { message, ownMessage, ownCompanyMessage } = this.props;
return (
<div className={cn("message", {
"own-message": ownMessage,
"own-company": ownCompanyMessage,
})}
>
<div className="message-sender">
{getFullName(message.sender)}
</div>
<div className="message-date">
{Moment(message.createdAt).format(`${DATE_TIME_FORMAT}`)}
</div>
{message.attachment
&& (
<a
className="attachment-uploader attachment-uploader-file"
href={hosturl + message.filePath}
download={message.fileName}
>
<div className="attachment-uploader-extension">{message.fileExtension}</div>
<div className="attachment-uploader-name">{message.fileName}</div>
<div className="attachment-uploader-name"> .</div>
<div className="attachment-uploader-size">{humanFileSize(message.fileSize, false)}</div>
</a>
)}
{message.content && (
<div className="message-content">
{message.content}
</div>
)}
</div>
);
}
}
ChatMessage.contextTypes = {
t: PropTypes.func.isRequired,
};
export default ChatMessage;
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import Tweet from './tweet'
class Dashboard extends Component{
render() {
return (
<div>
<h3 className="center">Your Timeline</h3>
<ul className="dashboard-list">
{this.props.tweetIds.map(
(id) => (
<li key={id}>
<div>
<Tweet id={id} />
</div>
</li>
))}
</ul>
</div>
)
}
}
function mapStateToProps({ tweets }){
return {
tweetIds: Object.keys(tweets)
.sort((a,b) => tweets[b].timestamp - tweets[a].timestamp)
}
}
export default connect(mapStateToProps)(Dashboard)
|
/* eslint-disable unicorn/prevent-abbreviations */
'use-strict';
const packageFile = require('../package.json');
const logger = require('../services/logger/logger.service');
const app = require('./app');
const http = require('http');
const https = require('https');
const SocketIO = require('./socket');
const httpService = require('../services/http/http.service');
const mqttService = require('../services/mqtt/mqtt.service');
const Config = require('../services/config/config.start');
const Sessions = require('../services/sessions/sessions.service');
const Streams = require('./services/streams.service');
const ClearTimer = require('./services/cleartimer.service');
const lowdb = require('./services/lowdb.service');
const config = new Config();
const server = config.ssl
? https.createServer(
{
key: config.ssl.key,
cert: config.ssl.cert,
},
app
)
: http.createServer(app);
const io = new SocketIO(server);
server.on('listening', async () => {
let addr = server.address();
let bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
logger.info(
`camera.ui v${packageFile.version} is listening on ${bind} (${config.ssl ? 'https' : 'http'})`,
false,
true
);
ClearTimer.start();
Sessions.init(config.cameras);
Streams.init(io);
if (config.mqtt) {
mqttService.start(config);
}
if (config.http) {
httpService.start(config);
}
});
server.on('error', (error) => {
let error_;
if (error.syscall !== 'listen') {
logger.error(error, false, true);
}
let bind = typeof port === 'string' ? 'Pipe ' + config.port : 'Port ' + config.port;
switch (error.code) {
case 'EACCES':
error_ = `Can not start the User Interface! ${bind} requires elevated privileges`;
break;
case 'EADDRINUSE':
error_ = `Can not start the User Interface! ${bind} is already in use`;
break;
default:
error_ = error;
}
logger.error(error_, false, true);
server.stopServer();
});
server.on('close', () => {
logger.debug('Stopping user interface server...', false, true);
});
server.startServer = async () => {
try {
//prepare db
await lowdb.ensureDatabase();
await lowdb.prepareDatabase();
await lowdb.refreshRecordingsDatabase();
lowdb.initTokensDatabase();
//start server
server.listen(config.port);
} catch (error) {
logger.error('An error occured during starting server!', false, true);
logger.error(error);
server.stopServer();
}
return server;
};
server.stopServer = async () => {
ClearTimer.stop();
Streams.stopStreams();
if (config.http) {
httpService.stop();
}
server.close();
};
if (process.env.NODE_ENV === 'test') {
server.startServer();
}
process.on('SIGHUP', () => {
server.stopServer();
});
module.exports = {
io,
server,
};
|
""" module to manage users"""
from flask_bcrypt import Bcrypt
import datetime
import jwt
from apps import db, app
class Users(db.Model):
"""model to store user details """
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
email = db.Column(db.String, nullable=False)
username = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
def __init__(self, name, email, username, password):
self.name = name
self.email = email
self.username = username
self.password = Bcrypt().generate_password_hash(password).decode()
def verifypassword(self, password):
"""method to verify user password"""
return Bcrypt().check_password_hash(self.password, password)
@staticmethod
def password_hash(password):
"""method to hash provided password"""
password = Bcrypt().generate_password_hash(password).decode()
return password
def save(self):
"""method to store new user"""
db.session.add(self)
db.session.commit()
@staticmethod
def getuser(current_user):
"""method to retrieve users"""
userlist = Users.query.filter_by(id=current_user.id).first()
results = {}
if userlist:
results["id"] = userlist.id
results["name"] = userlist.name
results["email"] = userlist.email
results["username"] = userlist.username
return results
def delete(self):
"""method to delete a user"""
db.session.delete(self)
db.session.commit()
class BlacklistTokens(db.Model):
"""model to store blacklisted tokens """
__tablename__ = 'blacklist'
id = db.Column(db.Integer, primary_key=True)
token = db.Column(db.String, nullable=False)
date_blacklisted = db.Column(db.DateTime, nullable=False)
def __init__(self, token):
self.token = token
self.date_blacklisted = datetime.datetime.utcnow()
def save(self):
"""method to store new user"""
db.session.add(self)
db.session.commit()
@staticmethod
def verify_blacklist(token):
"""method to verify if token is blacklisted """
blacklisted = BlacklistTokens.query.filter_by(token=token).first()
if blacklisted:
return True
else:
return False
@staticmethod
def generate_token(user_id):
"""method to generate token"""
token = jwt.encode(
{'id':user_id, 'exp':datetime.datetime.utcnow()+ datetime.timedelta(hours=720)},
app.config['SECRET'])#expires after 30 days
return token
def __repr__(self):
return '<id: token: {}'.format(self.token)
|
class ClientQuery {
constructor(clientId) {
this.clientId = clientId;
}
}
module.exports = ClientQuery;
|
import datetime as dt
import os
from datetime import timedelta
from pathlib import Path
import holidays
import pandas as pd
from sqlalchemy import create_engine
DB_HOST = 'localhost'
DB_PORT = 5432
DB = 'group_16'
def main():
user = input('Enter pgadmin username: ')
password = input('Enter pgadmin password: ')
engine = create_engine('postgresql+psycopg2://{}:{}@{}:{}/{}'.format(user, password, DB_HOST, DB_PORT, DB))
print('----------HOUR----------')
hour_df = create_hour_df()
insert_hour(engine, hour_df)
print('--------END HOUR--------')
print('---------WEATHER--------')
weather_df = create_weather_df()
insert_weather(engine, weather_df)
print('-------END WEATHER------')
print('--------COLLISION-------')
collision_df = create_collision_df()
print('--------LOCATION--------')
insert_location(engine, collision_df)
print('------END LOCATION------')
print('--------ACCIDENT--------')
insert_accident(engine, collision_df)
print('------END ACCIDENT------')
print('------END COLLISION-----')
print('----------FACT----------')
insert_fact(engine)
print('--------END FACT--------')
def create_weather_df():
weather_csv = Path('weather_final.csv')
if weather_csv.is_file():
weather_df = pd.read_csv('weather_final.csv', dtype={'weather': str})
else:
# Filter relevant stations from the file (ON, hourly data still active 2014+)
iter_stations = pd.read_csv('Station Inventory EN.csv', header=3, chunksize=1000)
station_df = pd.concat([chunk[(chunk['Province'] == 'ONTARIO') & (chunk['HLY Last Year'] >= 2014)] for chunk in iter_stations], ignore_index=True)
station_df = station_df.sort_values(by='Station ID').drop_duplicates('Name', keep='last')
station_df = station_df[['Name', 'Latitude (Decimal Degrees)', 'Longitude (Decimal Degrees)']] # Select columns
station_df.columns = ['station_name', 'latitude', 'longitude'] # Rename columns
station_names = station_df['station_name'].tolist()
# Create one dataframe from all files
weather_df = pd.DataFrame()
files = ['ontario_1_1.csv', 'ontario_1_2.csv', 'ontario_2_1.csv', 'Ontario_2_2.csv', 'Ontario_3.csv', 'Ontario_4.csv']
for f in files:
print('Processing file: ' + f)
# Get filtered dataframe for file
reader = pd.read_csv(f, chunksize=1000)
df = pd.concat([chunk[(chunk['Year'] >= 2014) & (chunk['X.U.FEFF..Station.Name.'].isin(station_names))] for chunk in reader])
# Drop rows that have no weather data
df.dropna(subset=df.columns[range(5, len(df.columns)-2)], how='all', inplace=True)
# Combine final df with file df
weather_df = pd.concat([weather_df, df], ignore_index=True)
# Clean and finalize dataframe
weather_df.drop(columns=list(weather_df.filter(regex='.Flag$')) + ['Year', 'Month', 'Day', 'Time', 'X.Province.'], inplace=True)
weather_df.columns = [
'date_time',
'temp_c',
'dew_point_temp_c',
'rel_hum',
'wind_dir_deg',
'wind_spd_kmh',
'visibility_km',
'stn_press_kpa',
'hmdx',
'wind_chill',
'weather',
'station_name'
]
weather_df = weather_df.merge(station_df, how='left')
weather_df.sort_values(['station_name', 'date_time'], inplace=True)
weather_df.to_csv('weather_final.csv', index=False)
print('Weather Processed (Rows, Cols) : ', weather_df.shape)
return weather_df
def insert_weather(engine, weather_df):
connection = engine.connect()
connection.execute('DROP TABLE IF EXISTS weather CASCADE')
connection.execute('''CREATE TABLE weather(
weather_key serial PRIMARY KEY,
station_name text,
longitude float8,
latitude float8,
temp_c float4,
dew_point_temp_c float4,
rel_hum int,
wind_dir_deg int,
wind_spd_kmh int,
visibility_km float4,
stn_press_kpa float4,
hmdx int,
wind_chill int,
weather text,
date_time timestamp,
hour_id int)''')
connection.close()
weather_df.to_sql('weather', con=engine, if_exists='append', index=False)
print('Weather table added to DB')
connection = engine.connect()
connection.execute('''UPDATE weather w
SET hour_id = h.hour_key
FROM hours h
WHERE w.date_time::date = h.currentdate
AND w.date_time::time = h.hour_start''')
connection.close()
print('Column hour_id updated in weather table')
def create_hour_df():
hour_df = pd.DataFrame()
hour_df['currentdate'] = pd.date_range(start='1/1/2014', end='01/01/2018', freq='H', closed='left')
hour_df['day_of_week'] = hour_df['currentdate'].dt.day_name()
hour_df['month_of_year'] = hour_df['currentdate'].dt.month_name()
hour_df['is_weekend'] = ((pd.DatetimeIndex(hour_df['currentdate']).dayofweek) // 5 == 1)
#HOLIDAY FLAG
# creating a blank series
Type_new_hol_flags = pd.Series([])
Type_new_hol_name = pd.Series([])
#Canadian holidays.
ca_hols = holidays.CA(years =(2014, 2015, 2016, 2017))
# running a for loop and assigning some values to series
for index, row in hour_df.iterrows():
hol_flag = getattr(row, "currentdate") in ca_hols
if hol_flag:
Type_new_hol_flags[index] = hol_flag
Type_new_hol_name[index] = ca_hols.get(getattr(row, "currentdate"))
else:
Type_new_hol_flags[index] = hol_flag
Type_new_hol_name[index] = None
hour_df['current_year'] = pd.to_datetime(hour_df['currentdate']).apply(lambda x: x.strftime('%Y'))
# inserting new column with values of holiday flag list made above
hour_df.insert(5, "is_holiday", Type_new_hol_flags)
# inserting new column with values of holiday name list made above
hour_df.insert(6, "holiday_name", Type_new_hol_name)
#hour start
hour_df['hour_start'] = hour_df['currentdate'].apply(lambda x: x.strftime('%H:%M:%S'))
#hour end = hour start + 1hr
hour_df['hour_end'] = hour_df['currentdate'] + timedelta(hours=1)
hour_df['hour_end'] = pd.to_datetime(hour_df['hour_end']).apply(lambda x: x.strftime('%H:%M:%S'))
#clean date
hour_df['currentdate'] = pd.to_datetime(hour_df['currentdate']).apply(lambda x: x.strftime('%Y-%m-%d'))
hour_df.to_csv("hour_final.csv", index=False)
print('Hour Table Processed (Rows, Cols) : ', hour_df.shape)
return hour_df
def insert_hour(engine, hour_df):
connection = engine.connect()
connection.execute('DROP TABLE IF EXISTS hours CASCADE')
connection.execute('''CREATE TABLE hours(
hour_key serial PRIMARY KEY,
hour_start time,
hour_end time,
currentdate date,
day_of_week text,
month_of_year text,
current_year int,
is_weekend bool,
is_holiday bool,
holiday_name text)''')
connection.close()
hour_df.to_sql("hours", engine, index=False, if_exists='append') #replace or append or fail
print('Hours table added to DB')
def create_collision_df():
collision_df = pd.read_csv(os.path.abspath("h2017collisionsfinal.csv"), header = 0, encoding = 'ISO-8859-1')
ac_16_df = pd.read_csv(os.path.abspath("2016collisionsfinal.csv"), header = 0, encoding = 'ISO-8859-1')
collision_df = collision_df.append(ac_16_df, sort=False)
ac_15_df = pd.read_csv(os.path.abspath("2015collisionsfinal.csv"), header = 0, encoding = 'ISO-8859-1')
collision_df = collision_df.append(ac_15_df, sort=False)
ac_14_df = pd.read_csv(os.path.abspath("2014collisionsfinal.csv"), header = 0, encoding = 'ISO-8859-1')
collision_df = collision_df.append(ac_14_df, sort=False)
# Create csv
collision_df.to_csv("full_collision_final.csv", index=False)
return collision_df
#accident flat file construction
def insert_accident(engine, collision_df):
accident_columns = ['accident_time', 'environment', 'road_surface', 'traffic_control', 'impact_type', 'visibility', 'accident_date',
'street_name', 'intersection_1', 'intersection_2', 'longitude', 'latitude', 'neighborhood', 'is_fatal']
accident_df = collision_df[['Time', 'Environment', 'Road_Surface', 'Traffic_Control', 'Impact_type', 'Light', 'Date',
'Location', 'Location', 'Location', 'lon', 'lat', 'Neighborhood', 'Collision_Classification']]
accident_df.columns = accident_columns
# Round to nearest hour
accident_df.loc[:, 'adjusted_time'] = pd.to_datetime(accident_df['accident_time']).apply(lambda x: x.round("H"))
accident_df.loc[:, 'adjusted_time'] = pd.to_datetime(accident_df['adjusted_time']).apply(lambda x: x.strftime('%H:%M:%S'))
# Get location data for comparison
accident_df.loc[:, 'street_name'] = accident_df['street_name'].apply(get_street_name)
accident_df.loc[:, 'intersection_1'] = accident_df['intersection_1'].apply(get_intersection_1)
accident_df.loc[:, 'intersection_2'] = accident_df['intersection_2'].apply(get_intersection_2)
# Get is_fatal values
accident_df.loc[:, 'is_fatal'] = accident_df['is_fatal'].apply(lambda x: True if '01' in x else False)
accident_df.to_csv('accident_final.csv', index=False)
print('Accident Processed (Rows, Cols) : ', accident_df.shape)
connection = engine.connect()
connection.execute('DROP TABLE IF EXISTS accidents CASCADE')
connection.execute('''CREATE TABLE accidents(
accident_key serial PRIMARY KEY,
accident_time time,
environment text,
road_surface text,
traffic_control text,
visibility text,
impact_type text,
accident_date date,
adjusted_time time,
hour_id int,
street_name text,
intersection_1 text,
intersection_2 text,
longitude float8,
latitude float8,
neighborhood text,
location_id int,
is_fatal bool)''')
connection.close()
accident_df.to_sql("accidents", engine, index=False, if_exists='append') #replace or append or fail
print('Accidents table added to DB')
connection = engine.connect()
connection.execute('''UPDATE accidents acc
SET hour_id = h.hour_key
FROM hours h
WHERE acc.accident_date = h.currentdate
AND acc.adjusted_time = h.hour_start''')
print('Column hour_id updated in accidents table')
connection.execute('''UPDATE accidents acc
SET location_id = l.locale_key
FROM locales l
WHERE acc.street_name = l.street_name
AND acc.intersection_1 IS NOT DISTINCT FROM l.intersection_1
AND acc.intersection_2 IS NOT DISTINCT FROM l.intersection_2
AND acc.longitude = l.longitude
AND acc.latitude = l.latitude
AND acc.neighborhood IS NOT DISTINCT FROM l.neighborhood''')
print('Column location_id updated in accidents table')
connection.close()
def insert_location(engine, collision_df):
# Get relevant columns
location_columns = ['street_name', 'intersection_1', 'intersection_2', 'longitude', 'latitude', 'neighborhood']
location_df = collision_df[['Location', 'Location', 'Location', 'lon', 'lat', 'Neighborhood' ]]
location_df.columns = location_columns
# Separate location into street_name, intersection_1, intersection_2
location_df.loc[:, 'street_name'] = location_df['street_name'].apply(get_street_name)
location_df.loc[:, 'intersection_1'] = location_df['intersection_1'].apply(get_intersection_1)
location_df.loc[:, 'intersection_2'] = location_df['intersection_2'].apply(get_intersection_2)
# Remove duplicates
location_df.drop_duplicates(inplace=True)
location_df.to_csv("location_final.csv", index=False)
print('Location Processed (Rows, Cols) : ', location_df.shape)
# Drop and create locales table
connection = engine.connect()
connection.execute('DROP TABLE IF EXISTS locales CASCADE')
connection.execute('''CREATE TABLE locales(
locale_key serial PRIMARY KEY,
street_name text,
intersection_1 text,
intersection_2 text,
longitude float8,
latitude float8,
neighborhood text)''')
connection.close()
location_df.to_sql("locales", engine, index=False, if_exists='append')
print('Location Table added to DB')
def get_street_name(location):
if '@' in location:
return location.split('@', 1)[1].strip()
elif 'btwn' in location:
return location.split('btwn', 1)[0].strip()
else:
return location.split('/')[0].strip()
def get_intersection_1(location):
if '@' in location:
return location.split('@', 1)[0].split('/', 1)[0].strip()
elif 'btwn' in location:
return location.split('btwn', 1)[1].split('&', 1)[0].strip()
elif '/' in location:
return location.split('/')[1].strip()
else:
return None
def get_intersection_2(location):
if '@' in location:
intersections = location.split('@', 1)[0].split('/', 1)
elif 'btwn' in location:
intersections = location.split('btwn', 1)[1].split('&', 1)
elif '/' in location:
intersections = location.split('/')[1:]
else:
intersections = []
if len(intersections) >= 2:
return intersections[1].strip()
else:
return None
def insert_fact(engine):
connection = engine.connect()
connection.execute('''CREATE TEMP TABLE distance AS
SELECT s.accident_key, s.location_id, s.station_name, d.distance
FROM (
SELECT acc.accident_key, acc.location_id, w.station_name
FROM accidents acc, weather w
WHERE acc.hour_id = w.hour_id
) AS s
JOIN (
SELECT l.locale_key, w.station_name, (acos(sin(radians(l.latitude)) * sin(radians(w.latitude)) + cos(radians(l.latitude)) * cos(radians(w.latitude)) * cos(radians(w.longitude - l.longitude))) * 6371) AS distance
FROM (
SELECT DISTINCT ON (station_name) station_name, latitude, longitude
FROM weather
) w, locales l
) AS d
ON s.location_id = d.locale_key AND s.station_name = d.station_name''')
print('Created temporary table for distances between accidents and stations')
connection.execute('DROP TABLE IF EXISTS facts')
connection.execute('''CREATE TABLE facts AS
SELECT h.hour_key, l.locale_key, acc.accident_key, w.weather_key, acc.is_fatal, (l.intersection_2 IS NULL) AS is_intersection
FROM hours h, accidents acc, locales l, weather w, (
SELECT d2.accident_key, d2.station_name
FROM (
SELECT d.accident_key, min(d.distance) AS min_distance
FROM distance d
GROUP BY d.accident_key
) md
JOIN distance d2 ON d2.accident_key = md.accident_key AND d2.distance = md.min_distance) near
WHERE acc.hour_id = h.hour_key
AND acc.location_id = l.locale_key
AND h.hour_key = w.hour_id
AND w.station_name = near.station_name
AND near.accident_key = acc.accident_key''')
connection.execute('''ALTER TABLE facts
ADD CONSTRAINT hours_fkey FOREIGN KEY (hour_key) REFERENCES hours(hour_key),
ADD CONSTRAINT locales_fkey FOREIGN KEY (locale_key) REFERENCES locales(locale_key),
ADD CONSTRAINT accidents_fkey FOREIGN KEY (accident_key) REFERENCES accidents(accident_key),
ADD CONSTRAINT weather_fkey FOREIGN KEY (weather_key) REFERENCES weather(weather_key)''')
print('Fact Table added to DB')
connection.execute('ALTER TABLE weather DROP COLUMN date_time, DROP COLUMN hour_id')
connection.execute('DELETE FROM weather WHERE weather_key NOT IN (SELECT weather_key FROM facts)')
connection.execute('''ALTER TABLE accidents DROP COLUMN accident_date, DROP COLUMN adjusted_time, DROP COLUMN hour_id,
DROP COLUMN street_name, DROP COLUMN intersection_1, DROP COLUMN intersection_2, DROP COLUMN longitude,
DROP COLUMN latitude, DROP COLUMN neighborhood, DROP COLUMN location_id, DROP COLUMN is_fatal''')
print('Removed unneeded rows and columns')
connection.close()
if __name__ == "__main__":
main()
|