text:
describe('dc.scatterPlot', function() {
    var id, chart;
    var data, group, dimension;

    beforeEach(function () {
        data = crossfilter(loadDateFixture());
        dimension = data.dimension(function(d) { return [+d.value, +d.nvalue]; });
        group = dimension.group();

        id = 'scatter-plot';
        appendChartID(id);

        chart = dc.scatterPlot("#" + id);
        chart.dimension(dimension)
            .group(group)
            .width(500).height(180)
            .x(d3.scale.linear().domain([0, 70]))
            .transitionDuration(0);
    });

    describe('rendering the scatter plot', function () {
        beforeEach(function () {
            chart.render();
        });

        it('should create an svg', function () {
            expect(chart.svg().empty()).toBeFalsy();
        });

        it('should create the correct number of symbols', function () {
            expect(chart.group().all().length).toBe(chart.selectAll('path.symbol').size());
        });

        it('should correctly place the symbols', function () {
            expect(nthSymbol(4).attr("transform")).toMatchTranslate(264,131);
            expect(nthSymbol(5).attr("transform")).toMatchTranslate(264,75);
            expect(nthSymbol(8).attr("transform")).toMatchTranslate(396,131);
        });

        it('should generate a default color fill for symbols', function () {
            expect(nthSymbol(4).attr("fill")).toBe('#1f77b4');
            expect(nthSymbol(5).attr("fill")).toBe('#1f77b4');
            expect(nthSymbol(8).attr("fill")).toBe('#1f77b4');
        });

        describe('with a custom color', function () {
            beforeEach(function () {
                chart.colors("red").render();
            });

            it('should color the symbols to the provided color', function () {
                expect(nthSymbol(4).attr("fill")).toBe('red');
                expect(nthSymbol(5).attr("fill")).toBe('red');
                expect(nthSymbol(8).attr("fill")).toBe('red');
            });
        });

        function nthSymbol(i) {
            return d3.select(chart.selectAll('path.symbol')[0][i]);
        }

        describe('filtering the chart', function () {
            var otherDimension;

            beforeEach(function () {
                otherDimension = data.dimension(function(d) { return [+d.value, +d.nvalue]; });

                chart.filterAll();
                chart.filter([[22, -3], [44, 2]]);
            });

            it('should filter dimensions based on the same data', function () {
                expect(otherDimension.top(Infinity).length).toBe(3);
            });

            describe('when filtering with null', function () {
                beforeEach(function () {
                    chart.filter(null);
                });

                it('should remove all filtering from the dimensions based on the same data', function () {
                    expect(otherDimension.top(Infinity).length).toBe(10);
                });

            });
        });

        describe('brushing', function () {
            var otherDimension;

            beforeEach(function () {
                otherDimension = data.dimension(function(d) { return [+d.value, +d.nvalue]; });

                chart.brush().extent([[22, -3], [44, 2]]);
                chart.brush().on("brush")();
                chart.redraw();
            });

            it('should filter dimensions based on the same data', function () {
                jasmine.clock().tick(100);
                expect(otherDimension.top(Infinity).length).toBe(3);
            });

            it('should set the height of the brush to the height implied by the extent', function () {
                expect(chart.select("g.brush rect.extent").attr("height")).toBe('46');
            });

            it('should not add handles to the brush', function () {
                expect(chart.select(".resize path").empty()).toBeTruthy();
            });

            describe('highlighting', function () {
                var selectedPoints;

                beforeEach(function () {
                    selectedPoints = selectedSymbols();
                });

                it('should highlight the selected points', function () {
                    expect(selectedPoints.length).toBe(2);
                    expect(selectedPoints[0].key).toEqual([22, -2]);
                    expect(selectedPoints[1].key).toEqual([33, 1]);
                });

                it('should remove highlighting when the brush is removed from the selected points', function () {
                    chart.brush().extent([[22, 2], [22, -3]]);
                    chart.brush().on("brush")();
                    selectedPoints = selectedSymbols();
                    expect(selectedPoints.length).toBe(0);
                    chart.redraw();
                    selectedPoints = selectedSymbols();
                    expect(selectedPoints.length).toBe(0);
                });

                function selectedSymbols() {
                    function getData(symbols) {
                        return symbols[0].map(function (symbol) {
                            return d3.select(symbol).datum();
                        });
                    }
                    return getData(chart.selectAll('path.symbol').filter(function () {
                        var symbol = d3.select(this);
                        var highlightedSize = Math.pow(chart.highlightedSize(), 2);
                        var highlightedPath = d3.svg.symbol().size(highlightedSize)();
                        var result = comparePaths(symbol.attr("d"), highlightedPath);
                        return result.pass;
                    }));
                }
            });
        });
    });

    describe('legends', function () {
        var compositeChart, id;
        var subChart1, subChart2;
        var firstItem;

        beforeEach(function () {
            id = 'scatter-plot-composite';
            appendChartID(id);

            compositeChart = dc.compositeChart("#" + id);
            compositeChart
                .dimension(dimension)
                .x(d3.time.scale().domain([new Date(2012, 0, 1), new Date(2012, 11, 31)]))
                .transitionDuration(0)
                .legend(dc.legend())
                .compose([
                    subChart1 = dc.scatterPlot(compositeChart).colors('red').group(group, "Scatter 1"),
                    subChart2 = dc.scatterPlot(compositeChart).colors('blue').group(group, "Scatter 2")
                ]).render();

            firstItem = compositeChart.select('g.dc-legend g.dc-legend-item');
        });

        it('should provide a composite chart with corresponding legend data', function() {
            expect(compositeChart.legendables()).toEqual([
                {chart: subChart1, name: 'Scatter 1', color: 'red'},
                {chart: subChart2, name: 'Scatter 2', color: 'blue'}
            ]);
        });

        describe('hovering', function() {
            beforeEach(function() {
                firstItem.on("mouseover")(firstItem.datum());
            });

            describe('when a legend item is hovered over', function () {
                it('should highlight corresponding plot', function () {
                    nthChart(0).expectPlotSymbolsToHaveSize(chart.highlightedSize());

                });

                it('should fade out non-corresponding lines and areas', function () {
                    nthChart(1).expectPlotSymbolsToHaveClass("fadeout");
                });
            });

            describe('when a legend item is hovered out', function () {
                beforeEach(function () {
                    firstItem.on("mouseout")(firstItem.datum());
                });

                it('should remove highlighting from corresponding lines and areas', function () {
                    nthChart(0).expectPlotSymbolsToHaveSize(chart.symbolSize());
                });

                it('should fade in non-corresponding lines and areas', function () {
                    nthChart(1).expectPlotSymbolsNotToHaveClass("fadeout");
                });
            });
        });

        function nthChart(n) {
            var subChart = d3.select(compositeChart.selectAll("g.sub")[0][n]);

            subChart.expectPlotSymbolsToHaveClass = function(className) {
                subChart.selectAll("path.symbol").each(function () {
                    expect(d3.select(this).classed(className)).toBeTruthy();
                });
            };

            subChart.expectPlotSymbolsToHaveSize = function(size) {
                var highlightedSize = Math.pow(size, 2);
                var highlightedPath = d3.svg.symbol().size(highlightedSize)();
                subChart.selectAll("path.symbol").each(function () {
                    expect(d3.select(this).attr("d")).toMatchPath(highlightedPath);
                });
            };

            subChart.expectPlotSymbolsNotToHaveClass = function(className){
                subChart.selectAll("path.symbol").each(function () {
                    expect(d3.select(this).classed(className)).toBeFalsy();
                });
            };

            return subChart;
        }
    });
});


text:
package org.apache.trevni;

import java.util.Random;
import java.util.Arrays;

import org.junit.Assert;
import org.junit.Test;

public class TestInputBytes {

  private static final int SIZE = 1000;
  private static final int COUNT = 100;

  @Test
  public void testRandomReads() throws Exception {
    Random random = new Random(19820210);
    int length = random.nextInt(SIZE) + 1;
    byte[] data = new byte[length];
    random.nextBytes(data);

    Input in = new InputBytes(data);

    for (int i = 0; i < COUNT; i++) {
      int p = random.nextInt(length);
      int l = Math.min(random.nextInt(SIZE / 10), length - p);
      byte[] buffer = new byte[l];
      in.read(p, buffer, 0, l);
      Assert.assertArrayEquals(Arrays.copyOfRange(data, p, p + l), buffer);
    }
    in.close();
  }
}

redpajama_set_name: RedPajamaGithub


text:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var webpack = require('webpack');

module.exports = {
	entry: './src/js/script.js',
	output: {
		path: './public/js',
		filename: 'app.bundle.js'
	},
  devServer: {
    contentBase: path.join(__dirname, 'public'),
    colors: true,
    historyApiFallback: true,
    inline: true
  },
  plugins: [
      new HtmlWebpackPlugin({
        filename: '../index.html',
        template: 'src/index.html'
      }),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity),

      // expose the environment to the front end
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('production')
        }
      }),
  ]
}


text:
<?php

declare(strict_types=1);

namespace Valkyrja\Routing\Enums;

use Valkyrja\Support\Enum\Enum;

/**
 * Enum AnnotationName.
 *
 * @author Melech Mizrachi
 */
final class AnnotationName extends Enum
{
    public const ROUTE                            = 'Route';
    public const ROUTE_ANY                        = 'Route\\Any';
    public const ROUTE_GET                        = 'Route\\Get';
    public const ROUTE_POST                       = 'Route\\Post';
    public const ROUTE_HEAD                       = 'Route\\Head';
    public const ROUTE_PATCH                      = 'Route\\Patch';
    public const ROUTE_PUT                        = 'Route\\Put';
    public const ROUTE_OPTIONS                    = 'Route\\Options';
    public const ROUTE_TRACE                      = 'Route\\Trace';
    public const ROUTE_CONNECT                    = 'Route\\Connect';
    public const ROUTE_DELETE                     = 'Route\\Delete';
    public const ROUTE_REDIRECT                   = 'Route\\Redirect';
    public const ROUTE_REDIRECT_ANY               = 'Route\\Redirect\\Any';
    public const ROUTE_REDIRECT_GET               = 'Route\\Redirect\\Get';
    public const ROUTE_REDIRECT_POST              = 'Route\\Redirect\\Post';
    public const ROUTE_REDIRECT_HEAD              = 'Route\\Redirect\\Head';
    public const ROUTE_REDIRECT_PATCH             = 'Route\\Redirect\\Patch';
    public const ROUTE_REDIRECT_PUT               = 'Route\\Redirect\\Put';
    public const ROUTE_REDIRECT_OPTIONS           = 'Route\\Redirect\\Options';
    public const ROUTE_REDIRECT_TRACE             = 'Route\\Redirect\\Trace';
    public const ROUTE_REDIRECT_CONNECT           = 'Route\\Redirect\\Connect';
    public const ROUTE_REDIRECT_DELETE            = 'Route\\Redirect\\Delete';
    public const ROUTE_REDIRECT_PERMANENT         = 'Route\\Redirect\\Permanent';
    public const ROUTE_REDIRECT_PERMANENT_ANY     = 'Route\\Redirect\\Permanent\\Any';
    public const ROUTE_REDIRECT_PERMANENT_GET     = 'Route\\Redirect\\Permanent\\Get';
    public const ROUTE_REDIRECT_PERMANENT_POST    = 'Route\\Redirect\\Permanent\\Post';
    public const ROUTE_REDIRECT_PERMANENT_HEAD    = 'Route\\Redirect\\Permanent\\Head';
    public const ROUTE_REDIRECT_PERMANENT_PATCH   = 'Route\\Redirect\\Permanent\\Patch';
    public const ROUTE_REDIRECT_PERMANENT_PUT     = 'Route\\Redirect\\Permanent\\Put';
    public const ROUTE_REDIRECT_PERMANENT_OPTIONS = 'Route\\Redirect\\Permanent\\Options';
    public const ROUTE_REDIRECT_PERMANENT_TRACE   = 'Route\\Redirect\\Permanent\\Trace';
    public const ROUTE_REDIRECT_PERMANENT_CONNECT = 'Route\\Redirect\\Permanent\\Connect';
    public const ROUTE_REDIRECT_PERMANENT_DELETE  = 'Route\\Redirect\\Permanent\\Delete';
    public const ROUTE_SECURE                     = 'Route\\Secure';
    public const ROUTE_SECURE_ANY                 = 'Route\\Secure\\Any';
    public const ROUTE_SECURE_GET                 = 'Route\\Secure\\Get';
    public const ROUTE_SECURE_POST                = 'Route\\Secure\\Post';
    public const ROUTE_SECURE_HEAD                = 'Route\\Secure\\Head';
    public const ROUTE_SECURE_PATCH               = 'Route\\Secure\\Patch';
    public const ROUTE_SECURE_PUT                 = 'Route\\Secure\\Put';
    public const ROUTE_SECURE_OPTIONS             = 'Route\\Secure\\Options';
    public const ROUTE_SECURE_TRACE               = 'Route\\Secure\\Trace';
    public const ROUTE_SECURE_CONNECT             = 'Route\\Secure\\Connect';
    public const ROUTE_SECURE_DELETE              = 'Route\\Secure\\Delete';
}


