Loading a dashboard featuring misc charts
488294
def load_misc_dashboard():
    """"""

    print('Creating the dashboard')
    db.session.expunge_all()
    dash = db.session.query(Dash).filter_by(slug=DASH_SLUG).first()

    if not dash:
        dash = Dash()
    js = textwrap.dedent("""\
{
    "CHART-BkeVbh8ANQ": {
        "children": [],
        "id": "CHART-BkeVbh8ANQ",
        "meta": {
            "chartId": 4004,
            "height": 34,
            "sliceName": "Multi Line",
            "width": 8
        },
        "type": "CHART"
    },
    "CHART-H1HYNzEANX": {
        "children": [],
        "id": "CHART-H1HYNzEANX",
        "meta": {
            "chartId": 3940,
            "height": 50,
            "sliceName": "Energy Sankey",
            "width": 6
        },
        "type": "CHART"
    },
    "CHART-HJOYVMV0E7": {
        "children": [],
        "id": "CHART-HJOYVMV0E7",
        "meta": {
            "chartId": 3969,
            "height": 63,
            "sliceName": "Mapbox Long/Lat",
            "width": 6
        },
        "type": "CHART"
    },
    "CHART-S1WYNz4AVX": {
        "children": [],
        "id": "CHART-S1WYNz4AVX",
        "meta": {
            "chartId": 3989,
            "height": 25,
            "sliceName": "Parallel Coordinates",
            "width": 4
        },
        "type": "CHART"
    },
    "CHART-r19KVMNCE7": {
        "children": [],
        "id": "CHART-r19KVMNCE7",
        "meta": {
            "chartId": 3971,
            "height": 34,
            "sliceName": "Calendar Heatmap multiformat 0",
            "width": 4
        },
        "type": "CHART"
    },
    "CHART-rJ4K4GV04Q": {
        "children": [],
        "id": "CHART-rJ4K4GV04Q",
        "meta": {
            "chartId": 3941,
            "height": 63,
            "sliceName": "Energy Force Layout",
            "width": 6
        },
        "type": "CHART"
    },
    "CHART-rkgF4G4A4X": {
        "children": [],
        "id": "CHART-rkgF4G4A4X",
        "meta": {
            "chartId": 3970,
            "height": 25,
            "sliceName": "Birth in France by department in 2016",
            "width": 8
        },
        "type": "CHART"
    },
    "CHART-rywK4GVR4X": {
        "children": [],
        "id": "CHART-rywK4GVR4X",
        "meta": {
            "chartId": 3942,
            "height": 50,
            "sliceName": "Heatmap",
            "width": 6
        },
        "type": "CHART"
    },
    "COLUMN-ByUFVf40EQ": {
        "children": [
            "CHART-rywK4GVR4X",
            "CHART-HJOYVMV0E7"
        ],
        "id": "COLUMN-ByUFVf40EQ",
        "meta": {
            "background": "BACKGROUND_TRANSPARENT",
            "width": 6
        },
        "type": "COLUMN"
    },
    "COLUMN-rkmYVGN04Q": {
        "children": [
            "CHART-rJ4K4GV04Q",
            "CHART-H1HYNzEANX"
        ],
        "id": "COLUMN-rkmYVGN04Q",
        "meta": {
            "background": "BACKGROUND_TRANSPARENT",
            "width": 6
        },
        "type": "COLUMN"
    },
    "GRID_ID": {
        "children": [
            "ROW-SytNzNA4X",
            "ROW-S1MK4M4A4X",
            "ROW-HkFFEzVRVm"
        ],
        "id": "GRID_ID",
        "type": "GRID"
    },
    "HEADER_ID": {
        "id": "HEADER_ID",
        "meta": {
            "text": "Misc Charts"
        },
        "type": "HEADER"
    },
    "ROOT_ID": {
        "children": [
            "GRID_ID"
        ],
        "id": "ROOT_ID",
        "type": "ROOT"
    },
    "ROW-HkFFEzVRVm": {
        "children": [
            "CHART-r19KVMNCE7",
            "CHART-BkeVbh8ANQ"
        ],
        "id": "ROW-HkFFEzVRVm",
        "meta": {
            "background": "BACKGROUND_TRANSPARENT"
        },
        "type": "ROW"
    },
    "ROW-S1MK4M4A4X": {
        "children": [
            "COLUMN-rkmYVGN04Q",
            "COLUMN-ByUFVf40EQ"
        ],
        "id": "ROW-S1MK4M4A4X",
        "meta": {
            "background": "BACKGROUND_TRANSPARENT"
        },
        "type": "ROW"
    },
    "ROW-SytNzNA4X": {
        "children": [
            "CHART-rkgF4G4A4X",
            "CHART-S1WYNz4AVX"
        ],
        "id": "ROW-SytNzNA4X",
        "meta": {
            "background": "BACKGROUND_TRANSPARENT"
        },
        "type": "ROW"
    },
    "DASHBOARD_VERSION_KEY": "v2"
}
    """)
    pos = json.loads(js)
    slices = (
        db.session
        .query(Slice)
        .filter(Slice.slice_name.in_(misc_dash_slices))
        .all()
    )
    slices = sorted(slices, key=lambda x: x.id)
    update_slice_ids(pos, slices)
    dash.dashboard_title = 'Misc Charts'
    dash.position_json = json.dumps(pos, indent=4)
    dash.slug = DASH_SLUG
    dash.slices = slices
    db.session.merge(dash)
    db.session.commit()
