text:
import collections
import six

from nailgun import consts
from nailgun.logger import logger
from nailgun import objects

def check_received_data(cached, received):
    """Check data received from net_probe (received)

    Received data is checked against data from task (cached) for one node.
    Assemble connectivity errors description and return it to the caller.

    :param   cached: data for one node from task.cache
    :type    cached: dict
    :param received: data for one node from net_checker response ('nodes')
    :type  received: dict
    :returns: connectivity errors description (list of dicts - one dict
              per error)
    """
    # Convert cached and received data from interface:vlans form
    # to vlan:interfaces form to perform analysis of interfaces within bonds.
    cached_vlans = collections.defaultdict(list)
    for cached_network in cached['networks']:
        for vlan in cached_network['vlans']:
            cached_vlans[vlan].append(cached_network['iface'])
    received_vlans = collections.defaultdict(list)
    for received_network in received.get('networks', []):
        for vlan in received_network['vlans']:
            received_vlans[vlan].append(
                received_network['iface'])

    absent = collections.defaultdict(list)
    for vlan in cached_vlans:
        absent_ifaces = set(cached_vlans[vlan])
        if vlan in received_vlans:
            absent_ifaces -= set(received_vlans[vlan])
            if absent_ifaces and \
                    cached['status'] != consts.NODE_STATUSES.ready and \
                    cached.get('bonds'):

                # We pass NICs instead of bonds while node is not deployed.
                # Check that at least one slave NIC of every bond has received
                # test data.
                for bond_name, slave_names in six.iteritems(cached['bonds']):
                    slaves = set(slave_names)
                    if absent_ifaces >= slaves:
                        # No NIC of this bond has received test data.
                        absent_ifaces.add(bond_name)
                    # These NICs should be excluded as we add bond's name
                    # if no data was received on any of them. If some data
                    # was received on some of them we don't need them
                    # either as the bond passes the test in this case.
                    absent_ifaces -= slaves
                # No bonds' slaves left in absent_ifaces just NICs and bonds.

        # Convert back to interface:vlans form to provide compatibility
        # with current UI. Will be removed when UI is updated.
        for iface in absent_ifaces:
            absent[iface].append(vlan)

    errors = []
    if absent:
        node_db = objects.Node.get_by_mac_or_uid(
            node_uid=cached['uid'])
        for iface in absent:
            error = {
                'uid': cached['uid'],
                'interface': iface,
                'absent_vlans': absent[iface],
                'name': cached['name'],
            }
            if node_db:
                for if_db in node_db.interfaces:
                    if if_db.name == iface:
                        error['mac'] = if_db.mac
                        break
            if 'mac' not in error:
                logger.warning(
                    "verify_networks_resp: can't find "
                    "interface %r for node %r in DB",
                    iface, cached['name']
                )
                error['mac'] = 'unknown'
            errors.append(error)

    return errors

def append_message(original, appendix):
    """Append message to output string with a delimiter

    No delimiter is added if any of strings is empty.
    """
    return '\n'.join(filter(None, (original, appendix)))


text:
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/slab.h>

#include <sound/soc.h>
#include <sound/soc-dapm.h>

#include <linux/mfd/arizona/core.h>
#include <linux/mfd/arizona/pdata.h>
#include <linux/mfd/arizona/registers.h>

struct arizona_haptics {
	struct arizona *arizona;
	struct input_dev *input_dev;
	struct work_struct work;

	struct mutex mutex;
	u8 intensity;
};

static void arizona_haptics_work(struct work_struct *work)
{
	struct arizona_haptics *haptics = container_of(work,
						       struct arizona_haptics,
						       work);
	struct arizona *arizona = haptics->arizona;
	int ret;

	if (!haptics->arizona->dapm) {
		dev_err(arizona->dev, "No DAPM context\n");
		return;
	}

	if (haptics->intensity) {
		ret = regmap_update_bits(arizona->regmap,
					 ARIZONA_HAPTICS_PHASE_2_INTENSITY,
					 ARIZONA_PHASE2_INTENSITY_MASK,
					 haptics->intensity);
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to set intensity: %d\n",
				ret);
			return;
		}

		/* This enable sequence will be a noop if already enabled */
		ret = regmap_update_bits(arizona->regmap,
					 ARIZONA_HAPTICS_CONTROL_1,
					 ARIZONA_HAP_CTRL_MASK,
					 1 << ARIZONA_HAP_CTRL_SHIFT);
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to start haptics: %d\n",
				ret);
			return;
		}

		ret = snd_soc_dapm_enable_pin(arizona->dapm, "HAPTICS");
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to start HAPTICS: %d\n",
				ret);
			return;
		}

		ret = snd_soc_dapm_sync(arizona->dapm);
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to sync DAPM: %d\n",
				ret);
			return;
		}
	} else {
		/* This disable sequence will be a noop if already enabled */
		ret = snd_soc_dapm_disable_pin(arizona->dapm, "HAPTICS");
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to disable HAPTICS: %d\n",
				ret);
			return;
		}

		ret = snd_soc_dapm_sync(arizona->dapm);
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to sync DAPM: %d\n",
				ret);
			return;
		}

		ret = regmap_update_bits(arizona->regmap,
					 ARIZONA_HAPTICS_CONTROL_1,
					 ARIZONA_HAP_CTRL_MASK, 0);
		if (ret != 0) {
			dev_err(arizona->dev, "Failed to stop haptics: %d\n",
				ret);
			return;
		}
	}
}

static int arizona_haptics_play(struct input_dev *input, void *data,
				struct ff_effect *effect)
{
	struct arizona_haptics *haptics = input_get_drvdata(input);
	struct arizona *arizona = haptics->arizona;

	if (!arizona->dapm) {
		dev_err(arizona->dev, "No DAPM context\n");
		return -EBUSY;
	}

	if (effect->u.rumble.strong_magnitude) {
		/* Scale the magnitude into the range the device supports */
		if (arizona->pdata.hap_act) {
			haptics->intensity =
				effect->u.rumble.strong_magnitude >> 9;
			if (effect->direction < 0x8000)
				haptics->intensity += 0x7f;
		} else {
			haptics->intensity =
				effect->u.rumble.strong_magnitude >> 8;
		}
	} else {
		haptics->intensity = 0;
	}

	schedule_work(&haptics->work);

	return 0;
}

static void arizona_haptics_close(struct input_dev *input)
{
	struct arizona_haptics *haptics = input_get_drvdata(input);

	cancel_work_sync(&haptics->work);

	if (haptics->arizona->dapm)
		snd_soc_dapm_disable_pin(haptics->arizona->dapm, "HAPTICS");
}

static int arizona_haptics_probe(struct platform_device *pdev)
{
	struct arizona *arizona = dev_get_drvdata(pdev->dev.parent);
	struct arizona_haptics *haptics;
	int ret;

	haptics = devm_kzalloc(&pdev->dev, sizeof(*haptics), GFP_KERNEL);
	if (!haptics)
		return -ENOMEM;

	haptics->arizona = arizona;

	ret = regmap_update_bits(arizona->regmap, ARIZONA_HAPTICS_CONTROL_1,
				 ARIZONA_HAP_ACT, arizona->pdata.hap_act);
	if (ret != 0) {
		dev_err(arizona->dev, "Failed to set haptics actuator: %d\n",
			ret);
		return ret;
	}

	INIT_WORK(&haptics->work, arizona_haptics_work);

	haptics->input_dev = devm_input_allocate_device(&pdev->dev);
	if (!haptics->input_dev) {
		dev_err(arizona->dev, "Failed to allocate input device\n");
		return -ENOMEM;
	}

	input_set_drvdata(haptics->input_dev, haptics);

	haptics->input_dev->name = "arizona:haptics";
	haptics->input_dev->close = arizona_haptics_close;
	__set_bit(FF_RUMBLE, haptics->input_dev->ffbit);

	ret = input_ff_create_memless(haptics->input_dev, NULL,
				      arizona_haptics_play);
	if (ret < 0) {
		dev_err(arizona->dev, "input_ff_create_memless() failed: %d\n",
			ret);
		return ret;
	}

	ret = input_register_device(haptics->input_dev);
	if (ret < 0) {
		dev_err(arizona->dev, "couldn't register input device: %d\n",
			ret);
		return ret;
	}

	platform_set_drvdata(pdev, haptics);

	return 0;
}

static struct platform_driver arizona_haptics_driver = {
	.probe		= arizona_haptics_probe,
	.driver		= {
		.name	= "arizona-haptics",
	},
};
module_platform_driver(arizona_haptics_driver);

MODULE_ALIAS("platform:arizona-haptics");
MODULE_DESCRIPTION("Arizona haptics driver");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");

redpajama_set_name: RedPajamaGithub


text:
@interface NSDictionary (ObjectForKeyOrNil)

- (id)objectForKeyOrNil:(id)key;

@end


text:
package com.graphhopper.storage;

import com.graphhopper.routing.ev.BooleanEncodedValue;
import com.graphhopper.routing.ev.DecimalEncodedValue;
import com.graphhopper.routing.ev.DecimalEncodedValueImpl;
import com.graphhopper.routing.ev.SimpleBooleanEncodedValue;
import com.graphhopper.routing.util.AccessFilter;
import com.graphhopper.routing.util.AllEdgesIterator;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.LocationIndexTree;
import com.graphhopper.util.GHUtility;
import org.junit.jupiter.api.Test;

import java.util.Set;
import java.util.TreeSet;

import static com.graphhopper.util.GHUtility.updateDistancesFor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

/**
 * @author Peter Karich
 */
public class GraphEdgeIdFinderTest {