text:
from base64 import b64encode as b64e
import unittest

from airflow.contrib.operators.pubsub_operator import PubSubPublishOperator
from airflow.contrib.operators.pubsub_operator import PubSubTopicCreateOperator

try:
    from unittest import mock
except ImportError:
    try:
        import mock
    except ImportError:
        mock = None

TASK_ID = 'test-task-id'
TEST_PROJECT = 'test-project'
TEST_TOPIC = 'test-topic'
TEST_MESSAGES = [
    {
        'data': b64e('Hello, World!'),
        'attributes': {'type': 'greeting'}
    },
    {'data': b64e('Knock, knock')},
    {'attributes': {'foo': ''}}]

class PubSubTopicCreateOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.pubsub_operator.PubSubHook')
    def test_failifexists(self, mock_hook):
        operator = PubSubTopicCreateOperator(task_id=TASK_ID,
                                             project=TEST_PROJECT,
                                             topic=TEST_TOPIC,
                                             fail_if_exists=True)

        operator.execute(None)
        mock_hook.return_value.create_topic.assert_called_once_with(
            TEST_PROJECT, TEST_TOPIC, fail_if_exists=True)

    @mock.patch('airflow.contrib.operators.pubsub_operator.PubSubHook')
    def test_succeedifexists(self, mock_hook):
        operator = PubSubTopicCreateOperator(task_id=TASK_ID,
                                             project=TEST_PROJECT,
                                             topic=TEST_TOPIC,
                                             fail_if_exists=False)

        operator.execute(None)
        mock_hook.return_value.create_topic.assert_called_once_with(
            TEST_PROJECT, TEST_TOPIC, fail_if_exists=False)

class PubSubPublishOperatorTest(unittest.TestCase):

    @mock.patch('airflow.contrib.operators.pubsub_operator.PubSubHook')
    def test_publish(self, mock_hook):
        operator = PubSubPublishOperator(task_id=TASK_ID,
                                         project=TEST_PROJECT,
                                         topic=TEST_TOPIC,
                                         messages=TEST_MESSAGES)

        operator.execute(None)
        mock_hook.return_value.publish.assert_called_once_with(
            TEST_PROJECT, TEST_TOPIC, TEST_MESSAGES)


text:
class Singleton(type):
    """A metaclass for creating Singletons (ta-da).
    """

    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            instance = super().__call__(*args, **kwargs)
            cls._instance = instance
        return cls._instance


text:
package org.rapidpm.event.opench2015.proxy.model;

/**
 * Created by Sven Ruppert on 22.09.2014.
 */
public interface Service {
  String work(String txt);
}


text:
var suite = new core.testrunner.Suite("Events", null, function() {
  core.Main.clearNamespace("events.Simple1");
  core.Main.clearNamespace("events.Simple2");
  core.Main.clearNamespace("events.Simple3");
  core.Main.clearNamespace("events.Simple4");
  core.Main.clearNamespace("events.Simple5");
  core.Main.clearNamespace("events.Simple6");
  core.Main.clearNamespace("events.Simple7");
  core.Main.clearNamespace("events.Simple8");
  core.Main.clearNamespace("events.Simple9");
});

suite.test("Basic", function()
{
  var test = this;

  core.Class("events.Simple1",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testBasic : function()
      {
        var eventExecuted = 0;
        this.addListener("simple1", function() {
          eventExecuted++;
        });

        this.fireEvent("simple1");
        test.isEqual(eventExecuted, 1);

        this.fireEvent("simple1");
        this.fireEvent("simple1");
        test.isEqual(eventExecuted, 3);
      }
    }
  });

  new events.Simple1().testBasic();
});

suite.test("Context", function()
{
  var test = this;

  core.Class("events.Simple2",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testContext : function()
      {
        var contextObject = {valid : 1};

        this.addListener("simple2", function() {
          test.isEqual(this.valid, 1);
        }, contextObject);

        this.fireEvent("simple2");
      }
    }
  });

  new events.Simple2().testContext();
});

suite.test("Deconnect", function()
{
  var test = this;

  core.Class("events.Simple4",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testDeconnect : function() {

        var eventExecuted = 0;
        var myListener = function() {
          eventExecuted++;
        };

        this.addListener("simple4", myListener);

        this.fireEvent("simple4");
        test.isEqual(eventExecuted, 1);

        this.removeListener("simple4", myListener);

        test.isEqual(eventExecuted, 1);
        this.fireEvent("simple4");
        test.isEqual(eventExecuted, 1);

        test.isEqual(this.addListener("simple4", myListener), true);
        test.isEqual(this.addListener("simple4", myListener), false);
        test.isEqual(this.addListener("simple4", myListener), false);

        this.fireEvent("simple4");
        test.isEqual(eventExecuted, 2);

        test.isEqual(this.removeListener("simple4", myListener), true);
        test.isEqual(this.removeListener("simple4", myListener), false);
      }
    }
  });

  new events.Simple4().testDeconnect();
});

suite.test("Has", function()
{
  var test = this;

  core.Class("events.Simple5",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testHasListener : function() {

        var myListener = function() {};
        var myHelperObject = {};

        test.isEqual(this.hasListener("simple5"), false);
        this.addListener("simple5", myListener);
        test.isEqual(this.hasListener("simple5"), true);
        test.isEqual(this.hasListener("simple5", myListener), true);
        test.isEqual(this.hasListener("simple5", myListener, myHelperObject), false);
        this.removeListener("simple5", myListener);

        test.isEqual(this.hasListener("simple5"), false);
        this.addListener("simple5", myListener, myHelperObject);
        test.isEqual(this.hasListener("simple5"), true);
        test.isEqual(this.hasListener("simple5", myListener), false);
        test.isEqual(this.hasListener("simple5", myListener, myHelperObject), true);
        this.removeListener("simple5", myListener, myHelperObject);

      }
    }
  });

  new events.Simple5().testHasListener();
});

suite.test("Connect While Fire", function()
{
  var test = this;

  core.Class("events.Simple6",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testConnectWhileFire : function() {

        var count1 = 0;
        var count2 = 0;

        var myListener1 = function() {
          count1++;
        };

        var myListener2 = function() {
          count2++;
          this.addListener("simple6", myListener1);
        };

        this.addListener("simple6", myListener2);
        test.isEqual(count1, 0);
        test.isEqual(count2, 0);

        this.fireEvent("simple6");

        test.isEqual(count1, 0);
        test.isEqual(count2, 1);

        this.fireEvent("simple6");

        test.isEqual(count1, 1);
        test.isEqual(count2, 2);

      }
    }
  });

  new events.Simple6().testConnectWhileFire();
});

suite.test("Deconnect While Fire", function()
{
  var test = this;

  core.Class("events.Simple7",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testDeconnectWhileFire : function() {

        var count1 = 0;
        var count2 = 0;

        var myListener1 = function() {
          count1++;
        };

        var myListener2 = function() {
          count2++;
          this.removeListener("simple7", myListener1);
        };

        this.addListener("simple7", myListener1);
        this.addListener("simple7", myListener2);

        test.isEqual(count1, 0);
        test.isEqual(count2, 0);

        this.fireEvent("simple7");

        test.isEqual(count1, 1);
        test.isEqual(count2, 1);

        this.fireEvent("simple7");

        test.isEqual(count1, 1);
        test.isEqual(count2, 2);

      }
    }
  });

  new events.Simple7().testDeconnectWhileFire();
});

suite.test("Deconnect Self", function()
{
  var test = this;

  core.Class("events.Simple8",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testDeconnectSelf : function() {

        var count = 0;
        var myListener = function() {
          count++;
          this.removeListener("simple8", myListener);
        }

        this.addListener("simple8", myListener);
        test.isEqual(count, 0);

        this.fireEvent("simple8");
        test.isEqual(count, 1);

        this.fireEvent("simple8");
        test.isEqual(count, 1);

      }
    }
  });

  new events.Simple8().testDeconnectSelf();
});

suite.test("Listen Once", function()
{
  var test = this;

  core.Class("events.Simple9",
  {
    include : [core.event.MEventTarget],
    members :
    {
      testListenOnce : function() {

        var count = 0;
        var myListener = function() {
          count++;
        }

        this.addListenerOnce("simple9", myListener);
        test.isEqual(count, 0);

        this.fireEvent("simple9");
        test.isEqual(count, 1);

        this.fireEvent("simple9");
        test.isEqual(count, 1);

      }
    }
  });

  new events.Simple9().testListenOnce();
});


text:
@interface SurePlaceholderView : UIView

@property (nonatomic, copy) void(^reloadClickBlock)(void);

@end


text:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Title from './title';
import Search from './search';
import Back from './back';
import Category from './category';
import Tags from './tags';
import Widgets from './widget';

class Blog extends Component {
  constructor() {
    super();
  }

  render() {
    return (

            <Title ref="title"/>

			  <Back />

              <Search />

            <Category />
            <Tags />

            <Widgets />

            { this.props.children }

Powered by zyzPress 2016-2017.

    )
  }

}

export default Blog;


text:
package metadslx.core;

class MetaExpressionImpl extends metadslx.core.ModelObject implements metadslx.core.MetaExpression {
    static {
        metadslx.core.MetaDescriptor.staticInit();
    }

	@Override
    public metadslx.core.MetaModel mMetaModel() {
        return metadslx.core.MetaInstance.Meta;
    }

	@Override
    public metadslx.core.MetaClass mMetaClass() {
        return metadslx.core.MetaInstance.MetaExpression;
    }