1076438
def collect_dashboard_js(collector):
    """"""
    dashmat = collector.configuration["dashmat"]

    modules = collector.configuration["__active_modules__"]
    compiled_static_prep = dashmat.compiled_static_prep
    compiled_static_folder = dashmat.compiled_static_folder

    npm_deps = list_npm_modules(collector, no_print=True)
    react_server = ReactServer()
    react_server.prepare(npm_deps, compiled_static_folder)

    for dashboard in collector.configuration["dashboards"].values():
        log.info("Generating compiled javascript for dashboard:{0}".format(dashboard.path))
        filename = dashboard.path.replace("_", "__").replace("/", "_")
        location = os.path.join(compiled_static_folder, "dashboards", "{0}.js".format(filename))
        if os.path.exists(location):
            os.remove(location)
        generate_dashboard_js(dashboard, react_server, compiled_static_folder, compiled_static_prep, modules)
92522
function() {

            var self = this;
            var insightsPanel = self.buildInsightsPanel();

            var media =
insightsPanel +
'<div class="media">' +
'  <div class="media-left">' +
// the visual chart as media-object.
'    <div class="media-object" id="' +
      self.getId('chart') + '">Charts</div>' +
'  </div>' +
'  <div class="media-body">' +
'    <div id="' + self.getId('summary') + '">Summary</div>' +
'  </div>' +
'</div>';

            $('#' + self.attrId).html(media);
        }
93171
def export_dashboards(print_stdout, dashboard_file):
    """"""
    data = dashboard_import_export.export_dashboards(db.session)
    if print_stdout or not dashboard_file:
        print(data)
    if dashboard_file:
        logging.info('Exporting dashboards to %s', dashboard_file)
        with open(dashboard_file, 'w') as data_stream:
            data_stream.write(data)
43878
def get_dashboard(context, location):
    
    if location == 'index':
        return get_index_dashboard(context)
    elif location == 'app_index':
        return get_app_index_dashboard(context)
    raise ValueError('Invalid dashboard location: "%s"' % location)
919385
public function index()
    {
        $stats     = $this->logViewer->statsTable();
        $chartData = $this->prepareChartData($stats);
        $percents  = $this->calcPercentages($stats->footer(), $stats->header());

        return $this->view('dashboard', compact('chartData', 'percents'));
    }