    @Test
    public void testParseStringHints() {
        BooleanEncodedValue accessEnc = new SimpleBooleanEncodedValue("access", true);
        DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false);
        EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build();
        BaseGraph graph = new BaseGraph.Builder(em).create();
        // 0-1-2
        // | |
        // 3-4
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(0, 1).setDistance(1));
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(1, 2).setDistance(1));
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(3, 4).setDistance(1));
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(0, 3).setDistance(1));
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(1, 4).setDistance(1));
        updateDistancesFor(graph, 0, 0.01, 0.00);
        updateDistancesFor(graph, 1, 0.01, 0.01);
        updateDistancesFor(graph, 2, 0.01, 0.02);
        updateDistancesFor(graph, 3, 0.00, 0.00);
        updateDistancesFor(graph, 4, 0.00, 0.01);

        LocationIndex locationIndex = new LocationIndexTree(graph, new RAMDirectory())
                .prepareIndex();

        GraphEdgeIdFinder graphFinder = new GraphEdgeIdFinder(graph, locationIndex);
        GraphEdgeIdFinder.BlockArea blockArea = graphFinder.parseBlockArea("0.01,0.005,1", AccessFilter.allEdges(accessEnc), 1000 * 1000);
        assertEquals("[0]", blockArea.toString(0));

        // big area => no edgeIds are collected up-front
        graphFinder = new GraphEdgeIdFinder(graph, locationIndex);
        blockArea = graphFinder.parseBlockArea("0,0,1000", AccessFilter.allEdges(accessEnc), 1000 * 1000);
        assertFalse(blockArea.hasCachedEdgeIds(0));
    }

    @Test
    public void testBlockAreasWithPolygon() {
        BooleanEncodedValue accessEnc = new SimpleBooleanEncodedValue("access", true);
        DecimalEncodedValue speedEnc = new DecimalEncodedValueImpl("speed", 5, 5, false);
        EncodingManager em = EncodingManager.start().add(accessEnc).add(speedEnc).build();
        BaseGraph graph = new BaseGraph.Builder(em).create();

        // 00-01-02-03
        // |  |
        // 04-05-06-07
        // |  |
        // 08-09-10-11
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(0, 1).setDistance(1)); // 0
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(1, 2).setDistance(1)); // 1
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(2, 3).setDistance(1)); // 2
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(0, 4).setDistance(1)); // 3
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(1, 5).setDistance(1)); // 4
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(4, 5).setDistance(1)); // 5
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(5, 6).setDistance(1)); // 6
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(6, 7).setDistance(1)); // 7
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(4, 8).setDistance(1)); // 8
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(5, 9).setDistance(1)); // 9
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(8, 9).setDistance(1)); // 10
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(9, 10).setDistance(1)); // 11
        GHUtility.setSpeed(60, true, true, accessEnc, speedEnc, graph.edge(10, 11).setDistance(1)); // 12

        updateDistancesFor(graph, 0, 2, 0);
        updateDistancesFor(graph, 1, 2, 1);
        updateDistancesFor(graph, 2, 2, 2);
        updateDistancesFor(graph, 3, 2, 3);
        updateDistancesFor(graph, 4, 1, 0);
        updateDistancesFor(graph, 5, 1, 1);
        updateDistancesFor(graph, 6, 1, 2);
        updateDistancesFor(graph, 7, 1, 3);
        updateDistancesFor(graph, 8, 0, 0);
        updateDistancesFor(graph, 9, 0, 1);
        updateDistancesFor(graph, 10, 0, 2);
        updateDistancesFor(graph, 11, 0, 3);

        LocationIndex locationIndex = new LocationIndexTree(graph, new RAMDirectory())
                .prepareIndex();

        GraphEdgeIdFinder graphFinder = new GraphEdgeIdFinder(graph, locationIndex);
        // big value => the polygon is small => force edgeId optimization
        double area = 500_000L * 500_000L;
        GraphEdgeIdFinder.BlockArea blockArea = graphFinder.parseBlockArea("2.1,1, -1.1,2, 2,3", AccessFilter.allEdges(accessEnc), area);
        assertEquals("[1, 2, 6, 7, 11, 12]", blockArea.toString(0));
        assertEdges(graph, "[1, 2, 6, 7, 11, 12]", blockArea);

        // small value => same polygon is now "large" => do not pre-calculate edgeId set => check only geometries
        blockArea = graphFinder.parseBlockArea("2.1,1, 0.9,3, 0.9,2, -0.3,0", AccessFilter.allEdges(accessEnc), 1000 * 1000);
        assertFalse(blockArea.hasCachedEdgeIds(0));
        assertEdges(graph, "[0, 1, 4, 5, 6, 7, 9, 10]", blockArea);

        blockArea = graphFinder.parseBlockArea("1.5,3,100000", AccessFilter.allEdges(accessEnc), area);
        assertEquals("[2, 7]", blockArea.toString(0));
        assertEdges(graph, "[2, 7]", blockArea);
    }

    private void assertEdges(Graph g, String assertSetContent, GraphEdgeIdFinder.BlockArea blockArea) {
        Set<Integer> blockedEdges = new TreeSet<>();
        AllEdgesIterator edgeIterator = g.getAllEdges();
        while (edgeIterator.next()) {
            if (blockArea.intersects(edgeIterator))
                blockedEdges.add(edgeIterator.getEdge());
        }
        assertEquals(assertSetContent, blockedEdges.toString());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Azure.AI.AnomalyDetector.Models
{
    /// <summary> Model factory for read-only models. </summary>
    public static partial class AnomalyDetectorModelFactory
    {
        /// <summary> Initializes a new instance of EntireDetectResponse. </summary>
        /// <param name="period"> Frequency extracted from the series, zero means no recurrent pattern has been found. </param>
        /// <param name="expectedValues"> ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. </param>
        /// <param name="upperMargins"> UpperMargins contain upper margin of each input point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in client side. The index of the array is consistent with the input series. </param>
        /// <param name="lowerMargins"> LowerMargins contain lower margin of each input point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client side. The index of the array is consistent with the input series. </param>
        /// <param name="isAnomaly"> IsAnomaly contains anomaly properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. </param>
        /// <param name="isNegativeAnomaly"> IsNegativeAnomaly contains anomaly status in negative direction for each input point. True means a negative anomaly has been detected. A negative anomaly means the point is detected as an anomaly and its real value is smaller than the expected one. The index of the array is consistent with the input series. </param>
        /// <param name="isPositiveAnomaly"> IsPositiveAnomaly contain anomaly status in positive direction for each input point. True means a positive anomaly has been detected. A positive anomaly means the point is detected as an anomaly and its real value is larger than the expected one. The index of the array is consistent with the input series. </param>
        /// <returns> A new <see cref="Models.EntireDetectResponse"/> instance for mocking. </returns>
        public static EntireDetectResponse EntireDetectResponse(int period = default, IEnumerable<float> expectedValues = null, IEnumerable<float> upperMargins = null, IEnumerable<float> lowerMargins = null, IEnumerable<bool> isAnomaly = null, IEnumerable<bool> isNegativeAnomaly = null, IEnumerable<bool> isPositiveAnomaly = null)
        {
            expectedValues ??= new List<float>();
            upperMargins ??= new List<float>();
            lowerMargins ??= new List<float>();
            isAnomaly ??= new List<bool>();
            isNegativeAnomaly ??= new List<bool>();
            isPositiveAnomaly ??= new List<bool>();

            return new EntireDetectResponse(period, expectedValues?.ToList(), upperMargins?.ToList(), lowerMargins?.ToList(), isAnomaly?.ToList(), isNegativeAnomaly?.ToList(), isPositiveAnomaly?.ToList());
        }

        /// <summary> Initializes a new instance of LastDetectResponse. </summary>
        /// <param name="period"> Frequency extracted from the series, zero means no recurrent pattern has been found. </param>
        /// <param name="suggestedWindow"> Suggested input series points needed for detecting the latest point. </param>
        /// <param name="expectedValue"> Expected value of the latest point. </param>
        /// <param name="upperMargin"> Upper margin of the latest point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it should be treated as normal value. By adjusting marginScale value, anomaly status of latest point can be changed. </param>
        /// <param name="lowerMargin"> Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. </param>
        /// <param name="isAnomaly"> Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. </param>
        /// <param name="isNegativeAnomaly"> Anomaly status in negative direction of the latest point. True means the latest point is an anomaly and its real value is smaller than the expected one. </param>
        /// <param name="isPositiveAnomaly"> Anomaly status in positive direction of the latest point. True means the latest point is an anomaly and its real value is larger than the expected one. </param>
        /// <returns> A new <see cref="Models.LastDetectResponse"/> instance for mocking. </returns>
        public static LastDetectResponse LastDetectResponse(int period = default, int suggestedWindow = default, float expectedValue = default, float upperMargin = default, float lowerMargin = default, bool isAnomaly = default, bool isNegativeAnomaly = default, bool isPositiveAnomaly = default)
        {
            return new LastDetectResponse(period, suggestedWindow, expectedValue, upperMargin, lowerMargin, isAnomaly, isNegativeAnomaly, isPositiveAnomaly);
        }

        /// <summary> Initializes a new instance of ChangePointDetectResponse. </summary>
        /// <param name="period"> Frequency extracted from the series, zero means no recurrent pattern has been found. </param>
        /// <param name="isChangePoint"> isChangePoint contains change point properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. </param>
        /// <param name="confidenceScores"> the change point confidence of each point. </param>
        /// <returns> A new <see cref="Models.ChangePointDetectResponse"/> instance for mocking. </returns>
        public static ChangePointDetectResponse ChangePointDetectResponse(int? period = null, IEnumerable<bool> isChangePoint = null, IEnumerable<float> confidenceScores = null)
        {
            isChangePoint ??= new List<bool>();
            confidenceScores ??= new List<float>();

            return new ChangePointDetectResponse(period, isChangePoint?.ToList(), confidenceScores?.ToList());
        }

        /// <summary> Initializes a new instance of ModelInfo. </summary>
        /// <param name="slidingWindow"> An optional field, indicates how many history points will be used to determine the anomaly score of one subsequent point. </param>
        /// <param name="alignPolicy"> An optional field, since those multivariate need to be aligned in the same timestamp before starting the detection. </param>
        /// <param name="source"> source file link of the input variables, each variable will be a csv with two columns, the first column will be timestamp, the second column will be value.Besides these variable csv files, an extra meta.json can be included in th zip file if you would like to rename a variable.Be default, the file name of the variable will be used as the variable name. </param>
        /// <param name="startTime"> require field, start time of data be used for generating multivariate anomaly detection model, should be data-time. </param>
        /// <param name="endTime"> require field, end time of data be used for generating multivariate anomaly detection model, should be data-time. </param>
        /// <param name="displayName"> optional field, name of the model. </param>
        /// <param name="status"> Model training status. </param>
        /// <param name="errors"> Error message when fails to create a model. </param>
        /// <param name="diagnosticsInfo"> Used for deep analysis model and variables. </param>
        /// <returns> A new <see cref="Models.ModelInfo"/> instance for mocking. </returns>
        public static ModelInfo ModelInfo(int? slidingWindow = null, AlignPolicy alignPolicy = null, string source = null, DateTimeOffset startTime = default, DateTimeOffset endTime = default, string displayName = null, ModelStatus? status = null, IEnumerable<ErrorResponse> errors = null, DiagnosticsInfo diagnosticsInfo = null)
        {
            errors ??= new List<ErrorResponse>();

            return new ModelInfo(slidingWindow, alignPolicy, source, startTime, endTime, displayName, status, errors?.ToList(), diagnosticsInfo);
        }

        /// <summary> Initializes a new instance of ErrorResponse. </summary>
        /// <param name="code"> The error Code. </param>
        /// <param name="message"> A message explaining the error reported by the service. </param>
        /// <returns> A new <see cref="Models.ErrorResponse"/> instance for mocking. </returns>
        public static ErrorResponse ErrorResponse(string code = null, string message = null)
        {
            return new ErrorResponse(code, message);
        }

        /// <summary> Initializes a new instance of DiagnosticsInfo. </summary>
        /// <param name="modelState"></param>
        /// <param name="variableStates"></param>
        /// <returns> A new <see cref="Models.DiagnosticsInfo"/> instance for mocking. </returns>
        public static DiagnosticsInfo DiagnosticsInfo(ModelState modelState = null, IEnumerable<VariableState> variableStates = null)
        {
            variableStates ??= new List<VariableState>();

            return new DiagnosticsInfo(modelState, variableStates?.ToList());
        }

        /// <summary> Initializes a new instance of ModelState. </summary>
        /// <param name="epochIds"> Epoch id. </param>
        /// <param name="trainLosses"></param>
        /// <param name="validationLosses"></param>
        /// <param name="latenciesInSeconds"></param>
        /// <returns> A new <see cref="Models.ModelState"/> instance for mocking. </returns>
        public static ModelState ModelState(IEnumerable<int> epochIds = null, IEnumerable<float> trainLosses = null, IEnumerable<float> validationLosses = null, IEnumerable<float> latenciesInSeconds = null)
        {
            epochIds ??= new List<int>();
            trainLosses ??= new List<float>();
            validationLosses ??= new List<float>();
            latenciesInSeconds ??= new List<float>();

            return new ModelState(epochIds?.ToList(), trainLosses?.ToList(), validationLosses?.ToList(), latenciesInSeconds?.ToList());
        }

        /// <summary> Initializes a new instance of VariableState. </summary>
        /// <param name="variable"> Variable name. </param>
        /// <param name="filledNARatio"> Merged NA ratio of a variable. </param>
        /// <param name="effectiveCount"> Effective time-series points count. </param>
        /// <param name="startTime"> Start time of a variable. </param>
        /// <param name="endTime"> End time of a variable. </param>
        /// <param name="errors"> Error message when parse variable. </param>
        /// <returns> A new <see cref="Models.VariableState"/> instance for mocking. </returns>
        public static VariableState VariableState(string variable = null, float? filledNARatio = null, int? effectiveCount = null, DateTimeOffset? startTime = null, DateTimeOffset? endTime = null, IEnumerable<ErrorResponse> errors = null)
        {
            errors ??= new List<ErrorResponse>();

            return new VariableState(variable, filledNARatio, effectiveCount, startTime, endTime, errors?.ToList());
        }

        /// <summary> Initializes a new instance of Model. </summary>
        /// <param name="modelId"> Model identifier. </param>
        /// <param name="createdTime"> Date and time (UTC) when the model was created. </param>
        /// <param name="lastUpdatedTime"> Date and time (UTC) when the model was last updated. </param>
        /// <param name="modelInfo"> Training Status of the model. </param>
        /// <returns> A new <see cref="Models.Model"/> instance for mocking. </returns>
        public static Model Model(Guid modelId = default, DateTimeOffset createdTime = default, DateTimeOffset lastUpdatedTime = default, ModelInfo modelInfo = null)
        {
            return new Model(modelId, createdTime, lastUpdatedTime, modelInfo);
        }

        /// <summary> Initializes a new instance of DetectionResult. </summary>
        /// <param name="resultId"></param>
        /// <param name="summary"> Multivariate anomaly detection status. </param>
        /// <param name="results"> anomaly status of each timestamp. </param>
        /// <returns> A new <see cref="Models.DetectionResult"/> instance for mocking. </returns>
        public static DetectionResult DetectionResult(Guid resultId = default, DetectionResultSummary summary = null, IEnumerable<AnomalyState> results = null)
        {
            results ??= new List<AnomalyState>();

            return new DetectionResult(resultId, summary, results?.ToList());
        }

        /// <summary> Initializes a new instance of DetectionResultSummary. </summary>
        /// <param name="status"> Multivariate anomaly detection status. </param>
        /// <param name="errors"> Error message when creating or training model fails. </param>
        /// <param name="variableStates"></param>
        /// <param name="setupInfo"> Request when creating the model. </param>
        /// <returns> A new <see cref="Models.DetectionResultSummary"/> instance for mocking. </returns>
        public static DetectionResultSummary DetectionResultSummary(DetectionStatus status = default, IEnumerable<ErrorResponse> errors = null, IEnumerable<VariableState> variableStates = null, DetectionRequest setupInfo = null)
        {
            errors ??= new List<ErrorResponse>();
            variableStates ??= new List<VariableState>();

            return new DetectionResultSummary(status, errors?.ToList(), variableStates?.ToList(), setupInfo);
        }

        /// <summary> Initializes a new instance of AnomalyState. </summary>
        /// <param name="timestamp"> timestamp. </param>
        /// <param name="value"></param>
        /// <param name="errors"> Error message when inference this timestamp. </param>
        /// <returns> A new <see cref="Models.AnomalyState"/> instance for mocking. </returns>
        public static AnomalyState AnomalyState(DateTimeOffset timestamp = default, AnomalyValue value = null, IEnumerable<ErrorResponse> errors = null)
        {
            errors ??= new List<ErrorResponse>();

            return new AnomalyState(timestamp, value, errors?.ToList());
        }

        /// <summary> Initializes a new instance of AnomalyValue. </summary>
        /// <param name="contributors"> If current timestamp is an anomaly, contributors will show potential root cause for thus anomaly. Contributors can help us understand why current timestamp has been detected as an anomaly. </param>
        /// <param name="isAnomaly"> To indicate whether current timestamp is anomaly or not. </param>
        /// <param name="severity"> anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be. </param>
        /// <param name="score"> anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be, score measures global significance. </param>
        /// <returns> A new <see cref="Models.AnomalyValue"/> instance for mocking. </returns>
        public static AnomalyValue AnomalyValue(IEnumerable<AnomalyContributor> contributors = null, bool isAnomaly = default, float severity = default, float? score = null)
        {
            contributors ??= new List<AnomalyContributor>();

            return new AnomalyValue(contributors?.ToList(), isAnomaly, severity, score);
        }

        /// <summary> Initializes a new instance of AnomalyContributor. </summary>
        /// <param name="contributionScore"> The higher the contribution score is, the more likely the variable to be the root cause of a anomaly. </param>
        /// <param name="variable"> Variable name of a contributor. </param>
        /// <returns> A new <see cref="Models.AnomalyContributor"/> instance for mocking. </returns>
        public static AnomalyContributor AnomalyContributor(float? contributionScore = null, string variable = null)
        {
            return new AnomalyContributor(contributionScore, variable);
        }

        /// <summary> Initializes a new instance of ModelSnapshot. </summary>
        /// <param name="modelId"> Model identifier. </param>
        /// <param name="createdTime"> Date and time (UTC) when the model was created. </param>
        /// <param name="lastUpdatedTime"> Date and time (UTC) when the model was last updated. </param>
        /// <param name="status"> Model training status. </param>
        /// <param name="displayName"></param>
        /// <param name="variablesCount"> Count of variables. </param>
        /// <returns> A new <see cref="Models.ModelSnapshot"/> instance for mocking. </returns>
        public static ModelSnapshot ModelSnapshot(Guid modelId = default, DateTimeOffset createdTime = default, DateTimeOffset lastUpdatedTime = default, ModelStatus status = default, string displayName = null, int variablesCount = default)
        {
            return new ModelSnapshot(modelId, createdTime, lastUpdatedTime, status, displayName, variablesCount);
        }
    }
}


text:
import type { IExplorerExtensibilityGroup } from "core/Debug/debugLayer";

import { faBraille } from "@fortawesome/free-solid-svg-icons";
import { TreeItemLabelComponent } from "../treeItemLabelComponent";
import { ExtensionsComponent } from "../extensionsComponent";
import * as React from "react";
import type { IParticleSystem } from "core/Particles/IParticleSystem";

interface IParticleSystemTreeItemComponentProps {
    system: IParticleSystem;
    extensibilityGroups?: IExplorerExtensibilityGroup[];
    onClick: () => void;
}

export class ParticleSystemTreeItemComponent extends React.Component<IParticleSystemTreeItemComponentProps> {
    constructor(props: IParticleSystemTreeItemComponentProps) {
        super(props);
    }

    render() {
        return (
            <div className="particleSystemTools">
                <TreeItemLabelComponent label={this.props.system.name || "Particle system"} onClick={() => this.props.onClick()} icon={faBraille} color="crimson" />
                {<ExtensionsComponent target={this.props.system} extensibilityGroups={this.props.extensibilityGroups} />}
            </div>
        );
    }
}


text:
/*
 * 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.
 */

angular.module('zeppelinWebApp').controller('NotebookCtrl', NotebookCtrl);

NotebookCtrl.$inject = [
  '$scope',
  '$route',
  '$routeParams',
  '$location',
  '$rootScope',
  '$http',
  'websocketMsgSrv',
  'baseUrlSrv',
  '$timeout',
  'saveAsService',
  'ngToast',
  'noteActionSrv',
  'noteVarShareService',
  'TRASH_FOLDER_ID'
];

function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
                      $http, websocketMsgSrv, baseUrlSrv, $timeout, saveAsService,
                      ngToast, noteActionSrv, noteVarShareService, TRASH_FOLDER_ID) {

  ngToast.dismiss();

  $scope.note = null;
  $scope.moment = moment;
  $scope.editorToggled = false;
  $scope.tableToggled = false;
  $scope.viewOnly = false;
  $scope.showSetting = false;
  $scope.looknfeelOption = ['default', 'simple', 'report'];
  $scope.cronOption = [
    {name: 'None', value: undefined},
    {name: '1m', value: '0 0/1 * * * ?'},
    {name: '5m', value: '0 0/5 * * * ?'},
    {name: '1h', value: '0 0 0/1 * * ?'},
    {name: '3h', value: '0 0 0/3 * * ?'},
    {name: '6h', value: '0 0 0/6 * * ?'},
    {name: '12h', value: '0 0 0/12 * * ?'},
    {name: '1d', value: '0 0 0 * * ?'}
  ];

  $scope.interpreterSettings = [];
  $scope.interpreterBindings = [];
  $scope.isNoteDirty = null;
  $scope.saveTimer = null;

  var connectedOnce = false;
  var isRevisionPath = function(path) {
    var pattern = new RegExp('^.*\/notebook\/[a-zA-Z0-9_]*\/revision\/[a-zA-Z0-9_]*');
    return pattern.test(path);
  };

  $scope.noteRevisions = [];
  $scope.currentRevision = 'Head';
  $scope.revisionView = isRevisionPath($location.path());

  $scope.$on('setConnectedStatus', function(event, param) {
    if (connectedOnce && param) {
      initNotebook();
    }
    connectedOnce = true;
  });

  $scope.getCronOptionNameFromValue = function(value) {
    if (!value) {
      return '';
    }

    for (var o in $scope.cronOption) {
      if ($scope.cronOption[o].value === value) {
        return $scope.cronOption[o].name;
      }
    }
    return value;
  };

  $scope.blockAnonUsers = function() {
    var zeppelinVersion = $rootScope.zeppelinVersion;
    var url = 'https://zeppelin.apache.org/docs/' + zeppelinVersion + '/security/notebook_authorization.html';
    var content = 'Only authenticated user can set the permission.' +
      '' +
      '' +
      '';
    BootstrapDialog.show({
      closable: false,
      closeByBackdrop: false,
      closeByKeyboard: false,
      title: 'No permission',
      message: content,
      buttons: [{
        label: 'Close',
        action: function(dialog) {
          dialog.close();
        }
      }]
    });
  };

  /** Init the new controller */
  var initNotebook = function() {
    noteVarShareService.clear();
    if ($routeParams.revisionId) {
      websocketMsgSrv.getNoteByRevision($routeParams.noteId, $routeParams.revisionId);
    } else {
      websocketMsgSrv.getNote($routeParams.noteId);
    }
    websocketMsgSrv.listRevisionHistory($routeParams.noteId);
    var currentRoute = $route.current;
    if (currentRoute) {
      setTimeout(
        function() {
          var routeParams = currentRoute.params;
          var $id = angular.element('#' + routeParams.paragraph + '_container');

          if ($id.length > 0) {
            // adjust for navbar
            var top = $id.offset().top - 103;
            angular.element('html, body').scrollTo({top: top, left: 0});
          }
        },
        1000
      );
    }
  };

  initNotebook();

  // force notebook reload on user change
  $scope.$on('setNoteMenu', function(event, note) {
    initNotebook();
  });

  $scope.focusParagraphOnClick = function(clickEvent) {
    if (!$scope.note) {
      return;
    }
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      var paragraphId = $scope.note.paragraphs[i].id;
      if (jQuery.contains(angular.element('#' + paragraphId + '_container')[0], clickEvent.target)) {
        $scope.$broadcast('focusParagraph', paragraphId, 0, true);
        break;
      }
    }
  };

  // register mouseevent handler for focus paragraph
  document.addEventListener('click', $scope.focusParagraphOnClick);

  $scope.keyboardShortcut = function(keyEvent) {
    // handle keyevent
    if (!$scope.viewOnly && !$scope.revisionView) {
      $scope.$broadcast('keyEvent', keyEvent);
    }
  };

  // register mouseevent handler for focus paragraph
  document.addEventListener('keydown', $scope.keyboardShortcut);

  $scope.paragraphOnDoubleClick = function(paragraphId) {
    $scope.$broadcast('doubleClickParagraph', paragraphId);
  };

  // Move the note to trash and go back to the main page
  $scope.moveNoteToTrash = function(noteId) {
    noteActionSrv.moveNoteToTrash(noteId, true);
  };

  // Remove the note permanently if it's in the trash
  $scope.removeNote = function(noteId) {
    noteActionSrv.removeNote(noteId, true);
  };

  $scope.isTrash = function(note) {
    return note ? note.name.split('/')[0] === TRASH_FOLDER_ID : false;
  };

  //Export notebook
  $scope.exportNote = function() {
    var jsonContent = JSON.stringify($scope.note);
    saveAsService.saveAs(jsonContent, $scope.note.name, 'json');
  };

  //Clone note
  $scope.cloneNote = function(noteId) {
    BootstrapDialog.confirm({
      closable: true,
      title: '',
      message: 'Do you want to clone this note?',
      callback: function(result) {
        if (result) {
          websocketMsgSrv.cloneNote(noteId);
          $location.path('/');
        }
      }
    });
  };

  // checkpoint/commit notebook
  $scope.checkpointNote = function(commitMessage) {
    BootstrapDialog.confirm({
      closable: true,
      title: '',
      message: 'Commit note to current repository?',
      callback: function(result) {
        if (result) {
          websocketMsgSrv.checkpointNote($routeParams.noteId, commitMessage);
        }
      }
    });
    document.getElementById('note.checkpoint.message').value = '';
  };

  // set notebook head to given revision
  $scope.setNoteRevision = function() {
    BootstrapDialog.confirm({
      closable: true,
      title: '',
      message: 'Set notebook head to current revision?',
      callback: function(result) {
        if (result) {
          websocketMsgSrv.setNoteRevision($routeParams.noteId, $routeParams.revisionId);
        }
      }
    });
  };

  $scope.$on('listRevisionHistory', function(event, data) {
    console.log('received list of revisions %o', data);
    $scope.noteRevisions = data.revisionList;
    $scope.noteRevisions.splice(0, 0, {
      id: 'Head',
      message: 'Head'
    });
    if ($routeParams.revisionId) {
      var index = _.findIndex($scope.noteRevisions, {'id': $routeParams.revisionId});
      if (index > -1) {
        $scope.currentRevision = $scope.noteRevisions[index].message;
      }
    }
  });

  $scope.$on('noteRevision', function(event, data) {
    console.log('received note revision %o', data);
    if (data.note) {
      $scope.note = data.note;
      initializeLookAndFeel();
    } else {
      $location.path('/');
    }
  });

  $scope.$on('setNoteRevisionResult', function(event, data) {
    console.log('received set note revision result %o', data);
    if (data.status) {
      $location.path('/notebook/' + $routeParams.noteId);
    }
  });

  $scope.visitRevision = function(revision) {
    if (revision.id) {
      if (revision.id === 'Head') {
        $location.path('/notebook/' + $routeParams.noteId);
      } else {
        $location.path('/notebook/' + $routeParams.noteId + '/revision/' + revision.id);
      }
    } else {
      ngToast.danger({content: 'There is a problem with this Revision',
        verticalPosition: 'top', dismissOnTimeout: false});
    }
  };

  $scope.runAllParagraphs = function(noteId) {
    BootstrapDialog.confirm({
      closable: true,
      title: '',
      message: 'Run all paragraphs?',
      callback: function(result) {
        if (result) {
          const paragraphs = $scope.note.paragraphs.map(p => {
            return {
              id: p.id,
              title: p.title,
              paragraph: p.text,
              config: p.config,
              params: p.settings.params
            };
          });
          websocketMsgSrv.runAllParagraphs(noteId, paragraphs);
        }
      }
    });
  };

  $scope.saveNote = function() {
    if ($scope.note && $scope.note.paragraphs) {
      _.forEach($scope.note.paragraphs, function(par) {
        angular
          .element('#' + par.id + '_paragraphColumn_main')
          .scope()
          .saveParagraph(par);
      });
      $scope.isNoteDirty = null;
    }
  };

  $scope.clearAllParagraphOutput = function(noteId) {
    noteActionSrv.clearAllParagraphOutput(noteId);
  };

  $scope.toggleAllEditor = function() {
    if ($scope.editorToggled) {
      $scope.$broadcast('openEditor');
    } else {
      $scope.$broadcast('closeEditor');
    }
    $scope.editorToggled = !$scope.editorToggled;
  };

  $scope.showAllEditor = function() {
    $scope.$broadcast('openEditor');
  };

  $scope.hideAllEditor = function() {
    $scope.$broadcast('closeEditor');
  };

  $scope.toggleAllTable = function() {
    if ($scope.tableToggled) {
      $scope.$broadcast('openTable');
    } else {
      $scope.$broadcast('closeTable');
    }
    $scope.tableToggled = !$scope.tableToggled;
  };

  $scope.showAllTable = function() {
    $scope.$broadcast('openTable');
  };

  $scope.hideAllTable = function() {
    $scope.$broadcast('closeTable');
  };

  $scope.isNoteRunning = function() {
    if (!$scope.note) { return false; }
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      const status = $scope.note.paragraphs[i].status;
      if (status === 'PENDING' || status === 'RUNNING') {
        return true;
      }
    }
    return false;
  };

  $scope.killSaveTimer = function() {
    if ($scope.saveTimer) {
      $timeout.cancel($scope.saveTimer);
      $scope.saveTimer = null;
    }
  };

  $scope.startSaveTimer = function() {
    $scope.killSaveTimer();
    $scope.isNoteDirty = true;
    //console.log('startSaveTimer called ' + $scope.note.id);
    $scope.saveTimer = $timeout(function() {
      $scope.saveNote();
    }, 10000);
  };

  angular.element(window).on('beforeunload', function(e) {
    $scope.killSaveTimer();
    $scope.saveNote();
  });

  $scope.setLookAndFeel = function(looknfeel) {
    $scope.note.config.looknfeel = looknfeel;
    if ($scope.revisionView === true) {
      $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel);
    } else {
      $scope.setConfig();
    }
  };

  /** Set cron expression for this note **/
  $scope.setCronScheduler = function(cronExpr) {
    if (cronExpr) {
      if (!$scope.note.config.cronExecutingUser) {
        $scope.note.config.cronExecutingUser = $rootScope.ticket.principal;
      }
    } else {
      $scope.note.config.cronExecutingUser = '';
    }
    $scope.note.config.cron = cronExpr;
    $scope.setConfig();
  };

  /** Set the username of the user to be used to execute all notes in notebook **/
  $scope.setCronExecutingUser = function(cronExecutingUser) {
    $scope.note.config.cronExecutingUser = cronExecutingUser;
    $scope.setConfig();
  };

  /** Set release resource for this note **/
  $scope.setReleaseResource = function(value) {
    $scope.note.config.releaseresource = value;
    $scope.setConfig();
  };

  /** Update note config **/
  $scope.setConfig = function(config) {
    if (config) {
      $scope.note.config = config;
    }
    websocketMsgSrv.updateNote($scope.note.id, $scope.note.name, $scope.note.config);
  };

  /** Update the note name */
  $scope.updateNoteName = function(newName) {
    const trimmedNewName = newName.trim();
    if (trimmedNewName.length > 0 && $scope.note.name !== trimmedNewName) {
      $scope.note.name = trimmedNewName;
      websocketMsgSrv.renameNote($scope.note.id, $scope.note.name);
    }
  };

  var initializeLookAndFeel = function() {
    if (!$scope.note.config.looknfeel) {
      $scope.note.config.looknfeel = 'default';
    } else {
      $scope.viewOnly = $scope.note.config.looknfeel === 'report' ? true : false;
    }

    if ($scope.note.paragraphs && $scope.note.paragraphs[0]) {
      $scope.note.paragraphs[0].focus = true;
    }
    $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel);
  };

  var cleanParagraphExcept = function(paragraphId, note) {
    var noteCopy = {};
    noteCopy.id = note.id;
    noteCopy.name = note.name;
    noteCopy.config = note.config;
    noteCopy.info = note.info;
    noteCopy.paragraphs = [];
    for (var i = 0; i < note.paragraphs.length; i++) {
      if (note.paragraphs[i].id === paragraphId) {
        noteCopy.paragraphs[0] = note.paragraphs[i];
        if (!noteCopy.paragraphs[0].config) {
          noteCopy.paragraphs[0].config = {};
        }
        noteCopy.paragraphs[0].config.editorHide = true;
        noteCopy.paragraphs[0].config.tableHide = false;
        break;
      }
    }
    return noteCopy;
  };

  var addPara = function(paragraph, index) {
    $scope.note.paragraphs.splice(index, 0, paragraph);
    _.each($scope.note.paragraphs, function(para) {
      if (para.id === paragraph.id) {
        para.focus = true;
        $scope.$broadcast('focusParagraph', para.id, 0, false);
      }
    });
  };

  var removePara = function(paragraphId) {
    var removeIdx;
    _.each($scope.note.paragraphs, function(para, idx) {
      if (para.id === paragraphId) {
        removeIdx = idx;
      }
    });
    return $scope.note.paragraphs.splice(removeIdx, 1);
  };

  $scope.$on('addParagraph', function(event, paragraph, index) {
    if ($scope.paragraphUrl) {
      return;
    }
    addPara(paragraph, index);
  });

  $scope.$on('removeParagraph', function(event, paragraphId) {
    if ($scope.paragraphUrl) {
      return;
    }
    removePara(paragraphId);
  });

  $scope.$on('moveParagraph', function(event, paragraphId, newIdx) {
    var removedPara = removePara(paragraphId);
    if (removedPara && removedPara.length === 1) {
      addPara(removedPara[0], newIdx);
    }
  });

  $scope.$on('updateNote', function(event, name, config, info) {
    /** update Note name */
    if (name !== $scope.note.name) {
      console.log('change note name to : %o', $scope.note.name);
      $scope.note.name = name;
    }
    $scope.note.config = config;
    $scope.note.info = info;
    initializeLookAndFeel();
  });

  var getInterpreterBindings = function() {
    websocketMsgSrv.getInterpreterBindings($scope.note.id);
  };

  $scope.$on('interpreterBindings', function(event, data) {
    $scope.interpreterBindings = data.interpreterBindings;
    $scope.interpreterBindingsOrig = angular.copy($scope.interpreterBindings); // to check dirty

    var selected = false;
    var key;
    var setting;

    for (key in $scope.interpreterBindings) {
      setting = $scope.interpreterBindings[key];
      if (setting.selected) {
        selected = true;
        break;
      }
    }

    if (!selected) {
      // make default selection
      var selectedIntp = {};
      for (key in $scope.interpreterBindings) {
        setting = $scope.interpreterBindings[key];
        if (!selectedIntp[setting.name]) {
          setting.selected = true;
          selectedIntp[setting.name] = true;
        }
      }
      $scope.showSetting = true;
    }
  });

  $scope.interpreterSelectionListeners = {
    accept: function(sourceItemHandleScope, destSortableScope) {return true;},
    itemMoved: function(event) {},
    orderChanged: function(event) {}
  };

  $scope.openSetting = function() {
    $scope.showSetting = true;
    getInterpreterBindings();
  };

  $scope.closeSetting = function() {
    if (isSettingDirty()) {
      BootstrapDialog.confirm({
        closable: true,
        title: '',
        message: 'Interpreter setting changes will be discarded.',
        callback: function(result) {
          if (result) {
            $scope.$apply(function() {
              $scope.showSetting = false;
            });
          }
        }
      });
    } else {
      $scope.showSetting = false;
    }
  };

  $scope.saveSetting = function() {
    var selectedSettingIds = [];
    for (var no in $scope.interpreterBindings) {
      var setting = $scope.interpreterBindings[no];
      if (setting.selected) {
        selectedSettingIds.push(setting.id);
      }
    }
    websocketMsgSrv.saveInterpreterBindings($scope.note.id, selectedSettingIds);
    console.log('Interpreter bindings %o saved', selectedSettingIds);

    _.forEach($scope.note.paragraphs, function(n, key) {
      var regExp = /^\s*%/g;
      if (n.text && !regExp.exec(n.text)) {
        $scope.$broadcast('saveInterpreterBindings', n.id);
      }
    });

    $scope.showSetting = false;
  };

  $scope.toggleSetting = function() {
    if ($scope.showSetting) {
      $scope.closeSetting();
    } else {
      $scope.openSetting();
      $scope.closePermissions();
    }
  };

  var getPermissions = function(callback) {
    $http.get(baseUrlSrv.getRestApiBase() + '/notebook/' + $scope.note.id + '/permissions').
    success(function(data, status, headers, config) {
      $scope.permissions = data.body;
      $scope.permissionsOrig = angular.copy($scope.permissions); // to check dirty

      var selectJson = {
        tokenSeparators: [',', ' '],
        ajax: {
          url: function(params) {
            if (!params.term) {
              return false;
            }
            return baseUrlSrv.getRestApiBase() + '/security/userlist/' + params.term;
          },
          delay: 250,
          processResults: function(data, params) {
            var results = [];

            if (data.body.users.length !== 0) {
              var users = [];
              for (var len = 0; len < data.body.users.length; len++) {
                users.push({
                  'id': data.body.users[len],
                  'text': data.body.users[len]
                });
              }
              results.push({
                'text': 'Users :',
                'children': users
              });
            }
            if (data.body.roles.length !== 0) {
              var roles = [];
              for (var len = 0; len < data.body.roles.length; len++) {
                roles.push({
                  'id': data.body.roles[len],
                  'text': data.body.roles[len]
                });
              }
              results.push({
                'text': 'Roles :',
                'children': roles
              });
            }
            return {
              results: results,
              pagination: {
                more: false
              }
            };
          },
          cache: false
        },
        width: ' ',
        tags: true,
        minimumInputLength: 3
      };

      $scope.setIamOwner();
      angular.element('#selectOwners').select2(selectJson);
      angular.element('#selectReaders').select2(selectJson);
      angular.element('#selectWriters').select2(selectJson);
      if (callback) {
        callback();
      }
    }).
    error(function(data, status, headers, config) {
      if (status !== 0) {
        console.log('Error %o %o', status, data.message);
      }
    });
  };

  $scope.openPermissions = function() {
    $scope.showPermissions = true;
    getPermissions();
  };

  $scope.closePermissions = function() {
    if (isPermissionsDirty()) {
      BootstrapDialog.confirm({
        closable: true,
        title: '',
        message: 'Changes will be discarded.',
        callback: function(result) {
          if (result) {
            $scope.$apply(function() {
              $scope.showPermissions = false;
            });
          }
        }
      });
    } else {
      $scope.showPermissions = false;
    }
  };

  function convertPermissionsToArray() {
    $scope.permissions.owners = angular.element('#selectOwners').val();
    $scope.permissions.readers = angular.element('#selectReaders').val();
    $scope.permissions.writers = angular.element('#selectWriters').val();
  }

  $scope.restartInterpreter = function(interpeter) {
    var thisConfirm = BootstrapDialog.confirm({
      closable: false,
      closeByBackdrop: false,
      closeByKeyboard: false,
      title: '',
      message: 'Do you want to restart ' + interpeter.name + ' interpreter?',
      callback: function(result) {
        if (result) {
          var payload  = {
            'noteId': $scope.note.id
          };

          thisConfirm.$modalFooter.find('button').addClass('disabled');
          thisConfirm.$modalFooter.find('button:contains("OK")')
            .html(' Saving Setting');

          $http.put(baseUrlSrv.getRestApiBase() + '/interpreter/setting/restart/' + interpeter.id, payload)
            .success(function(data, status, headers, config) {
              var index = _.findIndex($scope.interpreterSettings, {'id': interpeter.id});
              $scope.interpreterSettings[index] = data.body;
              thisConfirm.close();
            }).error(function(data, status, headers, config) {
            thisConfirm.close();
            console.log('Error %o %o', status, data.message);
            BootstrapDialog.show({
              title: 'Error restart interpreter.',
              message: data.message
            });
          });
          return false;
        }
      }
    });
  };

  $scope.savePermissions = function() {
    convertPermissionsToArray();
    $http.put(baseUrlSrv.getRestApiBase() + '/notebook/' + $scope.note.id + '/permissions',
      $scope.permissions, {withCredentials: true}).
    success(function(data, status, headers, config) {
      getPermissions(function() {
        console.log('Note permissions %o saved', $scope.permissions);
        BootstrapDialog.alert({
          closable: true,
          title: 'Permissions Saved Successfully!!!',
          message: 'Owners : ' + $scope.permissions.owners + '\n\n' + 'Readers : ' +
          $scope.permissions.readers + '\n\n' + 'Writers  : ' + $scope.permissions.writers
        });
        $scope.showPermissions = false;
      });
    }).
    error(function(data, status, headers, config) {
      console.log('Error %o %o', status, data.message);
      BootstrapDialog.show({
        closable: false,
        closeByBackdrop: false,
        closeByKeyboard: false,
        title: 'Insufficient privileges',
        message: data.message,
        buttons: [
          {
            label: 'Login',
            action: function(dialog) {
              dialog.close();
              angular.element('#loginModal').modal({
                show: 'true'
              });
            }
          },
          {
            label: 'Cancel',
            action: function(dialog) {
              dialog.close();
              $location.path('/');
            }
          }
        ]
      });
    });
  };

  $scope.togglePermissions = function() {
    var principal = $rootScope.ticket.principal;
    $scope.isAnonymous = principal === 'anonymous' ? true : false;
    if (!!principal && $scope.isAnonymous) {
      $scope.blockAnonUsers();
    } else {
      if ($scope.showPermissions) {
        $scope.closePermissions();
        angular.element('#selectOwners').select2({});
        angular.element('#selectReaders').select2({});
        angular.element('#selectWriters').select2({});
      } else {
        $scope.openPermissions();
        $scope.closeSetting();
      }
    }
  };

  $scope.setIamOwner = function() {
    if ($scope.permissions.owners.length > 0 &&
      _.indexOf($scope.permissions.owners, $rootScope.ticket.principal) < 0) {
      $scope.isOwner = false;
      return false;
    }
    $scope.isOwner = true;
    return true;
  };

  $scope.toggleNotePersonalizedMode = function() {
    var personalizedMode = $scope.note.config.personalizedMode;
    if ($scope.isOwner) {
      BootstrapDialog.confirm({
        closable: true,
        title: 'Setting the result display',
        message: function(dialog) {
          var modeText = $scope.note.config.personalizedMode === 'true' ? 'collaborate' : 'personalize';
          return 'Do you want to ' + modeText + ' your analysis?';
        },
        callback: function(result) {
          if (result) {
            if ($scope.note.config.personalizedMode === undefined) {
              $scope.note.config.personalizedMode = 'false';
            }
            $scope.note.config.personalizedMode = personalizedMode === 'true' ?  'false' : 'true';
            websocketMsgSrv.updatePersonalizedMode($scope.note.id, $scope.note.config.personalizedMode);
          }
        }
      });
    }
  };

  var isSettingDirty = function() {
    if (angular.equals($scope.interpreterBindings, $scope.interpreterBindingsOrig)) {
      return false;
    } else {
      return true;
    }
  };

  var isPermissionsDirty = function() {
    if (angular.equals($scope.permissions, $scope.permissionsOrig)) {
      return false;
    } else {
      return true;
    }
  };

  angular.element(document).click(function() {
    angular.element('.ace_autocomplete').hide();
  });

  /*
   ** $scope.$on functions below
   */

  $scope.$on('setConnectedStatus', function(event, param) {
    if (connectedOnce && param) {
      initNotebook();
    }
    connectedOnce = true;
  });

  $scope.$on('moveParagraphUp', function(event, paragraph) {
    var newIndex = -1;
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      if ($scope.note.paragraphs[i].id === paragraph.id) {
        newIndex = i - 1;
        break;
      }
    }
    if (newIndex < 0 || newIndex >= $scope.note.paragraphs.length) {
      return;
    }
    // save dirtyText of moving paragraphs.
    var prevParagraph = $scope.note.paragraphs[newIndex];
    angular
      .element('#' + paragraph.id + '_paragraphColumn_main')
      .scope()
      .saveParagraph(paragraph);
    angular
      .element('#' + prevParagraph.id + '_paragraphColumn_main')
      .scope()
      .saveParagraph(prevParagraph);
    websocketMsgSrv.moveParagraph(paragraph.id, newIndex);
  });

  $scope.$on('moveParagraphDown', function(event, paragraph) {
    var newIndex = -1;
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      if ($scope.note.paragraphs[i].id === paragraph.id) {
        newIndex = i + 1;
        break;
      }
    }

    if (newIndex < 0 || newIndex >= $scope.note.paragraphs.length) {
      return;
    }
    // save dirtyText of moving paragraphs.
    var nextParagraph = $scope.note.paragraphs[newIndex];
    angular
      .element('#' + paragraph.id + '_paragraphColumn_main')
      .scope()
      .saveParagraph(paragraph);
    angular
      .element('#' + nextParagraph.id + '_paragraphColumn_main')
      .scope()
      .saveParagraph(nextParagraph);
    websocketMsgSrv.moveParagraph(paragraph.id, newIndex);
  });

  $scope.$on('moveFocusToPreviousParagraph', function(event, currentParagraphId) {
    var focus = false;
    for (var i = $scope.note.paragraphs.length - 1; i >= 0; i--) {
      if (focus === false) {
        if ($scope.note.paragraphs[i].id === currentParagraphId) {
          focus = true;
          continue;
        }
      } else {
        $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, -1);
        break;
      }
    }
  });

  $scope.$on('moveFocusToNextParagraph', function(event, currentParagraphId) {
    var focus = false;
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      if (focus === false) {
        if ($scope.note.paragraphs[i].id === currentParagraphId) {
          focus = true;
          continue;
        }
      } else {
        $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, 0);
        break;
      }
    }
  });

  $scope.$on('insertParagraph', function(event, paragraphId, position) {
    var newIndex = -1;
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      if ($scope.note.paragraphs[i].id === paragraphId) {
        //determine position of where to add new paragraph; default is below
        if (position === 'above') {
          newIndex = i;
        } else {
          newIndex = i + 1;
        }
        break;
      }
    }

    if (newIndex < 0 || newIndex > $scope.note.paragraphs.length) {
      return;
    }
    websocketMsgSrv.insertParagraph(newIndex);
  });

  $scope.$on('setNoteContent', function(event, note) {
    if (note === undefined) {
      $location.path('/');
    }

    $scope.note = note;

    $scope.paragraphUrl = $routeParams.paragraphId;
    $scope.asIframe = $routeParams.asIframe;
    if ($scope.paragraphUrl) {
      $scope.note = cleanParagraphExcept($scope.paragraphUrl, note);
      $scope.$broadcast('$unBindKeyEvent', $scope.$unBindKeyEvent);
      $rootScope.$broadcast('setIframe', $scope.asIframe);
    }

    initializeLookAndFeel();
    //open interpreter binding setting when there're none selected
    getInterpreterBindings();
    getPermissions();
    var isPersonalized = $scope.note.config.personalizedMode;
    isPersonalized = isPersonalized === undefined ?  'false' : isPersonalized;
    $scope.note.config.personalizedMode = isPersonalized;
  });

  $scope.$on('$destroy', function() {
    angular.element(window).off('beforeunload');
    $scope.killSaveTimer();
    $scope.saveNote();

    document.removeEventListener('click', $scope.focusParagraphOnClick);
    document.removeEventListener('keydown', $scope.keyboardShortcut);
  });

  $scope.$on('$unBindKeyEvent', function() {
    document.removeEventListener('click', $scope.focusParagraphOnClick);
    document.removeEventListener('keydown', $scope.keyboardShortcut);
  });

  angular.element(window).bind('resize', function() {
    const actionbarHeight = document.getElementById('actionbar').lastElementChild.clientHeight;
    angular.element(document.getElementById('content')).css('padding-top', actionbarHeight - 20);
  });
}