    public MetaExpressionImpl() {
        this.mLazySet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty, metadslx.core.Lazy.create(() -> ModelCompilerContext.current().getTypeProvider().typeCheck((ModelObject)((MetaExpression)this)), true));
        metadslx.core.MetaImplementationProvider.implementation().MetaExpression(this);
        if (!this.mIsSet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty)) throw new ModelException("Readonly property Meta.MetaExpression.NoTypeErrorProperty was not set in MetaExpression_MetaExpression().");
        this.mMakeDefault();
    }

    public boolean getNoTypeError() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaExpression.NoTypeErrorProperty);
        if (result != null) return (boolean)result;
        else return (boolean)false;
    }

    public metadslx.core.MetaType getExpectedType() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaExpression.ExpectedTypeProperty);
        if (result != null) return (metadslx.core.MetaType)result;
        else return (metadslx.core.MetaType)null;
    }

    public metadslx.core.MetaType getType() {
        Object result = this.mGet(metadslx.core.MetaDescriptor.MetaTypedElement.TypeProperty);
        if (result != null) return (metadslx.core.MetaType)result;
        else return (metadslx.core.MetaType)null;
    }

    public void setType(metadslx.core.MetaType value) {
        this.mSet(metadslx.core.MetaDescriptor.MetaTypedElement.TypeProperty, value);
    }
}


text:
#ifndef JSNumberCell_h
#define JSNumberCell_h

#include "CallFrame.h"
#include "JSCell.h"
#include "JSImmediate.h"
#include "Collector.h"
#include "UString.h"
#include <stddef.h> // for size_t

namespace JSC {

    extern const double NaN;
    extern const double Inf;

#if USE(JSVALUE32)
    JSValue jsNumberCell(ExecState*, double);

    class Identifier;
    class JSCell;
    class JSObject;
    class JSString;
    class PropertySlot;

    struct ClassInfo;
    struct Instruction;

    class JSNumberCell : public JSCell {
        friend class JIT;
        friend JSValue jsNumberCell(JSGlobalData*, double);
        friend JSValue jsNumberCell(ExecState*, double);

    public:
        double value() const { return m_value; }

        virtual JSValue toPrimitive(ExecState*, PreferredPrimitiveType) const;
        virtual bool getPrimitiveNumber(ExecState*, double& number, JSValue& value);
        virtual bool toBoolean(ExecState*) const;
        virtual double toNumber(ExecState*) const;
        virtual UString toString(ExecState*) const;
        virtual JSObject* toObject(ExecState*) const;

        virtual UString toThisString(ExecState*) const;
        virtual JSObject* toThisObject(ExecState*) const;
        virtual JSValue getJSNumber();

        void* operator new(size_t size, ExecState* exec)
        {
            return exec->heap()->allocateNumber(size);
        }

        void* operator new(size_t size, JSGlobalData* globalData)
        {
            return globalData->heap.allocateNumber(size);
        }

        static PassRefPtr<Structure> createStructure(JSValue proto) { return Structure::create(proto, TypeInfo(NumberType, OverridesGetOwnPropertySlot | NeedsThisConversion)); }

    private:
        JSNumberCell(JSGlobalData* globalData, double value)
            : JSCell(globalData->numberStructure.get())
            , m_value(value)
        {
        }

        JSNumberCell(ExecState* exec, double value)
            : JSCell(exec->globalData().numberStructure.get())
            , m_value(value)
        {
        }

        virtual bool getUInt32(uint32_t&) const;

        double m_value;
    };

    JSValue jsNumberCell(JSGlobalData*, double);

    inline bool isNumberCell(JSValue v)
    {
        return v.isCell() && v.asCell()->isNumber();
    }

    inline JSNumberCell* asNumberCell(JSValue v)
    {
        ASSERT(isNumberCell(v));
        return static_cast<JSNumberCell*>(v.asCell());
    }

    ALWAYS_INLINE JSValue::JSValue(EncodeAsDoubleTag, ExecState* exec, double d)
    {
        *this = jsNumberCell(exec, d);
    }

    inline JSValue::JSValue(ExecState* exec, double d)
    {
        JSValue v = JSImmediate::from(d);
        *this = v ? v : jsNumberCell(exec, d);
    }

    inline JSValue::JSValue(ExecState* exec, int i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, i);
    }

    inline JSValue::JSValue(ExecState* exec, unsigned i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, i);
    }

    inline JSValue::JSValue(ExecState* exec, long i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, i);
    }

    inline JSValue::JSValue(ExecState* exec, unsigned long i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, i);
    }

    inline JSValue::JSValue(ExecState* exec, long long i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, static_cast<double>(i));
    }

    inline JSValue::JSValue(ExecState* exec, unsigned long long i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(exec, static_cast<double>(i));
    }

    inline JSValue::JSValue(JSGlobalData* globalData, double d)
    {
        JSValue v = JSImmediate::from(d);
        *this = v ? v : jsNumberCell(globalData, d);
    }

    inline JSValue::JSValue(JSGlobalData* globalData, int i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(globalData, i);
    }

    inline JSValue::JSValue(JSGlobalData* globalData, unsigned i)
    {
        JSValue v = JSImmediate::from(i);
        *this = v ? v : jsNumberCell(globalData, i);
    }

    inline bool JSValue::isDouble() const
    {
        return isNumberCell(asValue());
    }

    inline double JSValue::asDouble() const
    {
        return asNumberCell(asValue())->value();
    }

    inline bool JSValue::isNumber() const
    {
        return JSImmediate::isNumber(asValue()) || isDouble();
    }

    inline double JSValue::uncheckedGetNumber() const
    {
        ASSERT(isNumber());
        return JSImmediate::isImmediate(asValue()) ? JSImmediate::toDouble(asValue()) : asDouble();
    }

#endif // USE(JSVALUE32)