31357
private Chart getChartFromParams(final PageParameters params) {
        String chartString;
        String themeString;
        Chart config;

        //If the showcase is started without any parameters
        //set the parameters to lineBasic and give us a line Chart
        if(params.getAllNamed().size() < 2){
            PageParameters temp = new PageParameters();
            temp.add("theme", "default");
            temp.add("chart", "line");
            setResponsePage(HomepageHighcharts.class, temp);
            config = new Chart("chart", new BasicLineOptions(), null);
            return config;
        }

        themeString = params.getAllNamed().get(0).getValue();
        Theme theme = getThemeFromParams(themeString);
        chartString = params.getAllNamed().get(1).getValue();

        if(chartString == null) {
            config = new Chart("chart", new BasicLineOptions(), theme);
            return config;
        }

        switch(chartString) {
            case "basicBar":
                config = new Chart("chart", new BasicBarOptions(), theme);
                break;

            case "splineWithSymbols":
                config = new Chart("chart", new SplineWithSymbolsOptions(), theme);
                break;

            case "irregularIntervals":
                config = new Chart("chart", new TimeDataWithIrregularIntervalsOptions(), theme);
                break;

            case "logarithmicAxis":
                config = new Chart("chart", new LogarithmicAxisOptions(), theme);
                break;

            case "scatter":
                config = new Chart("chart", new ScatterPlotOptions(), theme);
                break;

            case "area":
                config = new Chart("chart", new BasicAreaOptions(), theme);
                break;

            case "areaWithNegativeValues":
                config = new Chart("chart", new AreaWithNegativeValuesOptions(), theme);
                break;

            case "stackedAndGroupedColumn":
                config = new Chart("chart", new StackedAndGroupedColumnOptions(), theme);
                break;

            case "combo":
                config = new Chart("chart", new ComboOptions(), theme);
                break;

            case "donut":
                config = new Chart("chart", new DonutOptions(), theme);
                break;

            case "withDataLabels":
                config = new Chart("chart", new LineWithDataLabelsOptions(), theme);
                break;

            case "zoomableTimeSeries":
                config = new Chart("chart", new ZoomableTimeSeriesOptions(), theme);
                break;

            case "splineInverted":
                config = new Chart("chart", new SplineWithInvertedAxisOptions(), theme);
                break;

            case "splineWithPlotBands":
                config = new Chart("chart", new SplineWithPlotBandsOptions(), theme);
                break;

            case "polar":
                config = new Chart("chart", new PolarOptions(), theme);
                break;

            case "stackedArea":
                config = new Chart("chart", new StackedAreaOptions(), theme);
                break;

            case "percentageArea":
                config = new Chart("chart", new PercentageAreaOptions(), theme);
                break;

            case "areaMissing":
                config = new Chart("chart", new AreaMissingOptions(), theme);
                break;

            case "areaInverted":
                config = new Chart("chart", new AreaInvertedAxisOptions(), theme);
                break;

            case "areaSpline":
                config = new Chart("chart", new AreaSplineOptions(), theme);
                break;

            case "areaSplineRange":
                config = new Chart("chart", new AreaSplineRangeOptions(), theme);
                break;

            case "columnWithDrilldown":
                config = new Chart("chart", new ColumnWithDrilldownOptions(), theme);
                break;

            case "columnRotated":
                config = new Chart("chart", new ColumnWithRotatedLabelsOptions(), theme);
                break;

            case "stackedBar":
                config = new Chart("chart", new StackedBarOptions(), theme);
                break;

            case "barNegativeStack":
                config = new Chart("chart", new StackedBarOptions(), theme);
                break;

            case "basicColumn":
                config = new Chart("chart", new BasicColumnOptions(), theme);
                break;

            case "columnWithNegativeValues":
                config = new Chart("chart", new ColumnWithNegativeValuesOptions(), theme);
                break;

            case "stackedColumn":
                config = new Chart("chart", new StackedColumnOptions(), theme);
                break;

            case "stackedPercentage":
                config = new Chart("chart", new StackedPercentageOptions(), theme);
                break;

            case "basicPie":
                config = new Chart("chart", new BasicPieOptions(), theme);
                break;

            case "pieWithGradient":
                config = new Chart("chart", new PieWithGradientOptions(), theme);
                break;

            case "pieWithLegend":
                config = new Chart("chart", new PieWithLegendOptions(), theme);
                break;

            case "splineUpdating":
                config = new Chart("chart", new WicketSplineUpdatingOptions(), theme);
                break;

            case "bubble":
                config = new Chart("chart", new BubbleChartOptions(), theme);
                break;

            case "3dbubble":
                config = new Chart("chart", new BubbleChart3DOptions(), theme);
                break;

            case "boxplot":
                config = new Chart("chart", new BoxplotChartOptions(), theme);
                break;

            case "interactive":
                config = new Chart("chart", new InteractionOptions(), theme);
                break;

            case "angularGauge":
                config = new Chart("chart", new AngularGaugeOptions(), theme);
                break;

            case "spiderweb":
                config = new Chart("chart", new SpiderwebOptions(), theme);
                break;

            case "windrose":
                config = new Chart("chart", new WindroseOptions(), theme);
                break;

            case "columnrange":
                config = new Chart("chart", new ColumnRangeOptions(), theme);
                break;

            case "arearange":
                config = new Chart("chart", new AreaRangeOptions(), theme);
                break;

            case "clicktoadd":
                config = new Chart("chart", new ClickToAddAPointOptions(), theme);
                break;

            case "dualAxes":
                config = new Chart("chart", new DualAxesOptions(), theme);
                break;

            case "scatterWithRegression":
                config = new Chart("chart", new ScatterWithRegressionLineOptions(), theme);
                break;

            case "multipleAxes":
                config = new Chart("chart", new MultipleAxesOptions(), theme);
                break;

            case "errorBar":
                config = new Chart("chart", new ErrorBarOptions(), theme);
                break;

            case "funnel":
                config = new Chart("chart", new FunnelOptions(), theme);
                break;

            case "pyramid":
                config = new Chart("chart", new PyramidOptions(), theme);
                break;

            case "heatmap":
                config = new Chart("chart", new HeatmapOptions(), theme);
                break;

            default:
                config = new Chart("chart", new BasicLineOptions(), theme);
                break;
        }
        return config;
    }