text:
author: Aniket
comments: true
date: 2014-06-24 17:02:50+00:00
layout: post
slug: why-learn-c
title: Why Learn C
wordpress_id: 35
categories:
- Let us C !
tags:
- Aniket
- language elements
- LET US C
- Object Oriented Programming
- OOP
---

Why learn C ? Many of us believe that c is suppressed by languages likes c++ and java  So why bother to learn C today

Here are top 5 reasons to lean C today

  1. C++ , C# or Java use the principle of Object Oriented Programming (OOP) to organize the program . To use OOP one should have a good hold over the language elements of C and basic of programming skills. so, it makes sense to learn C first.![C](http://kboo.fm/sites/default/files/nodeimages/c2.png)

  2. Major part of operating system like Windows, Unix, Linux are still written in C because when it comes to Speed nothing beats C. Moreover when one extents his operating system to work with new devices one need to write driver programs. These programs are exclusively written in C.

  3. Mobile phones and smartphones have become part of ones life .Even device like microwave, oven, washing machine are getting smarter day by day .This smartness comes from microprocessor, an operating system and coding .Since microprocessor have very less memory . Therefore we need a programming language that runs fast but also need less memory to execute, no wonder this language is C.

  4. We all have played enough games to understand that games need to be fast enough to match our reaction . Let us consider a fighting game one of opponent is right in front of you and suddenly you triggers the bullet but it took a while to trigger it in-game and your opponent moves. To match the expectations of the player the game has to react fast to the user inputs. This is where C language scores over other languages. Many popular going framework (like direct x ) have been built using C.

  5. At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance, it is the preferred choice of the programmers


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Creates the database interface required for database interctions
 * and add it to GLOBALS.
 *
 * @package PhpMyAdmin-DBI
 */