#if USE(JSVALUE64)
    ALWAYS_INLINE JSValue::JSValue(EncodeAsDoubleTag, ExecState*, double d)
    {
        *this = JSImmediate::fromNumberOutsideIntegerRange(d);
    }

    inline JSValue::JSValue(ExecState*, double d)
    {
        JSValue v = JSImmediate::from(d);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, int i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, unsigned i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, long i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, unsigned long i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, long long i)
    {
        JSValue v = JSImmediate::from(static_cast<double>(i));
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(ExecState*, unsigned long long i)
    {
        JSValue v = JSImmediate::from(static_cast<double>(i));
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(JSGlobalData*, double d)
    {
        JSValue v = JSImmediate::from(d);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(JSGlobalData*, int i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline JSValue::JSValue(JSGlobalData*, unsigned i)
    {
        JSValue v = JSImmediate::from(i);
        ASSERT(v);
        *this = v;
    }

    inline bool JSValue::isDouble() const
    {
        return JSImmediate::isDouble(asValue());
    }

    inline double JSValue::asDouble() const
    {
        return JSImmediate::doubleValue(asValue());
    }

    inline bool JSValue::isNumber() const
    {
        return JSImmediate::isNumber(asValue());
    }

    inline double JSValue::uncheckedGetNumber() const
    {
        ASSERT(isNumber());
        return JSImmediate::toDouble(asValue());
    }

#endif // USE(JSVALUE64)

#if USE(JSVALUE32) || USE(JSVALUE64)

    inline JSValue::JSValue(ExecState*, char i)
    {
        ASSERT(JSImmediate::from(i));
        *this = JSImmediate::from(i);
    }

    inline JSValue::JSValue(ExecState*, unsigned char i)
    {
        ASSERT(JSImmediate::from(i));
        *this = JSImmediate::from(i);
    }

    inline JSValue::JSValue(ExecState*, short i)
    {
        ASSERT(JSImmediate::from(i));
        *this = JSImmediate::from(i);
    }

    inline JSValue::JSValue(ExecState*, unsigned short i)
    {
        ASSERT(JSImmediate::from(i));
        *this = JSImmediate::from(i);
    }

    inline JSValue jsNaN(ExecState* exec)
    {
        return jsNumber(exec, NaN);
    }

    inline JSValue jsNaN(JSGlobalData* globalData)
    {
        return jsNumber(globalData, NaN);
    }

    // --- JSValue inlines ----------------------------

    ALWAYS_INLINE JSValue JSValue::toJSNumber(ExecState* exec) const
    {
        return isNumber() ? asValue() : jsNumber(exec, this->toNumber(exec));
    }

    inline bool JSValue::getNumber(double &result) const
    {
        if (isInt32())
            result = asInt32();
        else if (LIKELY(isDouble()))
            result = asDouble();
        else {
            ASSERT(!isNumber());
            return false;
        }
        return true;
    }

#endif // USE(JSVALUE32) || USE(JSVALUE64)

} // namespace JSC

#endif // JSNumberCell_h


text:
"""Unit test for Telegram objects."""
from xknx.dpt import DPTBinary
from xknx.telegram import GroupAddress, IndividualAddress, Telegram, TelegramDirection
from xknx.telegram.apci import GroupValueRead, GroupValueWrite
from xknx.telegram.tpci import TConnect, TDisconnect

class TestTelegram:
    """Test class for Telegram objects."""

    #
    # EQUALITY
    #
    def test_telegram_equal(self):
        """Test equals operator."""
        assert Telegram(GroupAddress("1/2/3"), payload=GroupValueRead()) == Telegram(
            GroupAddress("1/2/3"), payload=GroupValueRead()
        )

    def test_telegram_not_equal(self):
        """Test not equals operator."""
        assert Telegram(GroupAddress("1/2/3"), payload=GroupValueRead()) != Telegram(
            GroupAddress("1/2/4"), payload=GroupValueRead()
        )
        assert Telegram(GroupAddress("1/2/3"), payload=GroupValueRead()) != Telegram(
            GroupAddress("1/2/3"), payload=GroupValueWrite(DPTBinary(1))
        )
        assert Telegram(GroupAddress("1/2/3"), payload=GroupValueRead()) != Telegram(
            GroupAddress("1/2/3"),
            TelegramDirection.INCOMING,
            payload=GroupValueRead(),
        )
        assert Telegram(IndividualAddress(1), tpci=TConnect()) != Telegram(
            IndividualAddress(1), tpci=TDisconnect()
        )


text:
#include "fboss/agent/ThriftHandler.h"

#include <folly/IPAddressV4.h>
#include <folly/IPAddressV6.h>
#include "common/stats/ServiceData.h"
#include "fboss/agent/AddressUtil.h"
#include "fboss/agent/ArpHandler.h"
#include "fboss/agent/HighresCounterSubscriptionHandler.h"
#include "fboss/agent/IPv6Handler.h"
#include "fboss/agent/LldpManager.h"
#include "fboss/agent/SfpModule.h"
#include "fboss/agent/SwitchStats.h"
#include "fboss/agent/SwSwitch.h"
#include "fboss/agent/TxPacket.h"
#include "fboss/agent/Utils.h"
#include "fboss/agent/NeighborUpdater.h"
#include "fboss/agent/RouteUpdateLogger.h"
#include "fboss/agent/capture/PktCapture.h"
#include "fboss/agent/capture/PktCaptureManager.h"
#include "fboss/agent/hw/mock/MockRxPacket.h"
#include "fboss/agent/state/ArpEntry.h"
#include "fboss/agent/state/ArpTable.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/InterfaceMap.h"
#include "fboss/agent/state/NdpTable.h"
#include "fboss/agent/state/NdpEntry.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/Route.h"
#include "fboss/agent/state/RouteTable.h"
#include "fboss/agent/state/RouteTableRib.h"
#include "fboss/agent/state/RouteUpdater.h"
#include "fboss/agent/state/SwitchState.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"
#include "fboss/agent/if/gen-cpp2/NeighborListenerClient.h"

#include <folly/io/Cursor.h>
#include <folly/io/IOBuf.h>
#include <folly/MoveWrapper.h>
#include <folly/Range.h>
#include <thrift/lib/cpp2/async/DuplexChannel.h>

using apache::thrift::ClientReceiveState;
using facebook::fb303::cpp2::fb_status;
using folly::fbstring;
using folly::IOBuf;
using folly::make_unique;
using folly::StringPiece;
using folly::IPAddress;
using folly::IPAddressV4;
using folly::IPAddressV6;
using folly::MacAddress;
using folly::io::RWPrivateCursor;
using std::chrono::duration_cast;
using std::chrono::seconds;
using std::chrono::steady_clock;
using std::map;
using std::shared_ptr;
using std::string;
using std::vector;
using std::unique_ptr;
using namespace apache::thrift::transport;
using apache::thrift::server::TConnectionContext;

using facebook::network::toBinaryAddress;
using facebook::network::toAddress;
using facebook::network::toIPAddress;

namespace facebook { namespace fboss {

class RouteUpdateStats {
 public:
  RouteUpdateStats(SwSwitch *sw, const std::string& func, uint32_t routes)
      : sw_(sw),
        func_(func),
        routes_(routes),
        start_(std::chrono::steady_clock::now()) {
  }
  ~RouteUpdateStats() {
    auto end = std::chrono::steady_clock::now();
    auto duration =
      std::chrono::duration_cast<std::chrono::microseconds>(end - start_);
    sw_->stats()->routeUpdate(duration, routes_);
    VLOG(0) << func_ << " " << routes_ << " routes took "
            << duration.count() << "us";
  }
 private:
  SwSwitch* sw_;
  const std::string func_;
  uint32_t routes_;
  std::chrono::time_point<std::chrono::steady_clock> start_;
};

ThriftHandler::ThriftHandler(SwSwitch* sw) : FacebookBase2("FBOSS"), sw_(sw) {
  sw->registerNeighborListener(
    [=](const std::vector<std::string>& added,
        const std::vector<std::string>& deleted) {
      for (auto& listener : listeners_.accessAllThreads()) {
        LOG(INFO) << "Sending notification to bgpD";
        auto listenerPtr = &listener;
        listener.eventBase->runInEventBaseThread(
            [=] {
              LOG(INFO) << "firing off notification";
              invokeNeighborListeners(listenerPtr, added, deleted); });
      }
  });
}

fb_status ThriftHandler::getStatus() {
  if (sw_->isFullyInitialized()) {
    // We schedule a lightweight task on the update eventbase
    // so we can catch deadlocks in that thread
    auto healthcheckFn = [=] {
      //arbitrary code, could be changed if the log message is annoying
      VLOG(2) << "Healthcheck passed.";
    };
    sw_->getUpdateEVB()->runInEventBaseThreadAndWait(healthcheckFn);
    return fb_status::ALIVE;
  } else {
    return fb_status::STARTING;
  }
}

void ThriftHandler::async_tm_getStatus(ThriftCallback<fb_status> callback) {
  callback->result(getStatus());
}

void ThriftHandler::flushCountersNow() {
  // Currently SwSwitch only contains thread local stats.
  //
  // Depending on how we design the HW-specific stats interface,
  // we may also need to make a separate call to force immediate collection of
  // hardware stats.
  sw_->publishStats();
}

void ThriftHandler::addUnicastRoute(
    int16_t client, std::unique_ptr<UnicastRoute> route) {
  ensureConfigured("addUnicastRoute");
  ensureFibSynced("addUnicastRoute");
  RouteUpdateStats stats(sw_, "Add", 1);
  RouterID routerId = RouterID(0); // TODO, default vrf for now
  folly::IPAddress network = toIPAddress(route->dest.ip);
  uint8_t mask = static_cast<uint8_t>(route->dest.prefixLength);
  RouteNextHops nexthops;
  nexthops.reserve(route->nextHopAddrs.size());
  for (const auto& nh : route->nextHopAddrs) {
    nexthops.emplace(toIPAddress(nh));
  }
  if (network.isV4()) {
    sw_->stats()->addRouteV4();
  } else {
    sw_->stats()->addRouteV6();
  }

  // Perform the update
  auto updateFn = [=](const shared_ptr<SwitchState>& state) {
    RouteUpdater updater(state->getRouteTables());
    if (nexthops.size()) {
      updater.addRoute(routerId, network, mask, std::move(nexthops));
    } else {
      updater.addRoute(routerId, network, mask, RouteForwardAction::DROP);
    }
    auto newRt = updater.updateDone();
    if (!newRt) {
      return shared_ptr<SwitchState>();
    }
    auto newState = state->clone();
    newState->resetRouteTables(std::move(newRt));
    return newState;
  };
  sw_->updateStateBlocking("add unicast route", updateFn);
}

void ThriftHandler::deleteUnicastRoute(
    int16_t client, std::unique_ptr<IpPrefix> prefix) {
  ensureConfigured("deleteUnicastRoute");
  ensureFibSynced("deleteUnicastRoute");
  RouteUpdateStats stats(sw_, "Delete", 1);
  RouterID routerId = RouterID(0); // TODO, default vrf for now
  folly::IPAddress network =  toIPAddress(prefix->ip);
  uint8_t mask = static_cast<uint8_t>(prefix->prefixLength);
  if (network.isV4()) {
    sw_->stats()->delRouteV4();
  } else {
    sw_->stats()->delRouteV6();
  }

  // Perform the update
  auto updateFn = [=](const shared_ptr<SwitchState>& state) {
    RouteUpdater updater(state->getRouteTables());
    updater.delRoute(routerId, network, mask);
    auto newRt = updater.updateDone();
    if (!newRt) {
      return shared_ptr<SwitchState>();
    }
    auto newState = state->clone();
    newState->resetRouteTables(std::move(newRt));
    return newState;
  };
  sw_->updateStateBlocking("delete unicast route", updateFn);
}

void ThriftHandler::addUnicastRoutes(
    int16_t client, std::unique_ptr<std::vector<UnicastRoute>> routes) {
  ensureConfigured("addUnicastRoutes");
  ensureFibSynced("addUnicastRoutes");
  RouteUpdateStats stats(sw_, "Add", routes->size());
  auto updateFn = [&](const shared_ptr<SwitchState>& state) {
    RouteUpdater updater(state->getRouteTables());
    RouterID routerId = RouterID(0); // TODO, default vrf for now
    for (const auto& route : *routes) {
      auto network = toIPAddress(route.dest.ip);
      auto mask = static_cast<uint8_t>(route.dest.prefixLength);
      RouteNextHops nexthops;
      nexthops.reserve(route.nextHopAddrs.size());
      for (const auto& nh : route.nextHopAddrs) {
        nexthops.emplace(toIPAddress(nh));
      }
      if (nexthops.size()) {
        updater.addRoute(routerId, network, mask, std::move(nexthops));
      } else {
        updater.addRoute(routerId, network, mask, RouteForwardAction::DROP);
      }
      if (network.isV4()) {
        sw_->stats()->addRouteV4();
      } else {
        sw_->stats()->addRouteV6();
      }
    }
    auto newRt = updater.updateDone();
    if (!newRt) {
      return shared_ptr<SwitchState>();
    }
    auto newState = state->clone();
    newState->resetRouteTables(std::move(newRt));
    return newState;
  };
  sw_->updateStateBlocking("add unicast route", updateFn);
}

void ThriftHandler::getProductInfo(ProductInfo& productInfo) {
  sw_->getProductInfo(productInfo);
}

void ThriftHandler::deleteUnicastRoutes(
    int16_t client, std::unique_ptr<std::vector<IpPrefix>> prefixes) {
  ensureConfigured("deleteUnicastRoutes");
  ensureFibSynced("deleteUnicastRoutes");
  RouteUpdateStats stats(sw_, "Delete", prefixes->size());
  // Perform the update
  auto updateFn = [&](const shared_ptr<SwitchState>& state) {
    RouteUpdater updater(state->getRouteTables());
    RouterID routerId = RouterID(0); // TODO, default vrf for now
    for (const auto& prefix : *prefixes) {
      auto network = toIPAddress(prefix.ip);
      auto mask = static_cast<uint8_t>(prefix.prefixLength);
      if (network.isV4()) {
        sw_->stats()->delRouteV4();
      } else {
        sw_->stats()->delRouteV6();
      }
      updater.delRoute(routerId, network, mask);
    }
    auto newRt = updater.updateDone();
    if (!newRt) {
      return shared_ptr<SwitchState>();
    }
    auto newState = state->clone();
    newState->resetRouteTables(std::move(newRt));
    return newState;
  };
  sw_->updateStateBlocking("delete unicast route", updateFn);
}

void ThriftHandler::syncFib(
    int16_t client, std::unique_ptr<std::vector<UnicastRoute>> routes) {
  ensureConfigured("syncFib");
  RouteUpdateStats stats(sw_, "Sync", routes->size());

  // Note that we capture routes by reference here, since it is a unique_ptr.
  // This is safe since we use updateStateBlocking(), so routes will still
  // be valid in our scope when updateFn() is called.
  // We could use folly::MoveWrapper if we did need to capture routes by value.
  auto updateFn = [&](const shared_ptr<SwitchState>& state) {
    // create an update object starting from empty
    RouteUpdater updater(state->getRouteTables(), true);
    cfg::SwitchConfig emptyPrevConfig;
    // Add static routes from config
    updater.updateStaticRoutes(sw_->getConfig(), emptyPrevConfig);
    // add all interface routes
    updater.addInterfaceAndLinkLocalRoutes(state->getInterfaces());
    RouterID routerId = RouterID(0); // TODO, default vrf for now
    for (auto const& route : *routes) {
      folly::IPAddress network = toIPAddress(route.dest.ip);
      uint8_t mask = static_cast<uint8_t>(route.dest.prefixLength);
      RouteNextHops nexthops;
      nexthops.reserve(route.nextHopAddrs.size());
      for (const auto& nh : route.nextHopAddrs) {
        nexthops.emplace(toIPAddress(nh));
      }
      updater.addRoute(routerId, network, mask, std::move(nexthops));
      if (network.isV4()) {
        sw_->stats()->addRouteV4();
      } else {
        sw_->stats()->addRouteV6();
      }
    }
    auto newRt = updater.updateDone();
    if (!newRt) {
      return shared_ptr<SwitchState>();
    }
    auto newState = state->clone();
    newState->resetRouteTables(std::move(newRt));
    return newState;
  };
  sw_->updateStateBlocking("sync fib", updateFn);

  sw_->clearWarmBootCache();
  sw_->fibSynced();
}

void ThriftHandler::getAllInterfaces(
    std::map<int32_t, InterfaceDetail>& interfaces) {
  ensureConfigured();
  for (const auto& intf : (*sw_->getState()->getInterfaces())) {
    auto& interfaceDetail = interfaces[intf->getID()];

    interfaceDetail.interfaceName = intf->getName();
    interfaceDetail.interfaceId = intf->getID();
    interfaceDetail.vlanId = intf->getVlanID();
    interfaceDetail.routerId = intf->getRouterID();
    interfaceDetail.mac = intf->getMac().toString();
    interfaceDetail.address.reserve(intf->getAddresses().size());
    for (const auto& addrAndMask: intf->getAddresses()) {
      IpPrefix temp;
      temp.ip = toBinaryAddress(addrAndMask.first);
      temp.prefixLength = addrAndMask.second;
      interfaceDetail.address.push_back(temp);
    }
  }
}

void ThriftHandler::getInterfaceList(std::vector<std::string>& interfaceList) {
  ensureConfigured();
  for (const auto& intf : (*sw_->getState()->getInterfaces())) {
    interfaceList.push_back(intf->getName());
  }
}

void ThriftHandler::getInterfaceDetail(InterfaceDetail& interfaceDetail,
                                                        int32_t interfaceId) {
  ensureConfigured();
  const auto& intf = sw_->getState()->getInterfaces()->getInterfaceIf(
      InterfaceID(interfaceId));

  if (!intf) {
    throw FbossError("no such interface ", interfaceId);
  }

  interfaceDetail.interfaceName = intf->getName();
  interfaceDetail.interfaceId = intf->getID();
  interfaceDetail.vlanId = intf->getVlanID();
  interfaceDetail.routerId = intf->getRouterID();
  interfaceDetail.mac = intf->getMac().toString();
  interfaceDetail.address.clear();
  interfaceDetail.address.reserve(intf->getAddresses().size());
  for (const auto& addrAndMask: intf->getAddresses()) {
    IpPrefix temp;
    temp.ip = toBinaryAddress(addrAndMask.first);
    temp.prefixLength = int(addrAndMask.second);
    interfaceDetail.address.push_back(temp);
  }
}

void ThriftHandler::getNdpTable(std::vector<NdpEntryThrift>& ndpTable) {
  ensureConfigured();
  sw_->getNeighborUpdater()->getNdpCacheData(ndpTable);
}

void ThriftHandler::getArpTable(std::vector<ArpEntryThrift>& arpTable) {
  ensureConfigured();
  sw_->getNeighborUpdater()->getArpCacheData(arpTable);
}

void ThriftHandler::getL2Table(std::vector<L2EntryThrift>& l2Table) {
  ensureConfigured();
  sw_->getHw()->fetchL2Table(&l2Table);
  VLOG(6) << "L2 Table size:" << l2Table.size();
}

void ThriftHandler::fillPortStats(PortInfoThrift& portInfo) {
  auto portId = portInfo.portId;
  auto statMap = fbData->getStatMap();

  auto getSumStat = [&] (StringPiece prefix, StringPiece name) {
    // Currently, the internal name of the port is "port<n>", even though
    // `the external name is "eth<a>/<b>/<c>"
    auto portName = folly::to<std::string>("port", portId);
    auto statName = folly::to<std::string>(portName, ".", prefix, name);
    auto statPtr = statMap->getStatPtr(statName);
    auto numLevels = statPtr->numLevels();
    // Cumulative (ALLTIME) counters are at (numLevels - 1)
    return statPtr->sum(numLevels - 1);
  };

  auto fillPortCounters = [&] (PortCounters& ctr, StringPiece prefix) {
    ctr.bytes = getSumStat(prefix, "bytes");
    ctr.ucastPkts = getSumStat(prefix, "unicast_pkts");
    ctr.multicastPkts = getSumStat(prefix, "multicast_pkts");
    ctr.broadcastPkts = getSumStat(prefix, "broadcast_pkts");
    ctr.errors.errors = getSumStat(prefix, "errors");
    ctr.errors.discards = getSumStat(prefix, "discards");
  };

  const auto& status = sw_->getPortStatus(PortID(portId));
  portInfo.adminState = PortAdminState(status.enabled);
  portInfo.operState = PortOperState(status.up);

  fillPortCounters(portInfo.output, "out_");
  fillPortCounters(portInfo.input, "in_");
}

void ThriftHandler::getPortInfo(PortInfoThrift& portInfo, int32_t portId) {
  ensureConfigured();
  const auto port = sw_->getState()->getPorts()->getPortIf(PortID(portId));

  if (!port) {
    throw FbossError("no such port ", portId);
  }
  portInfo.portId = portId;
  portInfo.name = port->getName();
  portInfo.description = port->getDescription();
  portInfo.speedMbps = (int) port->getWorkingSpeed();
  for (auto entry : port->getVlans()) {
    portInfo.vlans.push_back(entry.first);
  }
  fillPortStats(portInfo);
}

void ThriftHandler::getAllPortInfo(map<int32_t, PortInfoThrift>& portInfoMap) {
  ensureConfigured();

  for (const auto& port : (*sw_->getState()->getPorts())) {
    auto portId = port->getID();
    auto& portInfo = portInfoMap[portId];
    getPortInfo(portInfo, portId);
  }
}

void ThriftHandler::getPortStats(PortInfoThrift& portInfo, int32_t portId) {
  getPortInfo(portInfo, portId);
}

void ThriftHandler::getAllPortStats(map<int32_t, PortInfoThrift>& portInfoMap) {
  getAllPortInfo(portInfoMap);
}

void ThriftHandler::getRunningConfig(std::string& configStr) {
  ensureConfigured();
  configStr = sw_->getConfigStr();
}

void ThriftHandler::getPortStatus(map<int32_t, PortStatus>& statusMap,
                                  unique_ptr<vector<int32_t>> ports) {
  ensureConfigured();
  if (ports->empty()) {
    statusMap = sw_->getPortStatus();
  } else {
    for (auto port : *ports) {
      statusMap[port] = sw_->getPortStatus(PortID(port));
    }
  }
}

void ThriftHandler::setPortState(int32_t portNum, bool enable) {
  ensureConfigured();
  PortID portId = PortID(portNum);
  const auto port = sw_->getState()->getPorts()->getPortIf(portId);
  if (!port) {
    throw FbossError("no such port ", portNum);
  }

  cfg::PortState newPortState =
    enable? cfg::PortState::UP: cfg::PortState::DOWN;

  if (port->getState() == newPortState) {
    VLOG(2) << "setPortState: port already in state " << (enable? "UP": "DOWN");
    return;
  }

  auto updateFn = [=](const shared_ptr<SwitchState>& state) {
    shared_ptr<SwitchState> newState{state};
    auto newPort = port->modify(&newState);
    newPort->setState(newPortState);
    return newState;
  };
  sw_->updateStateBlocking("set port state", updateFn);
}

void ThriftHandler::getRouteTable(std::vector<UnicastRoute>& route) {
  ensureConfigured();
  for (const auto& routeTable : (*sw_->getState()->getRouteTables())) {
    for (const auto& ipv4Rib : routeTable->getRibV4()->routes()) {
      UnicastRoute tempRoute;
      auto ipv4 = ipv4Rib.value().get();
      auto fwdInfo = ipv4->getForwardInfo();
      tempRoute.dest.ip = toBinaryAddress(ipv4->prefix().network);
      tempRoute.dest.prefixLength = ipv4->prefix().mask;
      for (const auto& hop : fwdInfo.getNexthops()) {
        tempRoute.nextHopAddrs.push_back(
                    toBinaryAddress(hop.nexthop));
      }
      route.push_back(tempRoute);
    }
    for (const auto& ipv6Rib : routeTable->getRibV6()->routes()) {
      UnicastRoute tempRoute;
      auto ipv6 = ipv6Rib.value().get();
      auto fwdInfo = ipv6->getForwardInfo();
      tempRoute.dest.ip = toBinaryAddress(
                                                     ipv6->prefix().network);
      tempRoute.dest.prefixLength = ipv6->prefix().mask;
      for (const auto& hop : fwdInfo.getNexthops()) {
        tempRoute.nextHopAddrs.push_back(
                    toBinaryAddress(hop.nexthop));
      }
      route.push_back(tempRoute);
    }
  }
}

void ThriftHandler::getIpRoute(UnicastRoute& route,
                                std::unique_ptr<Address> addr, int32_t vrfId) {
  ensureConfigured();
  folly::IPAddress ipAddr = toIPAddress(*addr);
  auto routeTable = sw_->getState()->getRouteTables()->getRouteTableIf(
                                                              RouterID(vrfId));
  if (!routeTable) {
    throw FbossError("No Such VRF ", vrfId);
  }

  if (ipAddr.isV4()) {
    auto ripV4Rib = routeTable->getRibV4();
    auto match = ripV4Rib->longestMatch(ipAddr.asV4());
    if (!match) {
      route.dest.ip = toBinaryAddress(IPAddressV4("0.0.0.0"));
      route.dest.prefixLength = 0;
      return;
    }
    const auto fwdInfo = match->getForwardInfo();
    route.dest.ip = toBinaryAddress(match->prefix().network);
    route.dest.prefixLength = match->prefix().mask;
    for (auto iter = fwdInfo.getNexthops().begin();
              iter != fwdInfo.getNexthops().end(); ++iter) {
      route.nextHopAddrs.push_back(toBinaryAddress(iter->nexthop));
    }
  } else {
    auto ripV6Rib = routeTable->getRibV6();
    auto match = ripV6Rib->longestMatch(ipAddr.asV6());
    if (!match) {
      route.dest.ip = toBinaryAddress(IPAddressV6("::0"));
      route.dest.prefixLength = 0;
      return;
    }
    const auto fwdInfo = match->getForwardInfo();
    route.dest.ip = toBinaryAddress(match->prefix().network);
    route.dest.prefixLength = match->prefix().mask;
    for (auto iter = fwdInfo.getNexthops().begin();
              iter != fwdInfo.getNexthops().end(); ++iter) {
      route.nextHopAddrs.push_back(toBinaryAddress(iter->nexthop));
    }
  }
}

static LinkNeighborThrift thriftLinkNeighbor(const LinkNeighbor& n,
                                             steady_clock::time_point now) {
  LinkNeighborThrift tn;
  tn.localPort = n.getLocalPort();
  tn.localVlan = n.getLocalVlan();
  tn.srcMac = n.getMac().toString();
  tn.chassisIdType = static_cast<int32_t>(n.getChassisIdType());
  tn.chassisId = n.getChassisId();
  tn.printableChassisId = n.humanReadableChassisId();
  tn.portIdType = static_cast<int32_t>(n.getPortIdType());
  tn.portId = n.getPortId();
  tn.printablePortId = n.humanReadablePortId();
  tn.originalTTL = duration_cast<seconds>(n.getTTL()).count();
  tn.ttlSecondsLeft =
    duration_cast<seconds>(n.getExpirationTime() - now).count();
  if (!n.getSystemName().empty()) {
    tn.systemName = n.getSystemName();
    tn.__isset.systemName = true;
  }
  if (!n.getSystemDescription().empty()) {
    tn.systemDescription = n.getSystemDescription();
    tn.__isset.systemDescription = true;
  }
  if (!n.getPortDescription().empty()) {
    tn.portDescription = n.getPortDescription();
    tn.__isset.portDescription = true;
  }
  return tn;
}

void ThriftHandler::getLldpNeighbors(vector<LinkNeighborThrift>& results) {
  ensureConfigured();
  auto* db = sw_->getLldpMgr()->getDB();
  // Do an immediate check for expired neighbors
  db->pruneExpiredNeighbors();
  auto neighbors = db->getNeighbors();
  results.reserve(neighbors.size());
  auto now = steady_clock::now();
  for (const auto& entry : db->getNeighbors()) {
    results.push_back(thriftLinkNeighbor(entry, now));
  }
}

void ThriftHandler::invokeNeighborListeners(ThreadLocalListener* listener,
                                             std::vector<std::string> added,
                                             std::vector<std::string> removed) {
  // Collect the iterators to avoid erasing and potentially reordering
  // the iterators in the list.
  std::vector<const TConnectionContext*> brokenClients;
  for (auto& client : listener->clients) {
    auto clientDone = [&](ClientReceiveState&& state) {
      try {
        NeighborListenerClientAsyncClient::recv_neighborsChanged(state);
      } catch (const std::exception& ex) {
        LOG(ERROR) << "Exception in neighbor listener: " << ex.what();
        brokenClients.push_back(client.first);
      }
    };
    client.second->neighborsChanged(clientDone, added, removed);
  }
  for (const auto& ctx : brokenClients) {
    listener->clients.erase(ctx);
  }
}

void ThriftHandler::async_eb_registerForNeighborChanged(
    ThriftCallback<void> cb) {
  auto ctx = cb->getConnectionContext()->getConnectionContext();
  auto client = ctx->getDuplexClient<NeighborListenerClientAsyncClient>();
  auto info = listeners_.get();
  CHECK(cb->getEventBase()->isInEventBaseThread());
  if (!info) {
    info = new ThreadLocalListener(cb->getEventBase());
    listeners_.reset(info);
  }
  DCHECK_EQ(info->eventBase, cb->getEventBase());
  if (!info->eventBase) {
    info->eventBase = cb->getEventBase();
  }
  info->clients.emplace(ctx, client);
  cb->done();
}

void ThriftHandler::startPktCapture(unique_ptr<CaptureInfo> info) {
  ensureConfigured();
  auto* mgr = sw_->getCaptureMgr();
  auto capture = make_unique<PktCapture>(info->name, info->maxPackets);
  mgr->startCapture(std::move(capture));
}

void ThriftHandler::stopPktCapture(unique_ptr<std::string> name) {
  ensureConfigured();
  auto* mgr = sw_->getCaptureMgr();
  mgr->forgetCapture(*name);
}

void ThriftHandler::stopAllPktCaptures() {
  ensureConfigured();
  auto* mgr = sw_->getCaptureMgr();
  mgr->forgetAllCaptures();
}

void ThriftHandler::startLoggingRouteUpdates(
    std::unique_ptr<RouteUpdateLoggingInfo> info) {
  auto* routeUpdateLogger = sw_->getRouteUpdateLogger();
  folly::IPAddress addr = toIPAddress(info->prefix.ip);
  uint8_t mask = static_cast<uint8_t>(info->prefix.prefixLength);
  RouteUpdateLoggingInstance loggingInstance{
      RoutePrefix<folly::IPAddress>{addr, mask}, info->identifier, info->exact};
  routeUpdateLogger->startLoggingForPrefix(loggingInstance);
}

void ThriftHandler::stopLoggingRouteUpdates(
    std::unique_ptr<IpPrefix> prefix,
    std::unique_ptr<std::string> identifier) {
  auto* routeUpdateLogger = sw_->getRouteUpdateLogger();
  folly::IPAddress addr = toIPAddress(prefix->ip);
  uint8_t mask = static_cast<uint8_t>(prefix->prefixLength);
  routeUpdateLogger->stopLoggingForPrefix(addr, mask, *identifier);
}

void ThriftHandler::stopLoggingAnyRouteUpdates(
    std::unique_ptr<std::string> identifier) {
  auto* routeUpdateLogger = sw_->getRouteUpdateLogger();
  routeUpdateLogger->stopLoggingForIdentifier(*identifier);
}

void ThriftHandler::getRouteUpdateLoggingTrackedPrefixes(
    std::vector<RouteUpdateLoggingInfo>& infos) {
  auto* routeUpdateLogger = sw_->getRouteUpdateLogger();
  for (const auto& tracked : routeUpdateLogger->getTrackedPrefixes()) {
    RouteUpdateLoggingInfo info;
    IpPrefix prefix;
    prefix.ip = toBinaryAddress(tracked.prefix.network);
    prefix.prefixLength = tracked.prefix.mask;
    info.prefix = prefix;
    info.identifier = tracked.identifier;
    info.exact = tracked.exact;
    infos.push_back(info);
  }
}

void ThriftHandler::sendPkt(int32_t port, int32_t vlan,
                            unique_ptr<fbstring> data) {
  ensureConfigured("sendPkt");
  auto buf = IOBuf::copyBuffer(reinterpret_cast<const uint8_t*>(data->data()),
                               data->size());
  auto pkt = make_unique<MockRxPacket>(std::move(buf));
  pkt->setSrcPort(PortID(port));
  pkt->setSrcVlan(VlanID(vlan));
  sw_->packetReceived(std::move(pkt));
}

void ThriftHandler::sendPktHex(int32_t port, int32_t vlan,
                               unique_ptr<fbstring> hex) {
  ensureConfigured("sendPktHex");
  auto pkt = MockRxPacket::fromHex(StringPiece(*hex));
  pkt->setSrcPort(PortID(port));
  pkt->setSrcVlan(VlanID(vlan));
  sw_->packetReceived(std::move(pkt));
}

void ThriftHandler::txPkt(int32_t port, unique_ptr<fbstring> data) {
  ensureConfigured("txPkt");

  unique_ptr<TxPacket> pkt = sw_->allocatePacket(data->size());
  RWPrivateCursor cursor(pkt->buf());
  cursor.push(StringPiece(*data));

  sw_->sendPacketOutOfPort(std::move(pkt), PortID(port));
}

void ThriftHandler::txPktL2(unique_ptr<fbstring> data) {
  ensureConfigured("txPktL2");

  unique_ptr<TxPacket> pkt = sw_->allocatePacket(data->size());
  RWPrivateCursor cursor(pkt->buf());
  cursor.push(StringPiece(*data));

  sw_->sendPacketSwitched(std::move(pkt));
}

void ThriftHandler::txPktL3(unique_ptr<fbstring> payload) {
  ensureConfigured("txPktL3");

  unique_ptr<TxPacket> pkt = sw_->allocateL3TxPacket(payload->size());
  RWPrivateCursor cursor(pkt->buf());
  cursor.push(StringPiece(*payload));

  sw_->sendL3Packet(RouterID(0), std::move(pkt));
}

Vlan* ThriftHandler::getVlan(int32_t vlanId) {
  ensureConfigured();
  return sw_->getState()->getVlans()->getVlan(VlanID(vlanId)).get();
}

Vlan* ThriftHandler::getVlan(const std::string& vlanName) {
  ensureConfigured();
  return sw_->getState()->getVlans()->getVlanSlow(vlanName).get();
}

int32_t ThriftHandler::flushNeighborEntry(unique_ptr<BinaryAddress> ip,
                                          int32_t vlan) {
  ensureConfigured("flushNeighborEntry");

  auto parsedIP = toIPAddress(*ip);
  VlanID vlanID(vlan);
  return sw_->getNeighborUpdater()->flushEntry(vlanID, parsedIP);
}

void ThriftHandler::getVlanAddresses(Addresses& addrs, int32_t vlan) {
  getVlanAddresses(getVlan(vlan), addrs, toAddress);
}

void ThriftHandler::getVlanAddressesByName(Addresses& addrs,
    unique_ptr<string> vlan) {
  getVlanAddresses(getVlan(*vlan), addrs, toAddress);
}

void ThriftHandler::getVlanBinaryAddresses(BinaryAddresses& addrs,
    int32_t vlan) {
  getVlanAddresses(getVlan(vlan), addrs, toBinaryAddress);
}

void ThriftHandler::getVlanBinaryAddressesByName(BinaryAddresses& addrs,
    const std::unique_ptr<std::string> vlan) {
  getVlanAddresses(getVlan(*vlan), addrs, toBinaryAddress);
}

void ThriftHandler::getSfpDomInfo(map<int32_t, SfpDom>& domInfos,
                                  unique_ptr<vector<int32_t>> ports) {
  ensureConfigured();
  if (ports->empty()) {
    domInfos = sw_->getSfpDoms();
  } else {
    for (auto port : *ports) {
      domInfos[port] = sw_->getSfpDom(PortID(port));
    }
  }
}

void ThriftHandler::getTransceiverInfo(map<int32_t, TransceiverInfo>& info,
                                  unique_ptr<vector<int32_t>> ids) {
  ensureConfigured();
  if (ids->empty()) {
    auto transceivers = sw_->getTransceiversInfo();
    for (auto& it : transceivers) {
      info[it.first] = it.second;
    }
  } else {
    for (auto id : *ids) {
      info[id] = sw_->getTransceiverInfo(TransceiverID(id));
    }
  }
}

template<typename ADDR_TYPE, typename ADDR_CONVERTER>
void ThriftHandler::getVlanAddresses(const Vlan* vlan,
    std::vector<ADDR_TYPE>& addrs, ADDR_CONVERTER& converter) {
  ensureConfigured();
  CHECK(vlan);
  for (auto intf : (*sw_->getState()->getInterfaces())) {
    if (intf->getVlanID() == vlan->getID()) {
      for (const auto& addrAndMask : intf->getAddresses()) {
          addrs.push_back(converter(addrAndMask.first));
      }
    }
  }
}

BootType ThriftHandler::getBootType() {
  return sw_->getBootType();
}

void ThriftHandler::ensureConfigured(StringPiece function) {
  if (sw_->isFullyConfigured()) {
    return;
  }

  if (!function.empty()) {
    VLOG(1) << "failing thrift prior to switch configuration: " << function;
  }
  throw FbossError("switch is still initializing or is exiting and is not "
                   "fully configured yet");
}

void ThriftHandler::ensureFibSynced(StringPiece function) {
  if (sw_->isFibSynced()) {
    return;
  }

  if (!function.empty()) {
    VLOG(1) << "failing thrift prior to FIB Sync: " << function;
  }
  throw FbossError("switch is still initializing, FIB not synced yet");
}

// If this is a premature client disconnect from a duplex connection, we need to
// clean up state.  Failure to do so may allow the server's duplex clients to
// use the destroyed context => segfaults.
void ThriftHandler::connectionDestroyed(TConnectionContext* ctx) {
  // Port status notifications
  if (listeners_) {
    listeners_->clients.erase(ctx);
  }

  // If there is an ongoing high-resolution counter subscription, kill it. Don't
  // grab a write lock if there are no active calls
  if (!highresKillSwitches_.asConst()->empty()) {
    SYNCHRONIZED(highresKillSwitches_) {
      auto killSwitchIter = highresKillSwitches_.find(ctx);

      if (killSwitchIter != highresKillSwitches_.end()) {
        killSwitchIter->second->set();
        highresKillSwitches_.erase(killSwitchIter);
      }
    }
  }
}

void ThriftHandler::async_tm_subscribeToCounters(
    ThriftCallback<bool> callback, unique_ptr<CounterSubscribeRequest> req) {

  // Grab the requested samplers from the underlying switch implementation
  auto samplers = make_unique<HighresSamplerList>();
  auto numCounters = sw_->getHighresSamplers(samplers.get(), req->counters);

  if (numCounters > 0) {
    // Grab the connection context and create a kill switch
    auto ctx = callback->getConnectionContext()->getConnectionContext();
    auto killSwitch = std::make_shared<Signal>();
    SYNCHRONIZED(highresKillSwitches_) {
      highresKillSwitches_[ctx] = killSwitch;
    }

    // Create the sender
    auto client = ctx->getDuplexClient<FbossHighresClientAsyncClient>();
    auto eventBase = callback->getEventBase();
    auto sender = std::make_shared<SampleSender>(std::move(client), killSwitch,
                                                 eventBase, numCounters);

    // Create the sample producer and send it on its way
    auto producer = make_unique<SampleProducer>(
        std::move(samplers), std::move(sender), std::move(killSwitch),
        eventBase, *req.get(), numCounters);
    auto wrappedProducer = folly::makeMoveWrapper(std::move(producer));
    auto veryNice = req->veryNice;
    std::thread producerThread([wrappedProducer, veryNice]() mutable {
      if (veryNice) {
        incNiceValue(20);
      }
      (*wrappedProducer)->produce();
    });
    producerThread.detach();

    callback->result(true);
  } else {
    LOG(ERROR) << "None of the requested counters were valid.";
    callback->result(false);
  }
}

int32_t ThriftHandler::getIdleTimeout() {
  if (thriftIdleTimeout_ < 0) {
    throw FbossError("Idle timeout has not been set");
  }
  return thriftIdleTimeout_;
}

void ThriftHandler::reloadConfig() {
  return sw_->applyConfig("reload config initiated by thrift call");
}

}} // facebook::fboss


text:
using System;
using System.Threading;
using log4net.Config;
using NServiceBus.Installation.Environments;
using NServiceBus.Tracking.Sample.Fakes;
using NServiceBus.Tracking.Sample.Messages;

namespace NServiceBus.Tracking.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            var startedEvent = new ManualResetEvent(false);
            var startableBus = Configure.With()
                .DefaultBuilder()
                .MsmqTransport()
                    .IsTransactional(false)
                    .PurgeOnStartup(true)
                .UnicastBus()
                    .ImpersonateSender(false)
                .OperationTracking()
                .FakeOperationProvider()
                .RunCustomAction(() =>
                    Configure.Instance.ForInstallationOn<Windows>().Install())
                .CreateBus();
            startableBus.Started += (sender, e) => startedEvent.Set();
            var bus = startableBus.Start();
            startedEvent.WaitOne();
            Thread.Sleep(500);
            Console.WriteLine();
            Console.WriteLine();
            while (true)
            {
                Console.WriteLine("Press any key to start a message chain, or ESC to exit.");
                Console.WriteLine();
                var key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                    break;
                Console.WriteLine();
                Console.WriteLine();
                bus.SendLocal(new OrderCommand { Description = "My order" });
                var operation = Operation.Current;
                operation.CompleteAfter<BillCommand, ShipCommand>();
                Console.Out.WriteLine(ConsoleColor.Green, "Operation ID is {0}", operation.Id);
                Console.Out.WriteLine(ConsoleColor.Green, "Waiting for operation to complete...");
                int waitCount = 0;
                while (!operation.IsCompleted())
                {
                    Thread.Sleep(500);
                    Console.Out.WriteLine(ConsoleColor.Gray, "Still waiting - polled {0} times", ++waitCount);
                }
                Console.Out.WriteLine(ConsoleColor.Green, "Ship command was received - operation completed!");
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("---");
            }
        }
    }
}