1176211
function(chart) {
		var cache = chart.$plugins || (chart.$plugins = {});
		if (cache.id === this._cacheId) {
			return cache.descriptors;
		}

		var plugins = [];
		var descriptors = [];
		var config = (chart && chart.config) || {};
		var options = (config.options && config.options.plugins) || {};

		this._plugins.concat(config.plugins || []).forEach(function(plugin) {
			var idx = plugins.indexOf(plugin);
			if (idx !== -1) {
				return;
			}

			var id = plugin.id;
			var opts = options[id];
			if (opts === false) {
				return;
			}

			if (opts === true) {
				opts = helpers.clone(defaults.global.plugins[id]);
			}

			plugins.push(plugin);
			descriptors.push({
				plugin: plugin,
				options: opts || {}
			});
		});

		cache.descriptors = descriptors;
		cache.id = this._cacheId;
		return descriptors;
	}
400527
def dashboard(self, dashboard_id):
        """"""
        session = db.session()
        qry = session.query(models.Dashboard)
        if dashboard_id.isdigit():
            qry = qry.filter_by(id=int(dashboard_id))
        else:
            qry = qry.filter_by(slug=dashboard_id)

        dash = qry.one_or_none()
        if not dash:
            abort(404)
        datasources = set()
        for slc in dash.slices:
            datasource = slc.datasource
            if datasource:
                datasources.add(datasource)

        if config.get('ENABLE_ACCESS_REQUEST'):
            for datasource in datasources:
                if datasource and not security_manager.datasource_access(datasource):
                    flash(
                        __(security_manager.get_datasource_access_error_msg(datasource)),
                        'danger')
                    return redirect(
                        'superset/request_access/?'
                        f'dashboard_id={dash.id}&')

        dash_edit_perm = check_ownership(dash, raise_if_false=False) and \
            security_manager.can_access('can_save_dash', 'Superset')
        dash_save_perm = security_manager.can_access('can_save_dash', 'Superset')
        superset_can_explore = security_manager.can_access('can_explore', 'Superset')
        superset_can_csv = security_manager.can_access('can_csv', 'Superset')
        slice_can_edit = security_manager.can_access('can_edit', 'SliceModelView')

        standalone_mode = request.args.get('standalone') == 'true'
        edit_mode = request.args.get('edit') == 'true'

        # Hack to log the dashboard_id properly, even when getting a slug
        @log_this
        def dashboard(**kwargs):  # noqa
            pass
        dashboard(
            dashboard_id=dash.id,
            dashboard_version='v2',
            dash_edit_perm=dash_edit_perm,
            edit_mode=edit_mode)

        dashboard_data = dash.data
        dashboard_data.update({
            'standalone_mode': standalone_mode,
            'dash_save_perm': dash_save_perm,
            'dash_edit_perm': dash_edit_perm,
            'superset_can_explore': superset_can_explore,
            'superset_can_csv': superset_can_csv,
            'slice_can_edit': slice_can_edit,
        })

        bootstrap_data = {
            'user_id': g.user.get_id(),
            'dashboard_data': dashboard_data,
            'datasources': {ds.uid: ds.data for ds in datasources},
            'common': self.common_bootsrap_payload(),
            'editMode': edit_mode,
        }

        if request.args.get('json') == 'true':
            return json_success(json.dumps(bootstrap_data))

        return self.render_template(
            'superset/dashboard.html',
            entry='dashboard',
            standalone_mode=standalone_mode,
            title=dash.dashboard_title,
            bootstrap_data=json.dumps(bootstrap_data),
        )