if (! defined('PHPMYADMIN')) {
    exit;
}

require_once './libraries/DatabaseInterface.class.php';

$extension = null;
if (defined('TESTSUITE')) {
    /**
     * For testsuite we use dummy driver which can fake some queries.
     */
    include_once './libraries/dbi/DBIDummy.class.php';
    $extension = new PMA_DBI_Dummy();
} else {

    /**
     * check for requested extension
     */
    $extensionName = $GLOBALS['cfg']['Server']['extension'];
    if (! PMA_DatabaseInterface::checkDbExtension($extensionName)) {

        // if it fails try alternative extension ...
        // and display an error ...
        $docurl = PMA_Util::getDocuLink('faq', 'faqmysql');
        $doclink = sprintf(
            __('See %sour documentation%s for more information.'),
            '[a@' . $docurl  . '@documentation]',
            '[/a]'
        );

        /**
         * @todo add different messages for alternative extension
         * and complete fail (no alternative extension too)
         */
        PMA_warnMissingExtension(
            $extensionName,
            false,
            $doclink
        );

        if ($extensionName === 'mysql') {
            $alternativ_extension = 'mysqli';
        } else {
            $alternativ_extension = 'mysql';
        }

        if (! PMA_DatabaseInterface::checkDbExtension($alternativ_extension)) {
            // if alternative fails too ...
            PMA_warnMissingExtension(
                $extensionName,
                true,
                $doclink
            );
        }

        $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
        unset($alternativ_extension);
    }

    /**
     * Including The DBI Plugin
     */
    switch($GLOBALS['cfg']['Server']['extension']) {
    case 'mysql' :
        include_once './libraries/dbi/DBIMysql.class.php';
        $extension = new PMA_DBI_Mysql();
        break;
    case 'mysqli' :
        include_once './libraries/dbi/DBIMysqli.class.php';
        $extension = new PMA_DBI_Mysqli();
        break;
    case 'drizzle' :
        include_once './libraries/dbi/DBIDrizzle.class.php';
        $extension = new PMA_DBI_Drizzle();
        break;
    }
}
$GLOBALS['dbi'] = new PMA_DatabaseInterface($extension);
?>