text:
from distutils.core import setup
import py2exe

setup(console=['vs_tool_agent.py'])


text:
define([
    "backbone",
    "mustache",
    "cms/views/item-form/project-form-view",
    "cms/views/item-form/tag-form-view",
    "cms/views/item-form/session-form-view",
    "cms/views/item-form/user-form-view",
    "notes",
    "text!cms/templates/forms/item-form.mustache",
    "text!cms/templates/forms/project-form-fields.mustache",
    "text!cms/templates/forms/tag-form-fields.mustache",
    "text!cms/templates/forms/session-form-fields.mustache",
    "text!cms/templates/forms/user-form-fields.mustache"
    ],function (Backbone,Mustache,ProjectFormView,TagFormView,SessionFormView,UserFormView,notes,formTemplate,projectFieldsTemplate,tagFieldsTemplate,sessionFieldsTemplate,userFieldsTemplate) {

    return Backbone.View.extend({

        initialize: function (options) {
            this.collections = options.collections;
            this.formViews = {
                "projects": ProjectFormView,
                "tags": TagFormView,
                "users": UserFormView,
                "sessions": SessionFormView
            };
            this.formFieldsPartials = {
                "projects": projectFieldsTemplate,
                "tags": tagFieldsTemplate,
                "users": userFieldsTemplate,
                "sessions": sessionFieldsTemplate
            };
            Backbone.Notifications.on(notes.ROUTE_CHANGED,this.onRouteChanged,this);
        },

        onRouteChanged: function (event) {
            if ( this.formView ) {
                this.formView.destroy();
            }
            if ( !event.action && !event.id ) {
                return;
            }
            var collection = this.collections[event.route];
            var self = this;
            if ( collection.length === 0 ) {
                collection.fetch({
                    error: function (collection,xhr,options) {
                        var serverError = JSON.parse(xhr.responseText);
                        Backbone.Notifications.trigger(notes.SHOW_MESSAGE,{title:"Error "+xhr.status+" "+serverError.code,error:true,message:serverError.message});
                    },
                    success: function () {
                        self.render(collection,event.id);
                    }
                });
            } else {
                this.render(collection,event.id);
            }
        },

        render: function (collection,id) {
            var model = id ? collection.get(id) : new collection.model();
            if ( model ) {
                var partial = {fields:this.formFieldsPartials[collection.name]};
                var view = this.formViews[collection.name];
                this.formView = new view({model:model,collection:collection,template:formTemplate,formFieldsPartial:partial});
                this.$el.append(this.formView.el);
            } else {
                Backbone.Notifications.trigger(notes.SHOW_MESSAGE,{title:"Error",error:true,message:"Item with id "+id+" not found."});
            }
        }
    });
});