831327
def load_graphs():
    ''''''
    mestate.graphs = []
    gfiles = ['mavgraphs.xml']
    if 'HOME' in os.environ:
        for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
            for filename in filenames:
                
                if filename.lower().endswith('.xml'):
                    gfiles.append(os.path.join(dirname, filename))
    for file in gfiles:
        if not os.path.exists(file):
            continue
        graphs = load_graph_xml(open(file).read(), file)
        if graphs:
            mestate.graphs.extend(graphs)
            mestate.console.writeln("Loaded %s" % file)
    # also load the built in graphs
    dlist = pkg_resources.resource_listdir("MAVProxy", "tools/graphs")
    for f in dlist:
        raw = pkg_resources.resource_stream("MAVProxy", "tools/graphs/%s" % f).read()
        graphs = load_graph_xml(raw, None)
        if graphs:
            mestate.graphs.extend(graphs)
            mestate.console.writeln("Loaded %s" % f)
    mestate.graphs = sorted(mestate.graphs, key=lambda g: g.name)
1133292
def _urls(self):
        """"""
        urlpatterns = self._get_default_urlpatterns()
        self._autodiscover()

        # Discover each dashboard's panels.
        for dash in self._registry.values():
            dash._autodiscover()

        # Load the plugin-based panel configuration
        self._load_panel_customization()

        # Allow for override modules
        if self._conf.get("customization_module", None):
            customization_module = self._conf["customization_module"]
            bits = customization_module.split('.')
            mod_name = bits.pop()
            package = '.'.join(bits)
            mod = import_module(package)
            try:
                before_import_registry = copy.copy(self._registry)
                import_module('%s.%s' % (package, mod_name))
            except Exception:
                self._registry = before_import_registry
                if module_has_submodule(mod, mod_name):
                    raise

        # Compile the dynamic urlconf.
        for dash in self._registry.values():
            urlpatterns.append(url(r'^%s/' % dash.slug,
                                   _wrapped_include(dash._decorated_urls)))

        # Return the three arguments to django.conf.urls.include
        return urlpatterns, self.namespace, self.slug
1043817
def _ensure_annotations(dashboard):
    ''''''
    if 'annotation_tags' not in dashboard:
        return
    tags = dashboard['annotation_tags']
    annotations = {
        'enable': True,
        'list': [],
    }
    for tag in tags:
        annotations['list'].append({
            'datasource': "graphite",
            'enable': False,
            'iconColor': "#C0C6BE",
            'iconSize': 13,
            'lineColor': "rgba(255, 96, 96, 0.592157)",
            'name': tag,
            'showLine': True,
            'tags': tag,
        })
    del dashboard['annotation_tags']
    dashboard['annotations'] = annotations