text:
namespace quic {

QuicTransmissionInfo::QuicTransmissionInfo()
    : encryption_level(ENCRYPTION_INITIAL),
      bytes_sent(0),
      sent_time(QuicTime::Zero()),
      transmission_type(NOT_RETRANSMISSION),
      in_flight(false),
      state(OUTSTANDING),
      has_crypto_handshake(false),
      num_padding_bytes(0) {}

QuicTransmissionInfo::QuicTransmissionInfo(
    EncryptionLevel level,
    TransmissionType transmission_type,
    QuicTime sent_time,
    QuicPacketLength bytes_sent,
    bool has_crypto_handshake,
    int num_padding_bytes)
    : encryption_level(level),
      bytes_sent(bytes_sent),
      sent_time(sent_time),
      transmission_type(transmission_type),
      in_flight(false),
      state(OUTSTANDING),
      has_crypto_handshake(has_crypto_handshake),
      num_padding_bytes(num_padding_bytes) {}

QuicTransmissionInfo::QuicTransmissionInfo(const QuicTransmissionInfo& other) =
    default;

QuicTransmissionInfo::~QuicTransmissionInfo() {}

}  // namespace quic


text:
class ProjectFilterQuery
  FILTER_TODO = "to do".freeze
  FILTER_FLAGGED = "flagged".freeze
  FILTER_DONE = "done".freeze
  FILTERS = [FILTER_TODO, FILTER_FLAGGED, FILTER_DONE].freeze

  attr_reader :params

  def initialize(params, project)
    @params = params.slice(:title_search, :filter)
    @project = project
  end

  def current_filter
    params[:filter] || FILTER_TODO
  end

  def items
    items = @project
      .content_items
      .with_valid_ids
      .order(updated_at: :desc)

    if params[:title_search].present?
      items = items.matching_search(params[:title_search])
    end

    case current_filter
    when FILTER_TODO
      items = items
                .todo
                .reorder(id: :asc) # Retain the spreadsheet order
    when FILTER_FLAGGED
      items = items.flagged
    when FILTER_DONE
      items = items.done
    end

    items
  end