text:
{
  "name": "Templating: Custom Attributes",
  "culture": "en-US",
  "description": "An overview of the Aurelia templating engine's custom attribute functionality. Custom Attributes are used to add custom behaviors to DOM elements.",
  "engines" : { "aurelia-doc" : "^1.0.0" },
  "author": {
  	"name": "Ashley Grant",
  	"url": "http://www.ashleygrant.com"
  },
  "contributors": [],
  "translators": [],
  "keywords": ["JavaScript", "Templating", "Custom Attributes"]
}
---
## [Introduction](aurelia-doc://section/1/version/1.0.0)

Custom attributes are a category of view resource, just like value converters, binding behaviors and custom elements.  Custom attributes provide the ability to alter the behavior or add functionality to any DOM element.

Custom attributes may work by simply being added to a DOM element, or they may require that a value be set for the attribute. The value may be a simple value, or a complex set of options. These options may or may not be known when a custom attribute is developed. Aurelia provides simple APIs to create custom attributes of all of these types, while the Aurelia templating engine provides strong databinding capabilities for custom attributes.

Many custom attributes will work directly on the DOM element they are attached to. It is not necessary to search the DOM for the element a custom attribute is attached to. This is accomplished simply by requesting the element be injected into the attribute by Aurelia's Dependency Injection system. Simply request for an object of type `Element` to be injected in to your attribute. Aurelia will ensure you are provided with the DOM element the attribute has been attached to.