645504
function callAdapter(chartType, chart) {
  let i, adapter, fnName, adapterName;
  fnName = "render" + chartType;
  adapterName = chart.options.adapter;

  loadAdapters();

  for (i = 0; i < adapters.length; i++) {
    adapter = adapters[i];
    if ((!adapterName || adapterName === adapter.name) && isFunction(adapter[fnName])) {
      chart.adapter = adapter.name;
      chart.__adapterObject = adapter;
      return adapter[fnName](chart);
    }
  }

  if (adapters.length > 0) {
    throw new Error("No charting library found for " + chartType);
  } else {
    throw new Error("No charting libraries found - be sure to include one before your charts");
  }
}
1271966
function () {
            var chart = this,
              axes = chart.axes,
              renderer = chart.renderer,
              options = chart.options;

            // Title
            chart.setTitle();


            // Legend
            chart.legend = new Legend(chart, options.legend);

            chart.getStacks(); // render stacks

            // Get margins by pre-rendering axes
            // set axes scales
            each(axes, function (axis) {
                axis.setScale();
            });

            chart.getMargins();

            chart.maxTicks = null; // reset for second pass
            each(axes, function (axis) {
                axis.setTickPositions(true); // update to reflect the new margins
                axis.setMaxTicks();
            });
            chart.adjustTickAmounts();
            chart.getMargins(); // second pass to check for new labels


            // Draw the borders and backgrounds
            chart.drawChartBox();


            // Axes
            if (chart.hasCartesianSeries) {
                each(axes, function (axis) {
                    axis.render();
                });
            }

            // The series
            if (!chart.seriesGroup) {
                chart.seriesGroup = renderer.g('series-group')
                  .attr({ zIndex: 3 })
                  .add();
            }
            chart.renderSeries();

            // Labels
            chart.renderLabels();

            // Credits
            chart.showCredits(options.credits);

            // Set flag
            chart.hasRendered = true;

        }
488511
@Override
    public List<Dashboard> getDashboards() {
        
       
            JAXBContext context;
            try {
                context = JAXBContext.newInstance(Dashboard.class.getPackage().getName());
            } catch (JAXBException e) {
                throw new IllegalArgumentException("Could not create JAXBContext", e);
            }
            List<Dashboard> dashboards = new ArrayList<Dashboard>();
            try {
                Configuration config = (Configuration) context.createUnmarshaller().unmarshal(sourceXml.getInputStream());
                dashboards.addAll(config.getDashboard());
            } catch (Exception e) {
                throw new IllegalStateException("Could not load dashboards configuration from " + sourceXml.toString(), e);
            }
            /*
            if(additionalSourceXml != null) {
                if (additionalSourceXml.isReadable()) {
            
                    try {
                        Configuration config = (Configuration) context.createUnmarshaller().unmarshal(additionalSourceXml.getInputStream());
                        dashboards.addAll(config.getDashboard());
                    } catch (Exception e) {
                    throw new IllegalStateException("Could not load dashboards configuration from " + additionalSourceXml.toString(), e);
                    }
                } else {
                    throw new IllegalStateException("Could not read configuration from " + additionalSourceXml.toString());
                }
            }
            */
            Collections.sort(dashboards);
            return dashboards;
      
       
    }
522377
def horizon_main_nav(context):
    """"""
    if 'request' not in context:
        return {}
    current_dashboard = context['request'].horizon.get('dashboard', None)
    dashboards = []
    for dash in Horizon.get_dashboards():
        if dash.can_access(context):
            if callable(dash.nav) and dash.nav(context):
                dashboards.append(dash)
            elif dash.nav:
                dashboards.append(dash)
    return {'components': dashboards,
            'user': context['request'].user,
            'current': current_dashboard,
            'request': context['request']}