end


text:
layout: null
title: 2015
subtitle:
image: "img/timeline/log.jpg"
---

**World** (Dec)
 Launch of the Art & Tech watch group: [Carpe Noctem](http://list.CarpeNoctem.cc)

 **Singapore** (Nov-Dec)
 Visits of a few labs: [NUS HCI](http://nus-hci.org), [CUTE center](http://cutecenter.nus.edu.sg), and [Augmented Human Lab](http://ahlab.org)

 **World** (Oct)
 Featured in [Hack A Day](http://hackaday.com/2015/10/02/the-square-inch-project-challenges-your-layout-skills) and in the [Hackster](https://twitter.com/Hacksterio/status/650097039963914240) café

 **France** (Sept)
 Jury at the [Greenathon](http://www.makery.info/2015/09/22/le-vetement-connecte-se-met-au-green): wearable & ecology contest.

 **France** (Aug)
 Presenting [Cyclokino](https://www.hackster.io/cedric/cyclokino-bab5bf): our immersive / augmented reality bike system for autonous and mobile cinema at the [Douarnenez Festival](http://festival-douarnenez.com)

 **France** (Jul)
 eTextile Summer Camp [exhibition](http://etextile-summercamp.org/2015/etextile-cuvee-2015) + [Swatchbook](http://etextile-summercamp.org/swatch-exchange)

 **France** (Jun)
 Twiz experimentations at [Woot Devices](http://wootdevices.io) ([press](http://www.makery.info/2015/06/09/woot-devices-la-hackfete-des-micro-cartes-au-jardin-dalice))

 **France** (May)
 Presenting Twiz at the [Toulouse Hacker Space Festival](http://thsf.tetalab.org) ([program](http://mixart-myrys.org/programmation2/20-15/mai/thsf-2015/thsf-2015-programmation/thsf-2015-conferences) - [press](http://www.liberation.fr/futurs/2015/05/15/a-toulouse-les-hackers-surfent-sur-le-canal-du-midi_1310194))

 **France** (Apr)
 Jury for the [Robotic & Embedded Systems](https://rose.telecom-paristech.fr/2015) program at [Telecom ParisTech](https://telecom-paristech.fr)

 **Indonesia** (Apr)
 Visit of the [LifePatch](http://lifepatch.org) bio+arts hackerspace

 **Singapore** (Apr)
 InterArtivity presentation at [Creative Coding](https://engineers.sg/video/cedric-honnet-creative-coding-meetup-three-of-pentacles--24) meetup

 **Singapore** (Mar)
 Presenting Twiz at the [Free & Open Source Systems Asia](http://2015.fossasia.org) conference ([video](http://youtu.be/hp0cTFngoGc))

 **Singapore** (Mar)
 [Augmented Human](http://www.augmented-human.com/home/augmented-human-international-conference-2015) Conference ([report](https://docs.google.com/document/d/1IpTPuJCg8RQ1IVpDc9gy1joIR_2kZXVgFCAlhreI9Zg))

 **Singapore** (Feb)
 Interview on [WeBuild](http://live.webuild.sg/030-cedric-honnet) radio

 **Singapore** (Feb)
 Growell's [Squat & Grow](https://www.facebook.com/events/774736155927468) workshops

 **Singapore** (Jan)
 Presenting Twiz at [NUS hackerspace](http://nushackers.org/2015/01/friday-hacks-86-Jan-30/#twi-a-bluetooth-low-energy-wireless-motion-sensor-by-cedric-honnet)

 **Hong Kong** (Jan)
 Presenting Twiz at [Polytechnic University](https://twitter.com/CedHon/status/554957651520413696)

 **Taiwan** (Jan)
 [PCB workshop](https://upverter.com/honnet/4406dca96d6bb186/Arduino-Shield-TaipeiHack) at [Taipei Hackerspace](https://taipeihack.org)


text:
package com.scriptedpapers.androidcortanaanimation;

import android.graphics.Canvas;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by mahes on 12/8/15.
 */
public interface CortanaInterface {

    void initializePaint();
    void calculateDimensions(int diameter, int centerX, int centerY);
    void onDraw(Canvas canvas);
    void startAnimation(final View view);
    void stopAnimation();

}


text:
<link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/public/stylesheets/email.css" media="screen" rel="stylesheet" type="text/css" />


text:
package org.broadinstitute.hellbender.tools.copynumber.utils.annotatedinterval;

import com.google.common.collect.ImmutableSortedMap;
import org.broadinstitute.hellbender.GATKBaseTest;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.collections.Sets;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public final class AnnotatedIntervalUnitTest extends GATKBaseTest {
    private static final File TEST_FILE = new File(toolsTestDir,
            "copynumber/utils/annotatedinterval/annotated-interval-many-columns.seg");

    @Test
    public void basicTest() throws IOException {
        final Set<String> headersOfInterest = Sets.newHashSet(Arrays.asList("name", "learning_SAMPLE_0"));
        final List<AnnotatedInterval> annotatedIntervals =
                AnnotatedIntervalCollection.create(TEST_FILE.toPath(), headersOfInterest).getRecords();

        Assert.assertEquals(annotatedIntervals.size(), 15);
        Assert.assertTrue(annotatedIntervals.stream()
                .mapToInt(s -> s.getAnnotations().entrySet().size())
                .allMatch(i -> i == headersOfInterest.size()));
        Assert.assertTrue(annotatedIntervals.stream().allMatch(s -> s.getAnnotations().keySet().containsAll(headersOfInterest)));

        // Grab the first 15 and test values
        List<AnnotatedInterval> gtRegions = Arrays.asList(
                new AnnotatedInterval(new SimpleInterval("1", 30365, 30503), ImmutableSortedMap.of("name", "target_1_None", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 69088, 70010), ImmutableSortedMap.of("name", "target_2_None", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 367656, 368599), ImmutableSortedMap.of("name", "target_3_None", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 621093, 622036), ImmutableSortedMap.of("name", "target_4_None", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 861319, 861395), ImmutableSortedMap.of("name", "target_5_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 865532, 865718), ImmutableSortedMap.of("name", "target_6_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 866416, 866471), ImmutableSortedMap.of("name", "target_7_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 871149, 871278), ImmutableSortedMap.of("name", "target_8_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 874417, 874511), ImmutableSortedMap.of("name", "target_9_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 874652, 874842), ImmutableSortedMap.of("name", "target_10_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 876521, 876688), ImmutableSortedMap.of("name", "target_11_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 877513, 877633), ImmutableSortedMap.of("name", "target_12_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 877787, 877870), ImmutableSortedMap.of("name", "target_13_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 877936, 878440), ImmutableSortedMap.of("name", "target_14_SAMD11", "learning_SAMPLE_0", "2")),
                new AnnotatedInterval(new SimpleInterval("1", 878630, 878759), ImmutableSortedMap.of("name", "target_15_SAMD11", "learning_SAMPLE_0", "2"))
        );

        Assert.assertEquals(annotatedIntervals.subList(0, gtRegions.size()), gtRegions);
    }

    @Test
    public void basicTestWithAllColumnsFile() throws IOException {

        // If no columns of interest are given in a read call, the method will try to load all columns as "interesting".
        final List<AnnotatedInterval> annotatedIntervals =
                AnnotatedIntervalCollection.create(TEST_FILE.toPath(), null).getRecords();

        Assert.assertEquals(annotatedIntervals.size(), 15);
        Assert.assertTrue(annotatedIntervals.stream()
                .mapToInt(s -> s.getAnnotations().entrySet().size())
                .allMatch(i -> i == 101)); // The number of columns in the TEST_FILE (name, learning_SAMPLE_0...99
    }

    @Test(dataProvider = "equalsTests")
    public void testEquals(AnnotatedInterval test1, AnnotatedInterval test2, boolean gt) {
        Assert.assertEquals(test1.equals(test2), gt);
    }

    @DataProvider(name = "equalsTests")
    public Object [][] createEqualsTests() {

        return new Object[][] {
            {
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                true
            }, {
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar2")),
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                false
            }, {
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foobar1", "bar1")),
                false
            }, {
                new AnnotatedInterval( new SimpleInterval("1", 1000, 2000),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                false
            }, {
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar", "Foo1", "bar1")),
                new AnnotatedInterval( new SimpleInterval("1", 100, 200),
                        ImmutableSortedMap.of("Foo", "bar")),
                false
            }
        };
    }
}


text:
[![Hackage version](https://img.shields.io/hackage/v/hsverilog.svg?style=flat)](https://hackage.haskell.org/package/hsverilog)  [![Build Status](https://travis-ci.org/junjihashimoto/hsverilog.png?branch=master)](https://travis-ci.org/junjihashimoto/hsverilog) [![Coverage Status](https://coveralls.io/repos/junjihashimoto/hsverilog/badge.png)](https://coveralls.io/r/junjihashimoto/hsverilog)

## Getting started

Install this from Hackage.

    cabal update && cabal install hsverilog

## Usage

Syntax is similar to Verilog.
See tests/test.hs and following examples.

### counter circuit

```
circuit "counter" $ do
  clk <- input "clk" Bit
  rstn <- input "rstn" Bit
  _ <- output "dout" $ 7><0
  reg "dout" (7><0) [Posedge clk,Negedge rstn] $ \dout ->
    If (Not (S rstn)) 0 $
      If (Eq dout 7)
        0
        (dout + 1)
```


text:
<?php

namespace Identicon\Identity;

final class Block
{
    protected $isColored;

    public function __construct($isColored = false)
    {
        $this->isColored = $isColored;
    }

    public function isColored()
    {
        return $this->isColored;
    }

    public function __toString()
    {
        return $this->isColored() ? "#" : " ";
    }
}


text:
"use strict";

var config  = require('../../config/config.js');
var neo4j = require('neo4j');
var _ = require("lodash");

var db = new neo4j.GraphDatabase({
    url: 'http://localhost:7474',
    auth: config.neo4j
});

module.exports = function *() {

    var groups = yield function(callback) {
        var cypherObj = {
            "query": `MATCH (g:Group) RETURN g.name as name`,
            "lean": true
        }

        db.cypher(cypherObj, function(err, res) {
            if (err) {
                callback(false, []);
            }
            else {
                callback(false, res);
            }
        });
    }

    this.body = groups
}


text:
#include "berryServiceLocatorCreator.h"

#include "berryServiceLocator.h"
#include "services/berryIServiceFactory.h"
#include "services/berryIDisposable.h"

namespace berry {

SmartPointer<IServiceLocator>
ServiceLocatorCreator::CreateServiceLocator(
      IServiceLocator* parent,
      const IServiceFactory* factory,
      WeakPointer<IDisposable> owner)
{
  IServiceLocator::Pointer locator(new ServiceLocator(parent, factory, owner));
  return locator;
}

}


text:
package org.pikater.core.ontology.subtrees.task;

import java.util.Date;

import org.pikater.core.ontology.subtrees.datainstance.DataInstances;

import jade.content.Concept;

import java.util.LinkedList;
import java.util.List;

public class Evaluation implements Concept {

	private static final long serialVersionUID = 1319671908304254420L;

	private List<Eval> evaluations;
	private Date start;
	private String status;

	private String objectFilename;

	private List<DataInstances> labeledData = new LinkedList<DataInstances>(); // List of DataInstances

	private DataInstances dataTable;

	private byte[] object; // saved agent

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public DataInstances getDataTable() {
		return dataTable;
	}

	public void setDataTable(DataInstances dataTable) {
		this.dataTable = dataTable;
	}

	public List<DataInstances> getLabeledData() {
		return labeledData;
	}

	public void setLabeledData(List<DataInstances> labeledData) {
		this.labeledData = labeledData;
	}

	public String getObjectFilename() {
		return objectFilename;
	}

	public void setObjectFilename(String object_filename) {
		this.objectFilename = object_filename;
	}

	public byte[] getObject() {
		return object;
	}

	public void setObject(byte[] object) {
		this.object = object;
	}

	public List<Eval> getEvaluations() {
		return evaluations;
	}

	public void setEvaluations(List<Eval> evaluations) {
		this.evaluations = evaluations;
	}

	public Eval exportEvalByName(String evalName) {

		for (Eval evalI : getEvaluations()) {
			if (evalI.getName().equals(evalName)) {
				return evalI;
			}
		}

		return null;
	}

	public Date getStart() {
		return start;
	}

	public void setStart(Date start) {
		this.start = start;
	}

}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Color Blocks</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body id="color">
<script src="js/script.js"></script>
</body>
</html>


text:
package br.com.badrequest.insporte.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import br.com.badrequest.insporte.util.Util;

public class NetworkChangeReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if(Util.haveNetworkConnection(context)) {
			Intent serviceIntent = new Intent(context, br.com.badrequest.insporte.service.SyncUserDataService_.class);
			context.startService(serviceIntent);
//            if(!Util.isStatusPushIDSent(context) || Util.getRegistrationId(context).length() == 0) {
//                Intent serviceGCM = new Intent(context, br.com.badrequest.insporte.service.RegisterGCMService_.class);
//                context.startService(serviceGCM);
//            }
		}
	}

}