## [Simple Custom Attribute](aurelia-doc://section/2/version/1.0.0)

The simplest custom attribute to create is one that changes the behavior of an element merely by being added to the element. The following attribute will make an HTML element be displayed as a 100 pixel square with a red background.

  <source-code lang="ES 2015/2016">
    export class RedSquareCustomAttribute {
      static inject = [Element];

      constructor(element){
        this.element = element;
        this.element.style.width = this.element.style.height = '100px';
        this.element.style.backgroundColor = 'red';
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {autoinject} from 'aurelia-framework';

    @autoinject
    export class RedSquareCustomAttribute {
      constructor(private element: Element){
          this.element.style.width = this.element.style.height = '100px';
          this.element.style.backgroundColor = 'red';
      }
    }
  </source-code>

  <source-code lang="HTML">
    <template>
      <require from="./red-square"></require>

    </template>
  </source-code>

The attribute name is inferred via an Aurelia convention. This convention is `\${Name}CustomAttribute` for the ECMAScript class name. The class name is in "init caps" format. Aurelia converts this to "dash-case" format for use in HTML. Thus, `RedSquareCustomAttribute` becomes `red-square`.

## [Explicit Attribute Naming](aurelia-doc://section/3/version/1.0.0)

Overriding the default naming convention is possible by utilizing the `@customAttribute` decorator. Provide this decorator with the exact name for your attribute as below. Note that Aurelia does not convert from "init caps" to "dash-case" when using this decorator. It uses the exact value passed to the decorator.

  <source-code lang="ES 2015/ES 2016/TypeScript">
    import {customAttribute} from 'aurelia-framework';

    @customAttribute('red-square')
    export class MyClass {
      // implement custom element here
    }
  </source-code>

## [Single Value Binding](aurelia-doc://section/4/version/1.0.0)

Aurelia custom attributes support three different types of binding: single value binding, options binding, and dynamic options binding. The simplest of the three binding types is single value binding. Aurelia will automatically set the `value` property on the attribute's view-model. Note that this property is not set until databinding is complete. This means the `value` property will not be set in the custom attribute's constructor or in its `created` lifecycle event. It is available in the `bind` and later lifecycle events.

  <source-code lang="ES 2015/2016">
    export class SquareCustomAttribute {
      static inject = [Element];

      constructor(element){
        this.element = element;
        this.element.style.width = this.element.style.height = '100px';
      }

      bind() {
        this.element.style.backgroundColor = this.value;
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {autoinject} from 'aurelia-framework';

    @autoinject
    export class SquareCustomAttribute {
      constructor(private element: Element){
        this.element.style.width = this.element.style.height = '100px';
      }

      bind() {
        this.element.style.backgroundColor = this.value;
      }
    }
  </source-code>

  <source-code lang="HTML">
    <template>
      <require from="./square"></require>

    </template>
  </source-code>

Note that in the above code sample, the color of the square will not be updated, even if the bound value is changed. This is because the attribute is not notified when the `value` property changes. Aurelia can notify a custom attribute when its value has changed, via the `valueChanged(newValue, oldValue)` callback function. The `valueChanged` callback function, if implemented on the view-model, will be called whenever the attribute's value changes. This function has two optional parameters, `newValue` and `oldValue`. These parameters will be set to the new value of the attribute and old value of the attribute, respectively. The `value` property is still set by Aurelia even if the `valueChanged` function is implemented. Note that if you implement both the `bind` and `valueChanged` callbacks, only `bind` will be called when the value is initially bound. If you implement only the `valueChanged` function, then it will be called when the value is initially bound.

  <source-code lang="ES 2015/2016">
    export class SquareCustomAttribute {
      static inject = [Element];

      constructor(element){
        this.element = element;
        this.element.style.width = this.element.style.height = '100px';
      }

      valueChanged(newValue, oldValue){
        this.element.style.backgroundColor = newValue;
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {autoinject} from 'aurelia-framework';

    @autoinject
    export class SquareCustomAttribute {
      constructor(private element: Element){
        this.element.style.width = this.element.style.height = '100px';
      }

      valueChanged(newValue: string, oldValue: string){
        this.element.style.backgroundColor = newValue;
      }
    }
  </source-code>

  <source-code lang="HTML">
    <template>
      <require from="./square"></require>

      <input type="text" value.bind="color" />
    </template>
  </source-code>

When the user updates the value of the `color` property via the textbox, Aurelia will call the `valueChanged` method on the custom attribute to alert the custom attribute to the change.

## [Options Binding](aurelia-doc://section/5/version/1.0.0)

Options binding provides a custom attribute the ability to have multiple bindable properties. Each bindable property must be specified using the `bindable` decorator. The attribute view-model may implement an optional `\${propertyName}Changed(newValue, oldValue)` callback function for each bindable property. When binding to these options, separate each option with a semicolon and supply a binding command or literal value as in the example below. It is important to note that bindable properties are converted to dash-case when used in the DOM, while the VM property they are bound to are kept with their original casing.

  <source-code lang="ES 2015/2016">
    import {bindable, inject} from 'aurelia-framework';

    @inject(Element)
    export class SquareCustomAttribute {
      @bindable sideLength;
      @bindable color;

      constructor(element){
        this.element = element;
      }

      sideLengthChanged(newValue, oldValue){
        this.element.style.width = this.element.style.height = `${newValue}px`;
      }

      colorChanged(newValue, oldValue){
        this.element.style.backgroundColor = newValue;
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {bindable, autoinject} from 'aurelia-framework';

    @autoinject
    export class SquareCustomAttribute {
      @bindable sideLength: string;
      @bindable color: string;

      constructor(private element: Element){
      }

      sideLengthChanged(newValue:string, oldValue:string){
        this.element.style.width = this.element.style.height = `${newValue}px`;
      }

      colorChanged(newValue:string, oldValue:string){
        this.element.style.backgroundColor = newValue;
      }
    }
  </source-code>

  <source-code lang="HTML">
    <template>
      <require from="./square"></require>

    </template>
  </source-code>

## [Default Option](aurelia-doc://section/6/version/1.0.0)

A single bindable property can be made the default among all the options in an options binding.  Thus, when you use a custom attribute that would otherwise require using the options HTML syntax, and you want to provide a value or binding only for the default property, then you can use the simpler HTML syntax of a single value binding.

With options bindings each bindable property must be decorated with the `bindable` decorator.  To specify that you want a bindable property to be the default among all the other bindable properties, use the `primaryProperty` configuration parameter of the `bindable` decorator, as shown below:

  <source-code lang="ES 2015/2016">
    import {bindable, inject} from 'aurelia-framework';

    @inject(Element)
    export class SquareCustomAttribute {
      @bindable sideLength;
      @bindable({ primaryProperty: true }) color;

      constructor(element){
        this.element = element;
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {bindable, autoinject} from 'aurelia-framework';

    @autoinject
    export class SquareCustomAttribute {
      @bindable sideLength: string;
      @bindable color({ primaryProperty: true }): string;

      constructor(private element: Element){
      }
    }
  </source-code>

Then when you use the custom attribute, instead of this:

  <source-code lang="HTML">

 </source-code>

You can do this:

  <source-code lang="HTML">

</source-code>

Or if you don't care about binding, then this:

  <source-code lang="HTML">

</source-code>

## [Dynamic Options Binding](aurelia-doc://section/7/version/1.0.0)

Utilizing dynamic options, a custom attribute may deal with bindable properties where the name of the property is not known when creating the attribute. Simply decorate the attribute's view-model with the `dynamicOptions` decorator and implement the `propertyChanged(name, newValue, oldValue)` callback function. Aurelia will provide the name of the option that has changed along with new and old values for the option. Binding to a dynamic options attribute works exactly the same as binding to an options attribute in the DOM.

  <source-code lang="ES 2015/2016">
    import {dynamicOptions, inject} from 'aurelia-framework';

    @dynamicOptions
    @inject(Element)
    export class SquareCustomAttribute {
      constructor(element){
        this.element = element;
      }

      propertyChanged(name, newValue, oldValue){
        switch(name){
          case 'fill':
            this.element.style.backgroundColor = newValue;
            break;
          case 'size':
            this.element.style.width = this.element.style.height = `${newValue}px`;
            break;
          default:
            this.element.style[name] = value;
            break;
        }
      }
    }
  </source-code>
  <source-code lang="TypeScript">
    import {dynamicOptions, autoinject} from 'aurelia-framework';

    @dynamicOptions
    @autoinject
    export class RedSquareCustomAttribute {
      constructor(private element: Element){
      }

      propertyChanged(name: string, newValue: string, oldValue: string){
        switch(name){
          case 'fill':
            this.element.style.backgroundColor = newValue;
            break;
          case 'size':
            this.element.style.width = this.element.style.height = `${newValue}px`;
            break;
          default:
            this.element.style[name] = value;
            break;
        }
      }
    }
  </source-code>

  <source-code lang="HTML">
    <template>
      <require from="./square"></require>

    </template>
  </source-code>

## [Globally Accessible Custom Attributes](aurelia-doc://section/8/version/1.0.0)

In all of our examples, we've been using the `require` element to import custom attributes we need into our view.  There's an easier way.  If you have some commonly used custom attributes that you'd like to make globally available, use Aurelia's `globalResources` function to register them.  This will will eliminate the need for `require` elements at the top of every view.


text:
//package org.yarlithub.staff;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.test.context.ContextConfiguration;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//import org.springframework.test.context.transaction.TransactionConfiguration;
//import org.springframework.transaction.annotation.Transactional;
//import org.yarlithub.yschool.staff.api.StaffHandler;
//
//
///**
// * Created with IntelliJ IDEA.
// * User: Jay Krish
// * Date: 9/17/13
// * Time: 10:17 AM
// * To change this template use File | Settings | File Templates.
// */
//
//
//
//
//
//@ContextConfiguration(locations = {"/applicationContext.xml"})
//@RunWith(SpringJUnit4ClassRunner.class)
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
//public class StaffTest {
//
//    @Test
//    @Transactional
//    public void testTesting(){
//        StaffHandler staffHandler=new StaffHandler();
//        System.out.println(staffHandler.getTeacher(1,"CT"));
//    }
//
//}
//
//


text:
#pragma once

#include <ckm/ckm-type.h>

namespace CKM {

class OCSPLogic {
public:
    OCSPLogic();
    OCSPLogic(const OCSPLogic &) = delete;
    OCSPLogic(OCSPLogic &&) = delete;
    OCSPLogic& operator=(const OCSPLogic &) = delete;
    OCSPLogic& operator=(OCSPLogic &&) = delete;

    RawBuffer ocspCheck(int commandId, const RawBufferVector &rawChain, bool allowed);
    virtual ~OCSPLogic() {}

private:
    void setNetAvailable();
    bool m_isNetAvailable;
};
} // namespace CKM


text:
class UNIX_OSPFAreaConfigurationFixture :
	public CIMFixtureBase
{
public:
	UNIX_OSPFAreaConfigurationFixture();
	~UNIX_OSPFAreaConfigurationFixture();
	virtual void Run();

};


text:
<?php

namespace Prooph\Processing\Processor;

use Rhumsaa\Uuid\Uuid;

/**
 * Class ProcessId
 *
 * @package Prooph\Processing\Processor
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class ProcessId
{
    /**
     * @var Uuid
     */
    private $uuid;

    /**
     * @return ProcessId
     */
    public static function generate()
    {
        return new self(Uuid::uuid4());
    }

    /**
     * @param $uuid
     * @return ProcessId
     */
    public static function fromString($uuid)
    {
        return new self(Uuid::fromString($uuid));
    }

    /**
     * @param Uuid $uuid
     */
    private function __construct(Uuid $uuid)
    {
        $this->uuid = $uuid;
    }

    /**
     * @return string
     */
    public function toString()
    {
        return $this->uuid->toString();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * @param ProcessId $processId
     * @return bool
     */
    public function equals(ProcessId $processId)
    {
        return $this->uuid->equals($processId->uuid);
    }
}


text:
const analyzeMongoCollections = require('./mongo-collections-analyzer');
const analyzeSequelizeTables = require('./sequelize-tables-analyzer');
const EmptyDatabaseError = require('../../utils/errors/database/empty-database-error');
const { terminate } = require('../../utils/terminator');

async function reportEmptyDatabase(orm, dialect) {
  const logs = [`Your database looks empty! Please create some ${orm === 'mongoose' ? 'collections' : 'tables'} before running the command.`];
  if (orm === 'sequelize') {
    logs.push('If not, check whether you are using a custom database schema (use in that case the --schema option).');
  }
  return terminate(1, {
    logs,
    errorCode: 'database_empty',
    errorMessage: 'Your database is empty.',
    context: {
      orm,
      dialect,
    },
  });
}

function DatabaseAnalyzer(databaseConnection, config, allowWarning) {
  this.perform = async () => {
    let analyze;
    if (config.dbDialect === 'mongodb') {
      analyze = analyzeMongoCollections;
    } else {
      analyze = analyzeSequelizeTables;
    }
    return analyze(databaseConnection, config, allowWarning)
      .catch((error) => {
        if (error instanceof EmptyDatabaseError) {
          return reportEmptyDatabase(error.details.orm, error.details.dialect);
        }
        throw error;
      });
  };
}

module.exports = DatabaseAnalyzer;


text:
'use strict';

/**
 * Parameters supplied to update Identity Provider
 *
 */
class IdentityProviderUpdateParameters {
  /**
   * Create a IdentityProviderUpdateParameters.
   * @member {string} [type] Identity Provider Type identifier. Possible values
   * include: 'facebook', 'google', 'microsoft', 'twitter', 'aad', 'aadB2C'
   * @member {array} [allowedTenants] List of Allowed Tenants when configuring
   * Azure Active Directory login.
   * @member {string} [signupPolicyName] Signup Policy Name. Only applies to
   * AAD B2C Identity Provider.
   * @member {string} [signinPolicyName] Signin Policy Name. Only applies to
   * AAD B2C Identity Provider.
   * @member {string} [profileEditingPolicyName] Profile Editing Policy Name.
   * Only applies to AAD B2C Identity Provider.
   * @member {string} [passwordResetPolicyName] Password Reset Policy Name.
   * Only applies to AAD B2C Identity Provider.
   * @member {string} [clientId] Client Id of the Application in the external
   * Identity Provider. It is App ID for Facebook login, Client ID for Google
   * login, App ID for Microsoft.
   * @member {string} [clientSecret] Client secret of the Application in
   * external Identity Provider, used to authenticate login request. For
   * example, it is App Secret for Facebook login, API Key for Google login,
   * Public Key for Microsoft.
   */
  constructor() {
  }

  /**
   * Defines the metadata of IdentityProviderUpdateParameters
   *
   * @returns {object} metadata of IdentityProviderUpdateParameters
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'IdentityProviderUpdateParameters',
      type: {
        name: 'Composite',
        className: 'IdentityProviderUpdateParameters',
        modelProperties: {
          type: {
            required: false,
            serializedName: 'properties.type',
            type: {
              name: 'String'
            }
          },
          allowedTenants: {
            required: false,
            serializedName: 'properties.allowedTenants',
            constraints: {
              MaxItems: 32
            },
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          signupPolicyName: {
            required: false,
            serializedName: 'properties.signupPolicyName',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          signinPolicyName: {
            required: false,
            serializedName: 'properties.signinPolicyName',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          profileEditingPolicyName: {
            required: false,
            serializedName: 'properties.profileEditingPolicyName',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          passwordResetPolicyName: {
            required: false,
            serializedName: 'properties.passwordResetPolicyName',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          clientId: {
            required: false,
            serializedName: 'properties.clientId',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          },
          clientSecret: {
            required: false,
            serializedName: 'properties.clientSecret',
            constraints: {
              MinLength: 1
            },
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = IdentityProviderUpdateParameters;


text:
#include <stdio.h>

int main(int argc, char const *argv[])
{
	int distance = 100;

	//comments! woooo
	/* multi-line comments
	multi-line comments */
	printf("You are %d kilometres away\n", distance);
	return 0;
}