1218843
function getDashboardOperations(self) {
	var curatedDevice = self;

	// Object that stores the registered listeners.  When there are
	// no listeners, the dashboard data collection should be stopped.
	var dashboardListeners = {};

	// Object that caches the data.
	this.dataCache = {};

	// Function that adds a data listener.
	function addListener(uid) {
		var addedListener = false;
		if(typeof(dashboardListeners[uid]) === 'undefined') {
			dashboardListeners[uid] = {
				'startTime': new Date(),
				'numIterations': 0,
				'uid': uid,
				'numStarts': 1,
			};
			addedListener = true;
		} else {
			// Don't add the listener.
			dashboardListeners[uid].numStarts += 1;
		}
		return addedListener;
	}

	// Function that removes a data listener.  
	function removeListener(uid) {
		var removedListener = false;
		if(typeof(dashboardListeners[uid]) !== 'undefined') {
			dashboardListeners[uid] = undefined;
			delete dashboardListeners[uid];
			removedListener = true;
		}
		return removedListener;
	}

	// Function that gets the number of listeners.
	function getNumListeners() {
		return Object.keys(dashboardListeners).length;
	}

	// This is a test function that just prooves "basic signs of life".
	this.testFunc = function() {
		var defered = q.defer();
		debugDTF("In Dashboard testFunc",
			self.savedAttributes.productType,
			self.savedAttributes.serialNumber,
			self.savedAttributes.serialNumber
		);
		var info = {
			'pt': self.savedAttributes.productType,
			'sn': self.savedAttributes.serialNumber,
		};
		defered.resolve(info);
		return defered.promise;
	};

	// variable that stores the dataCollector
	var dataCollector;

	// Function that handles the data collection "data" events.  This
	// data is the data returned by the read-commands that are performed.
	// This data still needs to be interpreted saved, cached, and organized
	// into "channels".
	// Maybe?? The dashboard_data_collector has logic for each of the devices.
	// This logic should probably be put there?
	function dataCollectorHandler(data) {
		// debugDDC('New data', data['FIO0']);
		var diffObj = _.diff(data, self.dataCache);

		// console.log('Data Difference - diff', diffObj);
		// Clean the object to get rid of empty results.
		diffObj = _.pickBy(diffObj, function(value, key) {
			return Object.keys(value).length > 0;
		});

		var numKeys = Object.keys(data);
		var numNewKeys = Object.keys(diffObj);
		// console.log('Num Keys for new data', numKeys, numNewKeys);
		// console.log('Data Difference - pickBy', diffObj);
		self.dataCache = data;

		self.emit(device_events.DASHBOARD_DATA_UPDATE, diffObj);
	}

	// Function that creates the "bundle" that is built-up and passed between
	// the steps that perform the "start" method.
	function createStartBundle(uid) {
		// Create and define the bundle object.
		return {
			'uid': uid,
			'data': {},
		};
	}

	// This function starts the data collector and registers event listeners.
	function innerStart (bundle) {
		var defered = q.defer();

		// Device Type is either T4, T5, or T7
		var deviceType = self.savedAttributes.deviceTypeName;

		// Save the created data collector object
		dataCollector = new dashboard_data_collector.create(deviceType);

		// Listen to only the next 'data' event emitted by the dataCollector.
		dataCollector.once('data', function(data) {
			debugDStart('dev_cur-dash_ops: First bit of data!');

			// Listen to future data.
			dataCollector.on('data', dataCollectorHandler);

			// Save the data to the data cache.
			self.dataCache = data;
			bundle.data = data;

			// Declare the innerStart function to be finished.
			defered.resolve(bundle);
		});

		// Start the data collector.
		dataCollector.start(self);

		return defered.promise;
	}

	/*
	 * This function starts the dashboard-ops procedure and registers a listener.
	 * This function returns data required to initialize the dashboard page.  If
	 * the listener already exists then its uid isn't added (since it is already
	 * there).
	*/
	this.start = function(uid) {
		var defered = q.defer();
		var addedListener = addListener(uid);
		var numListeners = getNumListeners();
		var bundle = createStartBundle(uid);

		function onSuccess(rBundle) {
			defered.resolve(rBundle);
		}
		function onError(rBundle) {
			defered.resolve(rBundle);
		}

		if(addedListener && (numListeners == 1)) {
			// We need to start the dashboard-service and we need to return 
			// the current state of all of the channels.
			innerStart(bundle)
			.then(onSuccess, onError);
		} else {
			// We don't need to start the dashboard-service.  We just need to
			// return the current state of all of the channels.
			onSuccess(bundle);
		}
		return defered.promise;
	};

	/*
	 * These functions "pause" and "resume" the data-reporting
	 */
	this.pauseReporting = function(){};
	this.resumeReporting = function(){};

	/*
	 * These functions "pause" and "resume" the DAQ loop collecting data from
	 * the device.
	 */
	this.pauseCollecting = function(){};
	this.resumeCollecting = function(){};


	function createStopBundle(uid) {
		return {
			'uid': uid,
			'isStopped': false,
		};
	}
	function innerStop(bundle) {
		var defered = q.defer();

		var isStopped = dataCollector.stop();
		bundle.isStopped = isStopped;
		defered.resolve(bundle);

		return defered.promise;
	}

	/* 
	 * This function stops the dashboard-ops procedure and un-registers a listener.
	 * If there are zero remaining listeners than the DAQ loop actually stops running.
	 */
	this.stop = function(uid){
		var defered = q.defer();
		var removedListener = removeListener(uid);
		var numListeners = getNumListeners();
		var bundle = createStopBundle(uid);

		function onSuccess(rBundle) {
			defered.resolve(rBundle);
		}
		function onError(rBundle) {
			defered.resolve(rBundle);
		}

		if(removedListener && (numListeners === 0)) {
			// We need to stop the dashboard-service.
			innerStop(bundle)
			.then(onSuccess, onError);
		} else {
			// We don't need to stop the dashboard-service.  It should already
			// be stopped.
			onSuccess(bundle);
		}
		return defered.promise;
	};

	function createConfigIOBundle(channelName, attribute, value) {
		var bundle = {
			'channelName': channelName,
			'attribute': attribute,
			'value': value,

			'registersToWrite': [],
			'valuesToWrite': [],

			'isError': false,
			'errMessage': '',
		};
		return bundle;
	}

	
	function getChannelInfo(channelName) {
		var deviceTypeName = curatedDevice.savedAttributes.deviceTypeName;
		var channels = dashboard_channel_parser.channels[deviceTypeName];

		var chInfo = channels[channelName];

		var info = {
			'type': chInfo.type,
			'ioNum': chInfo.ioNum,
			'name': chInfo.name,
		};

		return info;
	}
	function performWrites(bundle) {
		var executeWrite = false;
		if(bundle.registersToWrite.length >= 0) {
			if(bundle.valuesToWrite.length >= 0) {
				executeWrite = true;
			}
		}
		var defered = q.defer();
		if(executeWrite) {
			// console.log('Executing iWriteMany', bundle.registersToWrite, bundle.valuesToWrite);
			curatedDevice.iWriteMany(bundle.registersToWrite, bundle.valuesToWrite)
			.then(function(res) {
				defered.resolve({
					'registers': bundle.registersToWrite,
					'values': bundle.valuesToWrite,
				});
			})
			.catch(function(err) {
				defered.resolve({
					'registers': bundle.registersToWrite,
					'values': bundle.valuesToWrite,
					'err': err,
				});
			});
		} else {
			defered.resolve({
				'registers': bundle.registersToWrite,
				'values': bundle.valuesToWrite,
			});
		}
		return defered.promise;
	}

	this.configIO = function(channelName, attribute, value) {
		// console.log('in this.configIO', channelName, attribute, value);
		var defered = q.defer();

		var bundle = createConfigIOBundle(channelName, attribute, value);

		var validAttributes = {
			'analogEnable': {
				'enable': 1,
				'disable': 0,
			},
			'digitalDirection': {
				'output': 1,
				'input': 0,
			},
			'digitalState': {
				'high': 1,
				'low': 0,
			},
		};

		var chInfo = getChannelInfo(channelName);
		var chType = chInfo.type;

		var chNum = 0;
		var chNumValid = false;
		try {
			if(typeof(value) === 'string') {
				chNum = validAttributes[attribute][value];
			} else if(typeof(value) === 'number') {
				chNum = value;
			}
			if(typeof(chNum) === 'number') {
				chNumValid = true;
			}
		} catch(err) {
			// catch the error...
		}

		
		var bitMask = 0x0FFFFFFF;
		if(chNumValid) {
			if(chType === 'AIN') {
				// We don't have to really write anything...
			} else if(chType === 'DIO') {
				if(attribute === 'digitalDirection') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_DIRECTION');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'digitalState') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_STATE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				}
			} else if(chType === 'FLEX') {
				if(attribute === 'digitalDirection') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_DIRECTION');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'digitalState') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_STATE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'analogEnable') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_ANALOG_ENABLE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				}
			} else if(chType === 'AO') {
				if(attribute === 'analogValue') {
					bundle.registersToWrite.push(chInfo.name);
					bundle.valuesToWrite.push(value);
				}
			} else {
				// Don't do anything...
			}
		}

		// console.log('resolving..', chInfo, chType, chNum, chNumValid, bundle.registersToWrite, bundle.valuesToWrite);
		performWrites(bundle)
		.then(defered.resolve)
		.catch(defered.resolve);
		return defered.promise;
	};
}