text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::Persistence::ClassMethods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            Module
            ActiveRecord::Persistence::ClassMethods

/Users/Bonobo/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/persistence.rb

Methods

C

                create,

                create!

I

                instantiate

Instance Public methods

              create(attributes = nil, &block)

            Link

Creates an object (or multiple objects) and saves it to the database, if
validations pass. The resulting object is returned whether the object was
saved successfully to the database or not.

The attributes parameter can be either a Hash or an Array
of Hashes. These Hashes describe the attributes on the objects that are to
be created.

Examples

# Create a single new object
User.create(first_name: 'Jamie')

# Create an Array of new objects
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(first_name: 'Jamie') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
  u.is_admin = false
end

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/persistence.rb, line 29
def create(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, &block) }
  else
    object = new(attributes, &block)
    object.save
    object
  end
end

              create!(attributes = nil, &block)

            Link

Creates an object (or multiple objects) and saves it to the database, if
validations pass. Raises a RecordInvalid error if validations fail,
unlike Base#create.

The attributes parameter can be either a Hash or an Array
of Hashes. These describe which attributes to be created on the object, or
multiple objects when given an Array of
Hashes.

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/persistence.rb, line 46
def create!(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create!(attr, &block) }
  else
    object = new(attributes, &block)
    object.save!
    object
  end
end

              instantiate(attributes, column_types = {})

            Link

Given an attributes hash, instantiate returns a new instance
of the appropriate class. Accepts only keys as strings.

For example, Post.all may return Comments, Messages, and
Emails by storing the record's subclass in a type
attribute. By calling instantiate instead of new,
finder methods ensure they get new instances of the appropriate class for
each record.

See +ActiveRecord::Inheritance#discriminate_class_for_record+ to see how
this "single-table" inheritance mapping is implemented.

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/persistence.rb, line 66
def instantiate(attributes, column_types = {})
  klass = discriminate_class_for_record(attributes)
  attributes = klass.attributes_builder.build_from_database(attributes, column_types)
  klass.allocate.init_with('attributes' => attributes, 'new_record' => false)
end


text:
package com.bericotech.clavin.gazetteer;

import static org.junit.Assert.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests to make sure GeoNames gazetteer records are properly parsed
 * into corresponding {@link BasicGeoName} objects.
 *
 */
public class BasicGeoNameTest {
    private static class GeoRecord {
        public final String gazetteerRecord;
        public final BasicGeoName geoName;

        public GeoRecord(final String gaz, final BasicGeoName geo) {
            this.gazetteerRecord = gaz;
            this.geoName = geo;
        }
    }

    private GeoRecord reston;
    private GeoRecord howzEHaji;
    private GeoRecord strabenhaus;
    private GeoRecord noMansLand;
    private GeoRecord chihuahuaDesert;
    private GeoRecord rasSalim;
    private GeoRecord murrayCanyon;
    private GeoRecord boston;
    private GeoRecord gunBarrelCity;
    private GeoRecord unitedStates;
    private GeoRecord fairfaxCounty;
    private GeoRecord virginia;
    private GeoRecord antarctica;
    private GeoRecord coralSeaIslands;
    private GeoRecord campoParish;
    private GeoRecord americanSamoa;
    private GeoRecord australia;

    @Before
    public void setUp() throws IOException {
        // load GeoNames.org sample data file & instantiate corresponding GeoName objects
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(
                new File("./src/test/resources/gazetteers/GeoNamesSampleSet.txt")), "UTF-8"));
        String line;
        List<GeoRecord> geoRecords = new ArrayList<GeoRecord>();
        while ((line = r.readLine()) != null) {
            geoRecords.add(new GeoRecord(line, (BasicGeoName) BasicGeoName.parseFromGeoNamesRecord(line)));
        }
        r.close();

        reston = geoRecords.get(0);
        howzEHaji = geoRecords.get(1);
        strabenhaus = geoRecords.get(2);
        noMansLand = geoRecords.get(3);
        chihuahuaDesert = geoRecords.get(4);
        rasSalim = geoRecords.get(5);
        murrayCanyon = geoRecords.get(6);
        boston = geoRecords.get(7);
        gunBarrelCity = geoRecords.get(8);
        unitedStates = geoRecords.get(9);
        fairfaxCounty = geoRecords.get(10);
        virginia = geoRecords.get(11);
        antarctica = geoRecords.get(12);
        coralSeaIslands = geoRecords.get(13);
        campoParish = geoRecords.get(14);
        americanSamoa = geoRecords.get(15);
        australia = geoRecords.get(16);
    }

    /**
     * Test all attributes for a standard US city.
     * @throws ParseException if an error occurs parsing the test date
     */
    @Test
    public void testAllAttributes() throws ParseException {
        GeoName restonGeo = reston.geoName;
        assertEquals("incorrect geonameID", 4781530, restonGeo.getGeonameID());
        assertEquals("incorrect name", "Reston", restonGeo.getName());
        assertEquals("incorrect asciiName", "Reston", restonGeo.getAsciiName());
        assertEquals("incorrect alternateNames", Arrays.asList("Reston","Рестон"), restonGeo.getAlternateNames());
        assertEquals("incorrect latitude", 38.96872, restonGeo.getLatitude(), 0.1);
        assertEquals("incorrect longitude", -77.3411, restonGeo.getLongitude(), 0.1);
        assertEquals("incorrect featureClass", FeatureClass.P, restonGeo.getFeatureClass());
        assertEquals("incorrect featureCode", FeatureCode.PPL, restonGeo.getFeatureCode());
        assertEquals("incorrect primaryCountryCode", CountryCode.US, restonGeo.getPrimaryCountryCode());
        assertEquals("incorrect primaryCountryName", CountryCode.US.name, restonGeo.getPrimaryCountryName());
        assertEquals("incorrect alternateCountryCodes", new ArrayList<CountryCode>(), restonGeo.getAlternateCountryCodes());
        assertEquals("incorrect adminCode1", "VA", restonGeo.getAdmin1Code());
        assertEquals("incorrect adminCode2", "059", restonGeo.getAdmin2Code());
        assertEquals("incorrect adminCode3", "", restonGeo.getAdmin3Code());
        assertEquals("incorrect adminCode4", "", restonGeo.getAdmin4Code());
        assertEquals("incorrect population", 58404, restonGeo.getPopulation());
        assertEquals("incorrect elevation", 100, restonGeo.getElevation());
        assertEquals("incorrect digitalElevationModel", 102, restonGeo.getDigitalElevationModel());
        assertEquals("incorrect timezone", TimeZone.getTimeZone("America/New_York"), restonGeo.getTimezone());
        assertEquals("incorrect modificationDate", new SimpleDateFormat("yyyy-MM-dd").parse("2011-05-14"), restonGeo.getModificationDate());
        assertEquals("incorrect gazetteer record", reston.gazetteerRecord, restonGeo.getGazetteerRecord());
        assertEquals("incorrect parent ancestry key", "US.VA.059", restonGeo.getParentAncestryKey());
        assertNull("ancestry key should be null", restonGeo.getAncestryKey());
    }

    /**
     * Test UTF characters and missing columns.
     */
    @Test
    public void testUTFAndMissingColumns() {
        GeoName howzEHajiGeo = howzEHaji.geoName;
        assertEquals("incorrect geonameID", 1139905, howzEHajiGeo.getGeonameID());
        assertEquals("incorrect name", "Ḩowẕ-e Ḩājī Bēg", howzEHajiGeo.getName());
        assertEquals("incorrect asciiName", "Howz-e Haji Beg", howzEHajiGeo.getAsciiName());
        assertEquals("incorrect alternateNames", Arrays.asList("Hawdze Hajibeg","Howz-e Haji Beg","Howz-e Hajjibeyg","H̱awdze Ḩājibeg","حوض حاجی بېگ","Ḩowẕ-e Ḩājjībeyg","Ḩowẕ-e Ḩājī Bēg"), howzEHajiGeo.getAlternateNames());
        assertEquals("incorrect latitude", 34.90489, howzEHajiGeo.getLatitude(), 0.1);
        assertEquals("incorrect longitude", 64.10312, howzEHajiGeo.getLongitude(), 0.1);
    }

    /**
     * Test seldom used fields.
     */
    @Test
    public void testSeldomUsedFields() {
        GeoName strabenhausGeo = strabenhaus.geoName;
        assertEquals("incorrect geonameID", 2826158, strabenhausGeo.getGeonameID());
        assertEquals("incorrect alternateNames", new ArrayList<String>(), strabenhausGeo.getAlternateNames());
        assertEquals("incorrect adminCode3", "07138", strabenhausGeo.getAdmin3Code());
        assertEquals("incorrect adminCode4", "07138071", strabenhausGeo.getAdmin4Code());
        assertEquals("incorrect ancestry key", "DE.08.00.07138.07138071", strabenhausGeo.getAncestryKey());
        assertEquals("incorrect parent ancestry key", "DE.08.00.07138", strabenhausGeo.getParentAncestryKey());
    }

    /**
     * Test no primary country code.
     */
    @Test
    public void testNoPrimaryCountryCode() {
        GeoName noMansLandGeo = noMansLand.geoName;
        assertEquals("incorrect primaryCountryCode", CountryCode.NULL, noMansLandGeo.getPrimaryCountryCode());
        assertNull("if no country code, ancestry path should be null", noMansLandGeo.getParentAncestryKey());
        assertTrue("ancestry should be resolved", noMansLandGeo.isAncestryResolved());
    }

    /**
     * Test non-empty alternate country codes.
     */
    @Test
    public void testNonEmptyAlternateCountryCodes() {
        assertEquals("incorrect alternateCountryCodes", Arrays.asList(CountryCode.US, CountryCode.MX),
                chihuahuaDesert.geoName.getAlternateCountryCodes());
    }

    /**
     * Test malformed alternate country codes.
     */
    @Test
    public void testMalformedAlternateCountryCodes() {
        assertEquals("incorrect alternateCountryCodes", Arrays.asList(CountryCode.PS),
                rasSalim.geoName.getAlternateCountryCodes());
    }

    /**
     * Test no feature code.
     */
    @Test
    public void testNoFeatureCode() {
        assertEquals("incorrect featureCode", FeatureCode.NULL, murrayCanyon.geoName.getFeatureCode());
        assertNotNull("parent ancestry key should not be null", murrayCanyon.geoName.getParentAncestryKey());
    }

    /**
     * Test ancestry keys for top-level administrative division.
     */
    @Test
    public void testTopLevelAncestryKeys() {
        assertEquals("incorrect ancestry key", "US", unitedStates.geoName.getAncestryKey());
        assertNull("parent ancestry key should be null", unitedStates.geoName.getParentAncestryKey());
    }

    /**
     * Test isTopLevelAdminDivision.
     */
    @Test
    public void testIsTopLevelAdminDivision() {
        assertFalse("[Gun Barrel City] is not a top level admin division", gunBarrelCity.geoName.isTopLevelAdminDivision());
        assertTrue("[Antarctica] is a top level admin division", antarctica.geoName.isTopLevelAdminDivision());
        assertTrue("[American Samoa] is a top level admin division", americanSamoa.geoName.isTopLevelAdminDivision());
        assertFalse("[Coral Sea Islands] is not a top level admin division", coralSeaIslands.geoName.isTopLevelAdminDivision());
        assertTrue("[United States] is a top level admin division", unitedStates.geoName.isTopLevelAdminDivision());
        assertFalse("[Virginia] is not a top level admin division", virginia.geoName.isTopLevelAdminDivision());
        assertFalse("[Campo] is not a top level admin division", campoParish.geoName.isTopLevelAdminDivision());
    }

    /**
     * Test isToplevelTerritory.
     */
    @Test
    public void testIsTopLevelTerritory() {
        assertFalse("Non-territory [Gun Barrel City] should not be a top level territory", gunBarrelCity.geoName.isTopLevelTerritory());
        assertTrue("[Antarctica] should be a top level territory", antarctica.geoName.isTopLevelTerritory());
        assertTrue("[American Samoa] should be a top level territory", americanSamoa.geoName.isTopLevelTerritory());
        assertFalse("[Coral Sea Islands] should not be a top level territory", coralSeaIslands.geoName.isTopLevelTerritory());
    }

    /**
     * Test correct ancestry keys for territories.
     */
    @Test
    public void testTerritoryAncestryKeys() {
        assertEquals("incorrect ancestry key for top-level territory", "AQ", antarctica.geoName.getAncestryKey());
        assertNull("parent ancestry key of top-level territory should be null", antarctica.geoName.getParentAncestryKey());

        assertEquals("incorrect ancestry key for top-level territory", "AS", americanSamoa.geoName.getAncestryKey());
        assertNull("parent ancestry key of top-level territory should be null", americanSamoa.geoName.getParentAncestryKey());

        assertNull("ancestry key for non-top-level territory should be null", coralSeaIslands.geoName.getAncestryKey());
        assertEquals("incorrect parent ancestry key for non-top-level territory", "AU", coralSeaIslands.geoName.getParentAncestryKey());
    }

    /**
     * Test correct ancestry keys for parishes.
     */
    @Test
    public void testParishAncestryKeys() {
        assertNull("ancestry key for parish should be null", campoParish.geoName.getAncestryKey());
        assertEquals("incorrect parent ancestry key for parish", "ES", campoParish.geoName.getParentAncestryKey());
    }

    /**
     * Test ancestry resolution check when no parents are resolved.
     */
    @Test
    public void testIsAncestryResolved_NoParents() {
        // verify correct resolution response when no parents are set
        assertFalse("no parent set [reston], should not be resolved", reston.geoName.isAncestryResolved());
        assertFalse("no parent set [fairfax county], should not be resolved", fairfaxCounty.geoName.isAncestryResolved());
        assertFalse("no parent set [virginia], should not be resolved", virginia.geoName.isAncestryResolved());
        assertTrue("no parent set [united states] but top level, should be resolved", unitedStates.geoName.isAncestryResolved());
        assertTrue("no parent set [american samoa] but top level, should be resolved", americanSamoa.geoName.isAncestryResolved());
        assertFalse("no parent set [coral sea islands], should not be resolved", coralSeaIslands.geoName.isAncestryResolved());
    }

    /**
     * Test ancestry resolution when only part of the ancestry is resolved.
     */
    @Test
    public void testIsAncestryResolved_PartialResolution() {
        GeoName restonGeo = reston.geoName;
        BasicGeoName fairfaxCountyGeo = fairfaxCounty.geoName;
        BasicGeoName virginiaGeo = virginia.geoName;
        restonGeo.setParent(fairfaxCountyGeo);
        assertFalse("only one parent set [reston], should not be resolved", restonGeo.isAncestryResolved());
        fairfaxCountyGeo.setParent(virginiaGeo);
        assertFalse("only two parents set [reston], should not be resolved", restonGeo.isAncestryResolved());
        assertFalse("only one parent set [fairfax county], should not be resolved", fairfaxCountyGeo.isAncestryResolved());
    }

    /**
     * Test ancestry resolution when all ancestry is resolved.
     */
    @Test
    public void testIsAncestryResolved_FullResolution() {
        GeoName restonGeo = reston.geoName;
        BasicGeoName fairfaxCountyGeo = fairfaxCounty.geoName;
        BasicGeoName virginiaGeo = virginia.geoName;
        BasicGeoName unitedStatesGeo = unitedStates.geoName;
        GeoName coralSeaIslandsGeo = coralSeaIslands.geoName;

        virginiaGeo.setParent(unitedStatesGeo);
        fairfaxCountyGeo.setParent(virginiaGeo);
        restonGeo.setParent(fairfaxCountyGeo);
        assertTrue("[reston] should be fully resolved", restonGeo.isAncestryResolved());
        assertTrue("[fairfax county] should be fully resolved", fairfaxCountyGeo.isAncestryResolved());
        assertTrue("[virginia] should be fully resolved", virginiaGeo.isAncestryResolved());
        assertTrue("[united states] should be fully resolved", unitedStatesGeo.isAncestryResolved());
        assertEquals("incorrect gazetteer records with ancestry", String.format("%s\n%s\n%s\n%s", reston.gazetteerRecord,
                fairfaxCounty.gazetteerRecord, virginia.gazetteerRecord, unitedStates.gazetteerRecord),
                restonGeo.getGazetteerRecordWithAncestry());

        coralSeaIslandsGeo.setParent(australia.geoName);
        assertTrue("[coral sea islands] should be fully resolved", coralSeaIslandsGeo.isAncestryResolved());
    }

    /**
     * Test invalid parent configuration.
     */
    @Test
    public void testSetParent_InvalidParent() {
        BasicGeoName restonGeo = reston.geoName;

        assertNull("[reston] should have no parent", restonGeo.getParent());
        assertFalse("non-administrative parent should not be allowed", restonGeo.setParent(boston.geoName));
        assertNull("[reston] should have no parent", restonGeo.getParent());
        assertTrue("non-direct parent should be allowed", restonGeo.setParent(virginia.geoName));
        assertEquals("[reston] should have parent [virginia]", virginia.geoName, restonGeo.getParent());
        assertFalse("unrelated parent should not be allowed", restonGeo.setParent(australia.geoName));
        assertEquals("[reston] should have parent [virginia]", virginia.geoName, restonGeo.getParent());
        assertTrue("direct parent should be allowed", restonGeo.setParent(fairfaxCounty.geoName));
        assertEquals("[reston] should have parent [fairfax county]", fairfaxCounty.geoName, restonGeo.getParent());
        assertFalse("null parent should result in a no-op", restonGeo.setParent(null));
        assertEquals("[reston] should have parent [fairfax county]", fairfaxCounty.geoName, restonGeo.getParent());
        assertFalse("cannot set parent to self", restonGeo.setParent(restonGeo));
        assertEquals("[reston] should have parent [fairfax county]", fairfaxCounty.geoName, restonGeo.getParent());
    }

    /**
     * Parse a "bad" gazetteer record to make sure exceptions are
     * properly caught and handled.
     *
     * @throws IOException
     * @throws ParseException
     */
    @Test
    public void testParseExceptions() throws IOException, ParseException {
        BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(
                new File("./src/test/resources/gazetteers/BadGeoNamesSample.txt")), "UTF-8"));
        String line;
        List<GeoName> geonames = new ArrayList<GeoName>();
        while ((line = r.readLine()) != null)
            geonames.add(BasicGeoName.parseFromGeoNamesRecord(line));
        r.close();

        // if no exceptions are thrown, the test is assumed to have succeeded
    }

}

redpajama_set_name: RedPajamaGithub


text:
from py2neo import Node, Relationship, cast, cast_node, cast_relationship, remote
from test.util import GraphTestCase

def assert_node(node, *labels, **properties):
    assert isinstance(node, Node)
    assert set(node.labels()) == set(labels)
    assert dict(node) == properties

class GraphyCastTestCase(GraphTestCase):

    def test_cast(self):
        assert cast(None) is None

    def test_can_cast_node(self):
        alice = Node(name="Alice")
        self.graph.create(alice)
        casted = cast(alice)
        assert isinstance(casted, Node)
        assert remote(casted)
        assert casted["name"] == "Alice"

    def test_can_cast_dict(self):
        casted = cast({"name": "Alice"})
        assert isinstance(casted, Node)
        assert not remote(casted)
        assert casted["name"] == "Alice"

    def test_can_cast_rel(self):
        a = Node()
        b = Node()
        ab = Relationship(a, "KNOWS", b)
        self.graph.create(ab)
        casted = cast(ab)
        assert isinstance(casted, Relationship)
        assert remote(casted)
        assert casted.start_node() == a
        assert casted.type() == "KNOWS"
        assert casted.end_node() == b

    def test_can_cast_3_tuple(self):
        alice = Node()
        bob = Node()
        casted = cast((alice, "KNOWS", bob))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() is alice
        assert casted.type() == "KNOWS"
        assert casted.end_node() is bob

    def test_can_cast_4_tuple(self):
        alice = Node()
        bob = Node()
        casted = cast((alice, "KNOWS", bob, {"since": 1999}))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() is alice
        assert casted.type() == "KNOWS"
        assert casted.end_node() is bob
        assert casted["since"] == 1999

class NodeCastTestCase(GraphTestCase):

    def test_cast_node(self):
        alice = Node("Person", "Employee", name="Alice", age=33)
        assert cast_node(None) is None
        assert cast_node(alice) is alice
        assert_node(cast_node("Person"), "Person")
        assert_node(cast_node({"name": "Alice"}), name="Alice")
        assert_node(cast_node(("Person", "Employee", {"name": "Alice", "age": 33})),
                    "Person", "Employee", name="Alice", age=33)
        with self.assertRaises(TypeError):
            cast_node(3.14)

class RelationshipCastTestCase(GraphTestCase):

    def test_can_cast_relationship(self):
        a = Node()
        b = Node()
        ab = Relationship(a, "KNOWS", b)
        self.graph.create(a | b | ab)
        casted = cast_relationship(ab)
        assert isinstance(casted, Relationship)
        assert remote(casted)
        assert casted.start_node() == a
        assert casted.type() == "KNOWS"
        assert casted.end_node() == b

    def test_cannot_cast_0_tuple(self):
        with self.assertRaises(TypeError):
            cast_relationship(())

    def test_cannot_cast_1_tuple(self):
        with self.assertRaises(TypeError):
            cast_relationship(("Alice",))

    def test_cannot_cast_2_tuple(self):
        with self.assertRaises(TypeError):
            cast_relationship(("Alice", "KNOWS"))

    def test_can_cast_3_tuple(self):
        alice = Node()
        bob = Node()
        casted = cast_relationship((alice, "KNOWS", bob))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() == alice
        assert casted.type() == "KNOWS"
        assert casted.end_node() == bob

    def test_can_cast_3_tuple_with_unbound_rel(self):
        alice = Node()
        bob = Node()
        casted = cast_relationship((alice, ("KNOWS", {"since": 1999}), bob))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() == alice
        assert casted.type() == "KNOWS"
        assert casted.end_node() == bob
        assert casted["since"] == 1999

    def test_can_cast_4_tuple(self):
        alice = Node()
        bob = Node()
        casted = cast_relationship((alice, "KNOWS", bob, {"since": 1999}))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() == alice
        assert casted.type() == "KNOWS"
        assert casted.end_node() == bob
        assert casted["since"] == 1999

    def test_cannot_cast_6_tuple(self):
        with self.assertRaises(TypeError):
            cast_relationship(("Alice", "KNOWS", "Bob", "foo", "bar", "baz"))

    def test_can_cast_from_tuple_of_entities(self):
        a = Node()
        b = Node()
        r = Relationship(a, "TO", b)
        casted = cast_relationship((a, r, b))
        assert isinstance(casted, Relationship)
        assert not remote(casted)
        assert casted.start_node() == a
        assert casted.type() == "TO"
        assert casted.end_node() == b

    def test_can_cast_relationship_with_integer_nodes(self):
        a = Node()
        b = Node()
        nodes = [a, b]
        r = cast_relationship((0, "TO", 1), nodes)
        assert r.start_node() is a
        assert r.end_node() is b
        assert r.type() == "TO"

    def test_cannot_cast_relationship_from_generic_object(self):
        class Foo(object):
            pass
        foo = Foo()
        with self.assertRaises(ValueError):
            cast_relationship((Node(), foo, Node()))

    def test_cannot_cast_relationship_from_generic_object_with_properties(self):
        class Foo(object):
            pass
        foo = Foo()
        foo.properties = {}
        with self.assertRaises(ValueError):
            cast_relationship((Node(), foo, Node()))


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.FindReferences
{
    using Workspace = Microsoft.CodeAnalysis.Workspace;

    [ExportWorkspaceService(typeof(IDefinitionsAndReferencesFactory), ServiceLayer.Desktop), Shared]
    internal class VisualStudioDefinitionsAndReferencesFactory
        : DefaultDefinitionsAndReferencesFactory
    {
        private readonly IServiceProvider _serviceProvider;

        [ImportingConstructor]
        public VisualStudioDefinitionsAndReferencesFactory(SVsServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public override DefinitionItem GetThirdPartyDefinitionItem(
            Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken)
        {
            var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>();
            if (!symbolNavigationService.WouldNavigateToSymbol(
                    definitionItem, solution, cancellationToken,
                    out var filePath, out var lineNumber, out var charOffset))
            {
                return null;
            }

            var displayParts = GetDisplayParts(filePath, lineNumber, charOffset);
            return new ExternalDefinitionItem(
                definitionItem.Tags, displayParts,
                _serviceProvider, filePath, lineNumber, charOffset);
        }

        private ImmutableArray<TaggedText> GetDisplayParts(
            string filePath, int lineNumber, int charOffset)
        {
            var builder = ImmutableArray.CreateBuilder<TaggedText>();

            var sourceLine = GetSourceLine(filePath, lineNumber).Trim(' ', '\t');

            // Put the line in 1-based for the presentation of this item.
            var formatted = $"{filePath} - ({lineNumber + 1}, {charOffset + 1}) : {sourceLine}";

            return ImmutableArray.Create(new TaggedText(TextTags.Text, formatted));
        }

        private string GetSourceLine(string filePath, int lineNumber)
        {
            using (var invisibleEditor = new InvisibleEditor(
                _serviceProvider, filePath, projectOpt: null, needsSave: false, needsUndoDisabled: false))
            {
                var vsTextLines = invisibleEditor.VsTextLines;
                if (vsTextLines != null &&
                    vsTextLines.GetLengthOfLine(lineNumber, out var lineLength) == VSConstants.S_OK &&
                    vsTextLines.GetLineText(lineNumber, 0, lineNumber, lineLength, out var lineText) == VSConstants.S_OK)
                {
                    return lineText;
                }

                return ServicesVSResources.Preview_unavailable;
            }
        }

        private class ExternalDefinitionItem : DefinitionItem
        {
            private readonly IServiceProvider _serviceProvider;
            private readonly string _filePath;
            private readonly int _lineNumber;
            private readonly int _charOffset;

            internal override bool IsExternal => true;

            public ExternalDefinitionItem(
                ImmutableArray<string> tags,
                ImmutableArray<TaggedText> displayParts,
                IServiceProvider serviceProvider,
                string filePath,
                int lineNumber,
                int charOffset)
                : base(tags, displayParts, ImmutableArray<TaggedText>.Empty,
                       originationParts: default,
                       sourceSpans: default,
                       properties: null,
                       displayIfNoReferences: true)
            {
                _serviceProvider = serviceProvider;
                _filePath = filePath;
                _lineNumber = lineNumber;
                _charOffset = charOffset;
            }

            public override bool CanNavigateTo(Workspace workspace) => true;

            public override bool TryNavigateTo(Workspace workspace, bool isPreview)
            {
                return TryOpenFile() && TryNavigateToPosition();
            }

            private bool TryOpenFile()
            {
                var shellOpenDocument = (IVsUIShellOpenDocument)_serviceProvider.GetService(typeof(SVsUIShellOpenDocument));
                var textViewGuid = VSConstants.LOGVIEWID.TextView_guid;
                if (shellOpenDocument.OpenDocumentViaProject(
                        _filePath, ref textViewGuid, out var oleServiceProvider,
                        out var hierarchy, out var itemid, out var frame) == VSConstants.S_OK)
                {
                    frame.Show();
                    return true;
                }

                return false;
            }

            private bool TryNavigateToPosition()
            {
                IVsRunningDocumentTable docTable = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));
                if (docTable.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, _filePath,
                        out var hierarchy, out var itemid, out var bufferPtr, out var cookie) != VSConstants.S_OK)
                {
                    return false;
                }

                try
                {
                    var lines = Marshal.GetObjectForIUnknown(bufferPtr) as IVsTextLines;
                    if (lines == null)
                    {
                        return false;
                    }

                    var textManager = (IVsTextManager)_serviceProvider.GetService(typeof(SVsTextManager));
                    if (textManager == null)
                    {
                        return false;
                    }

                    return textManager.NavigateToLineAndColumn(
                        lines, VSConstants.LOGVIEWID.TextView_guid,
                        _lineNumber, _charOffset,
                        _lineNumber, _charOffset) == VSConstants.S_OK;
                }
                finally
                {
                    if (bufferPtr != IntPtr.Zero)
                    {
                        Marshal.Release(bufferPtr);
                    }
                }
            }
        }
    }
}


text:
title: Lambda Jam
logo: /resources/img/devoxx.png
location: Antwerp
description: We code in peace
start: 11 November 2013
end: 15 November 2013
link-out: http://www.devoxx.com/
---


text:
let soap = require('soap')
let ServiceSchema = require('./service-schema').default

function DFPService(name, clientOptions, authClient) {
  this.options = clientOptions
  this.dfpAuthClient = authClient
  this.dfpSoapClient = null
  this.serviceName = name
  this.service = null
  this._authTokens = null
  this._fetchTokens = null

  this.ready = new Promise((resolve, reject) => {
    this.getService(name).then(({ service: svcInterface, client }) => {
      this.service = svcInterface
      this.dfpSoapClient = client
      this.serviceSchema = new ServiceSchema(name, client)
      resolve(svcInterface)
    }).catch(err => {
      if (/Invalid WSDL URL/i.test(err.message) || /Code:\s*404/i.test(err.message)) {
        err = new Error(`Invalid service name '${name}': ${err.message.split('\n')[0]}`)
      }
      reject(err)
    })
  })

  let self = this
  return Object.create(new Proxy(this, {
    get(target, name) {
      if (name in target) {
        return target[name]
      }

      let returnFn = function(args, callback, options) {
        if (!args) {
          args = {}
        }

        return new Promise((resolve, reject) => {
          self.ready.then(service => {
            if (!service[name]) {
              throw new Error(`${self.serviceName} does not have a method named '${name}'`)
            }

            if (self.options.immutable && /(create|update|delete|action)/i.test(name)) {
              throw new Error(`Operation '${self.serviceName}.${name}()' is not permitted. Mutation is disabled from this instance.`)
            }

            service[name](self.serviceSchema.mapCall(name, args), (err, result) => {
              let logRequest = self.options.logRequest
              let logResponse = self.options.logResponse
              if (err && self.options.logXmlOnError) {
                logRequest = true
                logResponse = true
              }

              if (logRequest) {
                let msg = `XML of last request to ${self.serviceName}::${name}()`
                let dashes = (new Array(msg.length + 1)).join('-')
                console.log(`${msg}\n${dashes}\n${self.dfpSoapClient.lastRequest}\n`)
              }

              if (logResponse) {
                let msg = `XML of last response from ${self.serviceName}::${name}()`
                let dashes = (new Array(msg.length + 1)).join('-')
                console.log(`${msg}\n${dashes}\n${self.dfpSoapClient.lastResponse}\n`)
              }

              if (err) {
                err.lastRequestXML = self.dfpSoapClient.lastRequest
                err.lastResponseXML = self.dfpSoapClient.lastResponse
                reject(err)
              } else {
                resolve(result)
              }
            }, options)
          }).catch(reject)
        })
      }

      returnFn.getSchema = self.getOpSchema.bind(self, name)

      Object.defineProperty(returnFn, 'name', { value: name })
      return returnFn
    }
  }))
}

Object.assign(DFPService.prototype, {
  getRawService() {
    return this.ready
  },

  getTypeSchema(type) {
    let typeParts = this.serviceSchema.parseType(type)
    return this.serviceSchema.getType(typeParts.type, typeParts.prefix)
  },

  getOpSchema(op) {
    if (!this.serviceSchema.interface[op]) {
      throw new Error(`Invalid op name '${op}'. Has the service finished loading yet?`)
    }
    return this.serviceSchema.interface[op]
  },

  _getAuthTokens() {
    // The default ttl for the tokens appears to be an hour. To avoid problems caused by clock skew we'll just
    // go ahead and refresh the tokens if we're within 5 minutes of the expiry time.
    let ttl = this._authTokens ? this._authTokens.expiry_date - Date.now() : 0
    if (!this._fetchTokens || ttl < 300000) {
      this._fetchTokens = new Promise((resolve, reject) => {
        this.dfpAuthClient.authorize((err, tokens) => {
          if (err) {
            reject(err)
          } else {
            this._authTokens = tokens
            resolve(tokens)
          }
        })
      })
    }

    return this._fetchTokens
  },

  _getServiceMethod(interfacePort, method) {
    return (args, callback, options, extraHeaders) => {
      this._getAuthTokens().then(tokens => {
        extraHeaders = Object.assign({
          Authorization: `${tokens.token_type} ${tokens.access_token}`
        }, extraHeaders || {})
        interfacePort[method].call(interfacePort, args, callback, options, extraHeaders)
      }).catch(callback)
    }
  },

  getService(service) {
    return new Promise((resolve, reject) => {
      let opts = this.options
      let baseUrl = 'https://ads.google.com/apis/ads/publisher'
      let wsdlUrl = `${baseUrl}/${opts.apiVersion}/${service}?wsdl`

      let client = soap.createClient(wsdlUrl, (err, client) => {
        if (err) {
          return reject(err)
        }

        client.addSoapHeader({
          RequestHeader: {
            attributes: {
              'soapenv:actor'           : 'http://schemas.xmlsoap.org/soap/actor/next',
              'soapenv:mustUnderstand'  : 0,
              'xsi:type'                : 'ns1:SoapRequestHeader',
              'xmlns:ns1'               : `https://www.google.com/apis/ads/publisher/${opts.apiVersion}`,
              'xmlns:xsi'               : 'http://www.w3.org/2001/XMLSchema-instance',
              'xmlns:soapenv'           : 'http://schemas.xmlsoap.org/soap/envelope/'
            },
            'ns1:networkCode'     : opts.networkCode,
            'ns1:applicationName' : opts.propertyCode
          }
        })

        let serviceApi = {}
        let interfacePort = client[service][`${service}InterfacePort`]
        for (let method in interfacePort) {
          if (interfacePort.hasOwnProperty(method)) {
            if (typeof interfacePort[method] === 'function') {
              serviceApi[method] = this._getServiceMethod(interfacePort, method)
            }
          }
        }

        resolve({ service: serviceApi, client })
      })
    })
  }
})

module.exports = DFPService


text:
package org.jboss.arquillian.container.spi.context;

import org.jboss.arquillian.core.spi.context.IdBoundContext;

/**
 * ContainerContext
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
public interface ContainerContext extends IdBoundContext<String>
{

}


text:
#include <gtest/gtest.h>

#include <qi/application.hpp>

#include <qi/anyobject.hpp>
#include <qi/session.hpp>
#include <qi/anymodule.hpp>

qi::SessionPtr session;
TEST(Module, Load)
{
  session->loadService("naoqi.testanymodule.test");

  qi::AnyObject o = session->service("test");
  ASSERT_TRUE(o);
  int res = o.call<int>("testMethod", 12);
  ASSERT_EQ(13, res);
}

TEST(Module, LoadByHandWithSession)
{
  qi::AnyModule foomod = qi::import("naoqi.testanymodulesession");
  qi::AnyObject ao = foomod.call<qi::AnyObject>("Foo", session);
  session->registerService("Foo", ao);
  int res = ao.call<int>("bar");

  ASSERT_EQ(42, res);
}

TEST(Module, LoadWithSessionAndRename)
{
  //## register the Foo object as a service
  session->loadService("naoqi.testanymodulesession.Foo", "Bar");

  qi::AnyObject o = session->service("Bar");
  ASSERT_TRUE(o);
  int res = o.call<int>("bar");

  ASSERT_EQ(42, res);
}

int main(int argc, char **argv) {
  qi::Application app(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  session = qi::makeSession();

  session->listenStandalone("tcp://127.0.0.1:0");
  int res = RUN_ALL_TESTS();
  session->close();
  return res;
}


text:
class CalState {
  constructor(label) {
    this.date = new Date();
    this.year = this.date.getFullYear();
    this.refDate = new Date(this.year, 0, 1);
    this.month = {
      name: label,
      number: [],
      days: [],
      day: [],
      monthCellLayout: [],
    };
    this.dayName = [];
  }
  init() {
    this.year = this.date.getFullYear();
  }
  setArrays() {
    for (let m = 0; m < 12; m += 1) {
      this.month.monthCellLayout.push([]);
      this.month.number.push(m);
      this.month.days.push([]);
      this.month.day.push([]);
      this.dayName.push([]);
    }
  }
}

const monthArr = ['Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
const dayInMonthArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const weekArr = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
const weekArrSrt = ['L', 'M', 'M', 'J', 'V', 'S', 'D'];
const hoursArr = [];

// cycle elements wen out of range
const cycle = (elem, range) => {
  if (elem > range) {
    return (elem % range);
  }
  return elem;
};

// iteration variables;
let i = 0;
let j = 0;
let k = 0;
// let l = 0;
let count = 0;

// initiating the hours array
for (i = 0; i < 24; i += 1) {
  hoursArr.push(`${i}h`);
}

// the calendar object instence recipient
let calInstance = {};

// create a new calendar object
const calStateInit = function populateCurrentYearState() {
  calInstance = new CalState(monthArr);
  calInstance.setArrays();
};

// clearing the dom element
const clear = function clearTheDom(elemToClear) {
  let elMac = elemToClear;
  const newBoxMac = elMac.cloneNode(false);
  elMac.parentNode.replaceChild(newBoxMac, elMac);
  elMac = newBoxMac;
};

// Check for leap year and adjust feb days
const leapCheck = function checkForLeapYear(check) {
  if (check === 1) {
    if (
      (calLib.year % 4 === 0 && calLib.year % 100 !== 0) ||
      calLib.year % 400 === 0) {
      dayInMonthArray[1] = 29;
    } else {
      dayInMonthArray[1] = 28;
    }
  }
};

const populate = function initAndAssignFullCalendar() {
  // shorthands
  const mLayout = calInstance.month.monthCellLayout;
  const days = calInstance.month.days;
  const day = calInstance.month.day;
  const dayName = calInstance.dayName;
  const year = calInstance.year;

  // set the year dynamicly
  calInstance.refDate.setFullYear(calInstance.year + count);

  j = 0;

  // set up the arrays in the month (12 arrays of days/names/day)
  calInstance.month.name.map(
    () => {
      leapCheck(1);

      // setup the arrays
      calInstance.refDate.setMonth(j);
      calInstance.refDate.setDate(0);
      days[j].push([]);
      day[j].push([]);
      dayName[j].push([]);

      for (i = 0; i < (dayInMonthArray[j]); i += 1) {
        // increment the reference day
        calInstance.refDate.setDate(i + 1);
        // set the date's digit of the current day
        days[j][i] = i + 1;
        // set the day of the week of the current day
        day[j][i] = calInstance.refDate.getDay();
        // set the label of the current day
        dayName[j][i] = weekArr[calInstance.refDate.getDay()];
      }

      const startingDate = day[j][0];

      let digit = 0;
      // for (k = 0; k < 40; k += 1) {
      //   // check month for congruence
      //   switch (true) {
      //     // where k goes over the max # of days in the current month
      //     case (k > (dayInMonthArray[j] - (startingDate))):
      //       if (j === 11) {
      //         digit = days[0][(k - dayInMonthArray[11]) - (startingDate + 1)];
      //         digit = k;
      //       } else {
      //         digit = days[(j + 1)][0];
      //         console.log(days[(j + 1)][1]);
      //       }
      //       break;
      //     // where the first day to display is from the previous month
      //     // case ((startingDate + 1) > k):
      //     //   if (j === 0) {
      //     //     digit = days[11][(dayInMonthArray[11] - (startingDate)) + k];
      //     //   } else {
      //     //     digit = days[j - 1][(dayInMonthArray[j - 1] - (startingDate)) + k];
      //     //   }
      //     //   break;
      //     default:
      //     //   digit = days[j][k - (startingDate)];
      //   }
        // mLayout[j].push(digit);
      // }

      j += 1;
      return calInstance;
    }
  );
};

const renderY = function renderTheFullYear({ titleElemSup, contentElemSup }) {
  // shorthands
  const mLayout = calInstance.month.monthCellLayout;

  // reset iterators
  j = 0;
  k = 0;

  // append the year to the title bar
  $(titleElemSup).append(calInstance.year);

  // append the months
  monthArr.map(
    (x) => {
      // append the months name and prepare the dom for the rest
      $(contentElemSup).append(`<div class="monthCell"><p>${x}</p><div class="dayLabels"></div><div class="dayDigits"></div></div>`);

      // append the day shorthand to the calendar
      weekArrSrt.map(
        (y) => {
          $('.dayLabels').eq(j + 1).append(`<div>${y}</div>`);
          return weekArrSrt;
        }
      );

      // append the date to the calendar
      mLayout[j].map(
        (z) => {
          $('.dayDigits').eq(j + 1).append(`<div>${z}</div>`);
          return mLayout[j];
        }
      );
      j += 1;
      return monthArr;
    }
  );
};

const build = function initiatAndRenderDocument({ title, content }) {
  calStateInit();
  leapCheck();
  populate();
  renderY({ titleElemSup: title, contentElemSup: content });
};

const yearView = function initAndDisplayFullYear({ titleElemSup, contentElemSup }) {
  // reset the dom
  clear(titleElemSup);
  clear(contentElemSup);
};

const monthView = function initAndDisplayMonth({ titleElemSup, contentElemSup }) {
  // reset the dom
  clear(titleElemSup);
  clear(contentElemSup);
};

// counter management
const countUp = function setYearCounterUp() {
  count += 1;
};
const countDown = function setYearCounterDown() {
  count -= 1;
};
build({ title: '#macroContent', content: '#microContent' });

// trigger year mode on click
$('#yearButton').listen('click', () => { yearView({ titleElemSup: '#macroContent', contentElemSup: '#microContent' }); });

// trigger month mode on click
$('#monthButton').listen('click', () => { monthView({ titleElemSup: '#macroContent', contentElemSup: '#microContent' }); });

// cycle year/month on click
$('#prev').listen('click', () => { countDown(); });
$('#next').listen('click', () => { countUp(); });
// default view
// yearView({ titleElemSup: '#macroContent', contentElemSup: '#microContent' });

const calLib = [];

const ref = new Date();

function dateFull() {
  const theDate = new Date();
  theDate.setFullYear(theDate.getFullYear());
  theDate.setMonth(0);
  theDate.setDate(1);

  for (i = 0; i < 60; i += 1) {
    // populate the array with objects at date -/+ 30
    calLib.push({
      date: new Date(((ref.getFullYear() - 30) + i), 0, 1),
      year: this.date.getFullYear(),
      days: [],
      day: [],
      dayName: [],
    });
  }
  calLib.map(
    (x) => {
      // check for leap year
      if (
        (x.year % 4 === 0 && x.year % 100 !== 0) ||
        x.year % 400 === 0) {
        dayInMonthArray[1] = 29;
      } else {
        dayInMonthArray[1] = 28;
      }

      for (j = 0; j < 12; j += 1) {
        x.date.setMonth(j);
        for (i = 0; i < dayInMonthArray[j]; i += 1) {
          // increment the reference day
          x.date.setDate(i + 1);
          // set the date's digit of the current day
          x.days[j].push(i + 1);
          // set the day of the week of the current day
          x.day[j].push(x.date.getDay());
          // set the label of the current day
          x.dayName[j].push(weekArr[x.date.getDay()]);
        }
      }
      return calLib;
    }
  );
  // calLib.map(
  //   (a) => {
  //     j = 0;
  //     dayInMonthArray.map(
  //       (x) => {
  //
  //         j += 1;
  //         return dayInMonthArray;
  //       }
  //     );
  //     i += 1;
  //     return calLib;
  //   }
  // );

  console.log(calLib);
}

// instaurer un system de conteur, start a la moitier de l'echelle du calendrier et permet de choisir l'année voulue

dateFull();


text:
package org.apache.karaf.management.internal;

import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.karaf.jaas.config.KeystoreInstance;
import org.apache.karaf.jaas.config.KeystoreManager;
import org.apache.karaf.management.ConnectorServerFactory;
import org.apache.karaf.management.JaasAuthenticator;
import org.apache.karaf.management.KarafMBeanServerGuard;
import org.apache.karaf.management.MBeanServerFactory;
import org.apache.karaf.management.RmiRegistryFactory;
import org.apache.karaf.util.tracker.BaseActivator;
import org.apache.karaf.util.tracker.annotation.Managed;
import org.apache.karaf.util.tracker.annotation.ProvideService;
import org.apache.karaf.util.tracker.annotation.RequireService;
import org.apache.karaf.util.tracker.annotation.Services;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ManagedService;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Services(
        requires = {
                @RequireService(ConfigurationAdmin.class),
                @RequireService(KeystoreManager.class)
        },
        provides = @ProvideService(MBeanServer.class)
)
@Managed("org.apache.karaf.management")
public class Activator extends BaseActivator implements ManagedService {

    private static final Logger LOG = LoggerFactory.getLogger(Activator.class);

    private ConnectorServerFactory connectorServerFactory;
    private RmiRegistryFactory rmiRegistryFactory;
    private MBeanServerFactory mbeanServerFactory;

    private ServiceTracker<KeystoreInstance, KeystoreInstance> keystoreInstanceServiceTracker;

    private EventAdminLogger eventAdminLogger;

    protected void doStart() throws Exception {
        // Verify dependencies
        ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
        KeystoreManager keystoreManager = getTrackedService(KeystoreManager.class);
        if (configurationAdmin == null || keystoreManager == null) {
            return;
        }

        EventAdminLogger logger = null;
        if (getBoolean("audit.eventadmin.enabled", true)) {
            try {
                logger = new EventAdminLoggerImpl(bundleContext);
            } catch (Throwable ignore) {
                // Ignore the listener if EventAdmin package isn't present
            }
        }
        if (logger == null) {
            logger = new EventAdminLogger() {
                @Override
                public void close() {
                }
                @Override
                public void log(String methodName, String[] signature, Object result, Throwable error, Object... params) {
                }
            };
        }
        eventAdminLogger = logger;

        String rmiRegistryHost = getString("rmiRegistryHost", "");
        int rmiRegistryPort = getInt("rmiRegistryPort", 1099);
        String rmiServerHost = getString("rmiServerHost", "0.0.0.0");
        int rmiServerPort = getInt("rmiServerPort", 44444);

        String jmxRealm = getString("jmxRealm", "karaf");
        String serviceUrl = getString("serviceUrl",
                "service:jmx:rmi://" + rmiServerHost + ":" + rmiServerPort + "/jndi/rmi://" + rmiRegistryHost + ":" + rmiRegistryPort + "/karaf-" + System.getProperty("karaf.name"));

        boolean daemon = getBoolean("daemon", true);
        boolean threaded = getBoolean("threaded", true);
        ObjectName objectName = new ObjectName(getString("objectName", "connector:name=rmi"));
        long keyStoreAvailabilityTimeout = getLong("keyStoreAvailabilityTimeout", 5000);
        String authenticatorType = getString("authenticatorType", "password");
        final boolean secured = getBoolean("secured", false);
        String secureAlgorithm = getString("secureAlgorithm", "default");
        String secureProtocol = getString("secureProtocol", "TLS");
        String keyStore = getString("keyStore", "karaf.ks");
        String keyAlias = getString("keyAlias", "karaf");
        String trustStore = getString("trustStore", "karaf.ts");
        boolean createRmiRegistry = getBoolean("createRmiRegistry", true);
        boolean locateRmiRegistry = getBoolean("locateRmiRegistry", true);
        boolean locateExistingMBeanServerIfPossible = getBoolean("locateExistingMBeanServerIfPossible", true);

        KarafMBeanServerGuard guard = new KarafMBeanServerGuard();
        guard.setLogger(eventAdminLogger);
        guard.setConfigAdmin(configurationAdmin);

        rmiRegistryFactory = new RmiRegistryFactory();
        rmiRegistryFactory.setCreate(createRmiRegistry);
        rmiRegistryFactory.setLocate(locateRmiRegistry);
        rmiRegistryFactory.setHost(rmiRegistryHost);
        rmiRegistryFactory.setPort(rmiRegistryPort);
        rmiRegistryFactory.setBundleContext(bundleContext);
        rmiRegistryFactory.init();

        mbeanServerFactory = new MBeanServerFactory();
        mbeanServerFactory.setLocateExistingServerIfPossible(locateExistingMBeanServerIfPossible);
        mbeanServerFactory.init();

        MBeanServer mbeanServer = mbeanServerFactory.getServer();
        mbeanServer = new EventAdminMBeanServerWrapper(mbeanServer, eventAdminLogger);

        JaasAuthenticator jaasAuthenticator = new JaasAuthenticator();
        jaasAuthenticator.setRealm(jmxRealm);

        connectorServerFactory = new ConnectorServerFactory();
        connectorServerFactory.setServer(mbeanServer);
        connectorServerFactory.setServiceUrl(serviceUrl);
        connectorServerFactory.setGuard(guard);
        connectorServerFactory.setRmiServerHost(rmiServerHost);
        connectorServerFactory.setDaemon(daemon);
        connectorServerFactory.setThreaded(threaded);
        connectorServerFactory.setObjectName(objectName);
        Map<String, Object> environment = new HashMap<>();
        environment.put("jmx.remote.authenticator", jaasAuthenticator);
        try {
            connectorServerFactory.setEnvironment(environment);
            connectorServerFactory.setKeyStoreAvailabilityTimeout(keyStoreAvailabilityTimeout);
            connectorServerFactory.setAuthenticatorType(authenticatorType);
            connectorServerFactory.setSecured(secured);
            connectorServerFactory.setAlgorithm(secureAlgorithm);
            connectorServerFactory.setSecureProtocol(secureProtocol);
            connectorServerFactory.setKeyStore(keyStore);
            connectorServerFactory.setKeyAlias(keyAlias);
            connectorServerFactory.setTrustStore(trustStore);
            connectorServerFactory.setKeystoreManager(keystoreManager);
            connectorServerFactory.init();
        } catch (Exception e) {
            LOG.error("Can't init JMXConnectorServer: " + e.getMessage());
        }

        JMXSecurityMBeanImpl securityMBean = new JMXSecurityMBeanImpl();
        securityMBean.setMBeanServer(mbeanServer);
        securityMBean.setGuard(guard);
        registerMBean(securityMBean, "type=security,area=jmx");

        register(MBeanServer.class, mbeanServer);

        if (secured) {
            keystoreInstanceServiceTracker = new ServiceTracker<>(
                    bundleContext, KeystoreInstance.class, new ServiceTrackerCustomizer<KeystoreInstance, KeystoreInstance>() {
                @Override
                public KeystoreInstance addingService(ServiceReference<KeystoreInstance> reference) {
                    try {
                        connectorServerFactory.init();
                    } catch (Exception e) {
                        LOG.error("Can't re-init JMXConnectorServer with SSL enabled when register a keystore:" + e.getMessage());
                    }
                    return null;
                }

                @Override
                public void modifiedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
                }

                @Override
                public void removedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
                    try {
                        connectorServerFactory.init();
                    } catch (Exception e) {
                        LOG.error("Can't re-init JMXConnectorServer with SSL enabled when unregister a keystore: " + e.getMessage());
                    }
                }
            });
            keystoreInstanceServiceTracker.open();
        }
    }

    protected void doStop() {
        super.doStop();
        if (connectorServerFactory != null) {
            try {
                connectorServerFactory.destroy();
            } catch (Exception e) {
                logger.warn("Error destroying ConnectorServerFactory", e);
            }
            connectorServerFactory = null;
        }
        if (mbeanServerFactory != null) {
            try {
                mbeanServerFactory.destroy();
            } catch (Exception e) {
                logger.warn("Error destroying MBeanServerFactory", e);
            }
            mbeanServerFactory = null;
        }
        if (rmiRegistryFactory != null) {
            try {
                rmiRegistryFactory.destroy();
            } catch (Exception e) {
                logger.warn("Error destroying RMIRegistryFactory", e);
            }
            rmiRegistryFactory = null;
        }
        if (keystoreInstanceServiceTracker != null) {
            try {
                keystoreInstanceServiceTracker.close();
            } finally {
                keystoreInstanceServiceTracker = null;
            }
        }
        if (eventAdminLogger != null) {
            try {
                eventAdminLogger.close();
            } finally {
                eventAdminLogger = null;
            }
        }
    }

}


text:
%Edit: Carl Doersch (cdoersch at cs dot cmu dot edu) to use dswork.
function [patches, patFeats, probabilities] = sampleRandomPatches(pos,samplelimit)
% Samples random patches. Sampling is biased to reduce selection of blank
% patches.
%
% Author: saurabh.me@gmail.com (Saurabh Singh).
global ds;
params=ds.conf.params;
levelFactor = 2;%params.levelFactor;
%data = pos;
%pos = pos.annotation;
rand('seed',1000*pos);
I = im2double(getimg(ds,pos));%imread([ds.conf.gbz{ds.conf.currimset}.cutoutdir ds.imgs(pos).fullpath]));

[IS, scale] = convertToCanonicalSize(I, params.imageCanonicalSize);
[rows, cols, unused] = size(IS);
IG = getGradientImage(IS);
pyramid = constructFeaturePyramidForImg(I, params);
[features, levels, indexes] = unentanglePyramid(pyramid, ...
  params.patchCanonicalSize);
selLevels = 1 : params.scaleIntervals/2 : length(pyramid.scales);
levelScales = pyramid.scales(selLevels);
numLevels = length(selLevels);
[prSize, pcSize, unused] = getCanonicalPatchHOGSize(params);

patches = [];
patFeats = [];
probabilities = [];
basenperlev=pyramid.features{selLevels(end)};
basenperlev=(basenperlev(1)-prSize+1)*(basenperlev(2)-pcSize+1);
for i = 1 : numLevels
  levPatSize = floor(params.patchCanonicalSize .* levelScales(i));
  if(dsbool(params,'sampleBig'))
    numLevPat=floor(basenperlev/levelFactor);
  else
    numLevPat = floor((rows / (levPatSize(1) / levelFactor)) * ...
      (cols / (levPatSize(2) / levelFactor))*2);
  end
  %disp([num2str(levelScales(i)) '->' num2str(numLevPat)]);

  levelPatInds = find(levels == selLevels(i));
  if numLevPat <= 0
    continue;
  end

  IGS = IG;
  pDist = getProbDistribution(IGS, levPatSize);
  pDist1d = pDist(:);
  randNums = getRandForPdf(pDist1d, numLevPat);
  probs = pDist1d(randNums);
  [IY, IX] = ind2sub(size(IGS), randNums);
  IY = ceil(IY ./ (levelScales(i) * params.sBins));
  IX = ceil(IX ./ (levelScales(i) * params.sBins));

  [nrows, ncols, unused] = size(pyramid.features{selLevels(i)});
  IY = IY - floor(prSize / 2);
  IX = IX - floor(pcSize / 2);
  xyToSel = IY>0 & IY<=nrows-prSize+1 & IX>0 & IX<=ncols-pcSize+1;
  IY = IY(xyToSel);
  IX = IX(xyToSel);
  probs = probs(xyToSel);
  inds = sub2ind([nrows-prSize+1 ncols-pcSize+1], IY, IX);
  [inds, m, unused] = unique(inds);
  probs = probs(m);
  selectedPatInds = levelPatInds(inds);
  metadata = getMetadataForPositives(selectedPatInds, levels,...
    indexes, prSize, pcSize, pyramid, pos);
  feats = features(selectedPatInds, :);
  if ~isempty(metadata)
    patInds = cleanUpOverlappingPatches(metadata, ...
      params.patchOverlapThreshold, probs);
    patches = [patches metadata(patInds)];
    patFeats = [patFeats; feats(patInds, :)];
    probabilities = [probabilities probs(patInds)'];
  end

end
if(exist('samplelimit','var'))
  inds=randperm(numel(patches));
  inds=inds(1:min(numel(inds),samplelimit));
  patches=patches(inds);
  patFeats=patFeats(inds,:);
  probabilities=probabilities(inds);
end
end

function patInds = cleanUpOverlappingPatches(patches, thresh, probs)
[unused, probInds] = sort(probs, 'descend');
patInds = zeros(1, length(patches));
indCount = 0;
mask = zeros(patches(1).size.nrows, patches(1).size.ncols);
nr = patches(1).y2 - patches(1).y1 + 1;
nc = patches(1).x2 - patches(1).x1 + 1;
patchArea = nr * nc;
for i = 1 : length(probInds)
  p = patches(probInds(i));
  %p
  subMaskArea = sum(sum(mask(p.y1:p.y2, p.x1:p.x2)));
  if subMaskArea / patchArea > thresh
    continue;
  end
  mask(p.y1:p.y2, p.x1:p.x2) = 1;
  indCount = indCount + 1;
  patInds(indCount) = probInds(i);
end
patInds = patInds(1:indCount);
patInds = sort(patInds);
end

function [centers, vertExt] = getCategoryCenters(data, category)
objects = data.annotation.object;
objNames = {objects.name};
[ismem, unused] = ismember(objNames, {category});
primLoc = find(ismem);
centers = zeros(length(primLoc), 2);
vertExt = zeros(length(primLoc), 1);
for j = 1 : length(primLoc)
  vertExt(j) = getVerticalExtent(objects(primLoc(j)));
  [centers(j, 1), centers(j, 2)] = getCenter(objects(primLoc(j)), data);
end
end

function ext = getVerticalExtent(obj)
[x,y] = getLMpolygon(obj.polygon);
ext = max(y) - min(y) + 1;
end

function [cx cy] = getCenter(obj, data)
bb = getBoundingBox(obj, data.annotation);
cx = (bb(1) + bb(3)) / 2;
cy = (bb(2) + bb(4)) / 2;
end

function I1 = getGradientImage(I)
[GX, GY] = gradient(I);
I1 = sum(abs(GX), 3) + sum(abs(GY), 3);
I1 = I1.^2;
end

function dist = getProbDistribution(I, pSize)
h = fspecial('gaussian', pSize, min(pSize)/3);
I = imfilter(I, h);
dist = I ./ sum(sum(I));
end


text:
package org.elasticsearch.plugin.mapper.attachments.tika;

import org.apache.tika.Tika;

/**
 *
 */
public class TikaInstance {

    private static final Tika tika = new Tika();

    public static Tika tika() {
        return tika;
    }
}


text:
package opennlp.tools.postag;

import java.io.File;
import java.io.IOException;

import opennlp.tools.dictionary.Dictionary;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.TrainingParameters;
import opennlp.tools.util.eval.CrossValidationPartitioner;
import opennlp.tools.util.eval.Mean;
import opennlp.tools.util.model.ModelType;
import opennlp.tools.util.model.ModelUtil;

public class POSTaggerCrossValidator {

  private final String languageCode;

  private final TrainingParameters params;

  private Integer ngramCutoff;

  private Mean wordAccuracy = new Mean();
  private POSTaggerEvaluationMonitor[] listeners;

  /* this will be used to load the factory after the ngram dictionary was created */
  private String factoryClassName;
  /* user can also send a ready to use factory */
  private POSTaggerFactory factory;

  private Integer tagdicCutoff = null;
  private File tagDictionaryFile;

  /**
   * Creates a {@link POSTaggerCrossValidator} that builds a ngram dictionary
   * dynamically. It instantiates a sub-class of {@link POSTaggerFactory} using
   * the tag and the ngram dictionaries.
   */
  public POSTaggerCrossValidator(String languageCode,
      TrainingParameters trainParam, File tagDictionary,
      Integer ngramCutoff, Integer tagdicCutoff, String factoryClass,
      POSTaggerEvaluationMonitor... listeners) {
    this.languageCode = languageCode;
    this.params = trainParam;
    this.ngramCutoff = ngramCutoff;
    this.listeners = listeners;
    this.factoryClassName = factoryClass;
    this.tagdicCutoff = tagdicCutoff;
    this.tagDictionaryFile = tagDictionary;
  }

  /**
   * Creates a {@link POSTaggerCrossValidator} using the given
   * {@link POSTaggerFactory}.
   */
  public POSTaggerCrossValidator(String languageCode,
      TrainingParameters trainParam, POSTaggerFactory factory,
      POSTaggerEvaluationMonitor... listeners) {
    this.languageCode = languageCode;
    this.params = trainParam;
    this.listeners = listeners;
    this.factory = factory;
    this.ngramCutoff = null;
    this.tagdicCutoff = null;
  }

  /**
   * @deprecated use
   *             {@link #POSTaggerCrossValidator(String, TrainingParameters, POSTaggerFactory, POSTaggerEvaluationMonitor...)}
   *             instead and pass in a {@link TrainingParameters} object and a
   *             {@link POSTaggerFactory}.
   */
  public POSTaggerCrossValidator(String languageCode, ModelType modelType, POSDictionary tagDictionary,
      Dictionary ngramDictionary, int cutoff, int iterations) {
    this(languageCode, create(modelType, cutoff, iterations), create(ngramDictionary, tagDictionary));
  }

  /**
   * @deprecated use
   *             {@link #POSTaggerCrossValidator(String, TrainingParameters, POSTaggerFactory, POSTaggerEvaluationMonitor...)}
   *             instead and pass in a {@link TrainingParameters} object and a
   *             {@link POSTaggerFactory}.
   */
  public POSTaggerCrossValidator(String languageCode, ModelType modelType, POSDictionary tagDictionary,
      Dictionary ngramDictionary) {
    this(languageCode, create(modelType, 5, 100), create(ngramDictionary, tagDictionary));
  }

  /**
   * @deprecated use
   *             {@link #POSTaggerCrossValidator(String, TrainingParameters, POSTaggerFactory, POSTaggerEvaluationMonitor...)}
   *             instead and pass in a {@link POSTaggerFactory}.
   */
  public POSTaggerCrossValidator(String languageCode,
      TrainingParameters trainParam, POSDictionary tagDictionary,
      POSTaggerEvaluationMonitor... listeners) {
    this(languageCode, trainParam, create(null, tagDictionary), listeners);
  }

  /**
   * @deprecated use
   *             {@link #POSTaggerCrossValidator(String, TrainingParameters, POSDictionary, Integer, String, POSTaggerEvaluationMonitor...)}
   *             instead and pass in the name of {@link POSTaggerFactory}
   *             sub-class.
   */
  public POSTaggerCrossValidator(String languageCode,
      TrainingParameters trainParam, POSDictionary tagDictionary,
      Integer ngramCutoff, POSTaggerEvaluationMonitor... listeners) {
    this(languageCode, trainParam, create(null, tagDictionary), listeners);
    this.ngramCutoff = ngramCutoff;
  }

  /**
   * @deprecated use
   *             {@link #POSTaggerCrossValidator(String, TrainingParameters, POSTaggerFactory, POSTaggerEvaluationMonitor...)}
   *             instead and pass in a {@link POSTaggerFactory}.
   */
  public POSTaggerCrossValidator(String languageCode,
      TrainingParameters trainParam, POSDictionary tagDictionary,
      Dictionary ngramDictionary, POSTaggerEvaluationMonitor... listeners) {
    this(languageCode, trainParam, create(ngramDictionary, tagDictionary), listeners);
  }

  /**
   * Starts the evaluation.
   *
   * @param samples
   *          the data to train and test
   * @param nFolds
   *          number of folds
   *
   * @throws IOException
   */
  public void evaluate(ObjectStream<POSSample> samples, int nFolds) throws IOException {

    CrossValidationPartitioner<POSSample> partitioner = new CrossValidationPartitioner<POSSample>(
        samples, nFolds);

    while (partitioner.hasNext()) {

      CrossValidationPartitioner.TrainingSampleStream<POSSample> trainingSampleStream = partitioner
          .next();

      if (this.factory == null) {
        this.factory = POSTaggerFactory.create(this.factoryClassName, null,
            null);
      }

      Dictionary ngramDict = this.factory.getDictionary();
      if (ngramDict == null) {
        if(this.ngramCutoff != null) {
          System.err.print("Building ngram dictionary ... ");
          ngramDict = POSTaggerME.buildNGramDictionary(trainingSampleStream,
              this.ngramCutoff);
          trainingSampleStream.reset();
          System.err.println("done");
        }
        this.factory.setDictionary(ngramDict);
      }

      if (this.tagDictionaryFile != null
          && this.factory.getTagDictionary() == null) {
        this.factory.setTagDictionary(this.factory
            .createTagDictionary(tagDictionaryFile));
      }
      if (this.tagdicCutoff != null) {
        TagDictionary dict = this.factory.getTagDictionary();
        if (dict == null) {
          dict = this.factory.createEmptyTagDictionary();
          this.factory.setTagDictionary(dict);
        }
        if (dict instanceof MutableTagDictionary) {
          POSTaggerME.populatePOSDictionary(trainingSampleStream, (MutableTagDictionary)dict,
              this.tagdicCutoff);
        } else {
          throw new IllegalArgumentException(
              "Can't extend a TagDictionary that does not implement MutableTagDictionary.");
        }
        trainingSampleStream.reset();
      }

      POSModel model = POSTaggerME.train(languageCode, trainingSampleStream,
          params, this.factory);

      POSEvaluator evaluator = new POSEvaluator(new POSTaggerME(model), listeners);

      evaluator.evaluate(trainingSampleStream.getTestSampleStream());

      wordAccuracy.add(evaluator.getWordAccuracy(), evaluator.getWordCount());

      if (this.tagdicCutoff != null) {
        this.factory.setTagDictionary(null);
      }

    }
  }

  /**
   * Retrieves the accuracy for all iterations.
   *
   * @return the word accuracy
   */
  public double getWordAccuracy() {
    return wordAccuracy.mean();
  }

  /**
   * Retrieves the number of words which where validated
   * over all iterations. The result is the amount of folds
   * multiplied by the total number of words.
   *
   * @return the word count
   */
  public long getWordCount() {
    return wordAccuracy.count();
  }

  private static TrainingParameters create(ModelType type, int cutoff, int iterations) {
    TrainingParameters params = ModelUtil.createTrainingParameters(iterations, cutoff);
    params.put(TrainingParameters.ALGORITHM_PARAM, type.toString());
    return params;
  }

  private static POSTaggerFactory create(Dictionary ngram, TagDictionary pos) {
    return new POSTaggerFactory(ngram, pos);
  }
}


text:
#pragma once
#include <aws/iotevents/IoTEvents_EXPORTS.h>
#include <aws/iotevents/model/SNSTopicPublishAction.h>
#include <aws/iotevents/model/IotTopicPublishAction.h>
#include <aws/iotevents/model/LambdaAction.h>
#include <aws/iotevents/model/IotEventsAction.h>
#include <aws/iotevents/model/SqsAction.h>
#include <aws/iotevents/model/FirehoseAction.h>
#include <aws/iotevents/model/DynamoDBAction.h>
#include <aws/iotevents/model/DynamoDBv2Action.h>
#include <aws/iotevents/model/IotSiteWiseAction.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTEvents
{
namespace Model
{

  /**
   *
Specifies one of the following actions to receive notifications when the
   * alarm state changes.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTEVENTS_API AlarmAction
  {
  public:
    AlarmAction();
    AlarmAction(Aws::Utils::Json::JsonView jsonValue);
    AlarmAction& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    inline const SNSTopicPublishAction& GetSns() const{ return m_sns; }

    inline bool SnsHasBeenSet() const { return m_snsHasBeenSet; }

    inline void SetSns(const SNSTopicPublishAction& value) { m_snsHasBeenSet = true; m_sns = value; }

    inline void SetSns(SNSTopicPublishAction&& value) { m_snsHasBeenSet = true; m_sns = std::move(value); }

    inline AlarmAction& WithSns(const SNSTopicPublishAction& value) { SetSns(value); return *this;}

    inline AlarmAction& WithSns(SNSTopicPublishAction&& value) { SetSns(std::move(value)); return *this;}

    inline const IotTopicPublishAction& GetIotTopicPublish() const{ return m_iotTopicPublish; }

    inline bool IotTopicPublishHasBeenSet() const { return m_iotTopicPublishHasBeenSet; }

    inline void SetIotTopicPublish(const IotTopicPublishAction& value) { m_iotTopicPublishHasBeenSet = true; m_iotTopicPublish = value; }

    inline void SetIotTopicPublish(IotTopicPublishAction&& value) { m_iotTopicPublishHasBeenSet = true; m_iotTopicPublish = std::move(value); }

    inline AlarmAction& WithIotTopicPublish(const IotTopicPublishAction& value) { SetIotTopicPublish(value); return *this;}

    inline AlarmAction& WithIotTopicPublish(IotTopicPublishAction&& value) { SetIotTopicPublish(std::move(value)); return *this;}

    inline const LambdaAction& GetLambda() const{ return m_lambda; }

    inline bool LambdaHasBeenSet() const { return m_lambdaHasBeenSet; }

    inline void SetLambda(const LambdaAction& value) { m_lambdaHasBeenSet = true; m_lambda = value; }

    inline void SetLambda(LambdaAction&& value) { m_lambdaHasBeenSet = true; m_lambda = std::move(value); }

    inline AlarmAction& WithLambda(const LambdaAction& value) { SetLambda(value); return *this;}

    inline AlarmAction& WithLambda(LambdaAction&& value) { SetLambda(std::move(value)); return *this;}

    inline const IotEventsAction& GetIotEvents() const{ return m_iotEvents; }

    inline bool IotEventsHasBeenSet() const { return m_iotEventsHasBeenSet; }

    inline void SetIotEvents(const IotEventsAction& value) { m_iotEventsHasBeenSet = true; m_iotEvents = value; }

    inline void SetIotEvents(IotEventsAction&& value) { m_iotEventsHasBeenSet = true; m_iotEvents = std::move(value); }

    inline AlarmAction& WithIotEvents(const IotEventsAction& value) { SetIotEvents(value); return *this;}

    inline AlarmAction& WithIotEvents(IotEventsAction&& value) { SetIotEvents(std::move(value)); return *this;}

    inline const SqsAction& GetSqs() const{ return m_sqs; }

    inline bool SqsHasBeenSet() const { return m_sqsHasBeenSet; }

    inline void SetSqs(const SqsAction& value) { m_sqsHasBeenSet = true; m_sqs = value; }

    inline void SetSqs(SqsAction&& value) { m_sqsHasBeenSet = true; m_sqs = std::move(value); }

    inline AlarmAction& WithSqs(const SqsAction& value) { SetSqs(value); return *this;}

    inline AlarmAction& WithSqs(SqsAction&& value) { SetSqs(std::move(value)); return *this;}

    inline const FirehoseAction& GetFirehose() const{ return m_firehose; }

    inline bool FirehoseHasBeenSet() const { return m_firehoseHasBeenSet; }

    inline void SetFirehose(const FirehoseAction& value) { m_firehoseHasBeenSet = true; m_firehose = value; }

    inline void SetFirehose(FirehoseAction&& value) { m_firehoseHasBeenSet = true; m_firehose = std::move(value); }

    inline AlarmAction& WithFirehose(const FirehoseAction& value) { SetFirehose(value); return *this;}

    inline AlarmAction& WithFirehose(FirehoseAction&& value) { SetFirehose(std::move(value)); return *this;}

    inline const DynamoDBAction& GetDynamoDB() const{ return m_dynamoDB; }

    inline bool DynamoDBHasBeenSet() const { return m_dynamoDBHasBeenSet; }

    inline void SetDynamoDB(const DynamoDBAction& value) { m_dynamoDBHasBeenSet = true; m_dynamoDB = value; }

    inline void SetDynamoDB(DynamoDBAction&& value) { m_dynamoDBHasBeenSet = true; m_dynamoDB = std::move(value); }

    inline AlarmAction& WithDynamoDB(const DynamoDBAction& value) { SetDynamoDB(value); return *this;}

    inline AlarmAction& WithDynamoDB(DynamoDBAction&& value) { SetDynamoDB(std::move(value)); return *this;}

    inline const DynamoDBv2Action& GetDynamoDBv2() const{ return m_dynamoDBv2; }

    inline bool DynamoDBv2HasBeenSet() const { return m_dynamoDBv2HasBeenSet; }

    inline void SetDynamoDBv2(const DynamoDBv2Action& value) { m_dynamoDBv2HasBeenSet = true; m_dynamoDBv2 = value; }

    inline void SetDynamoDBv2(DynamoDBv2Action&& value) { m_dynamoDBv2HasBeenSet = true; m_dynamoDBv2 = std::move(value); }

    inline AlarmAction& WithDynamoDBv2(const DynamoDBv2Action& value) { SetDynamoDBv2(value); return *this;}

    inline AlarmAction& WithDynamoDBv2(DynamoDBv2Action&& value) { SetDynamoDBv2(std::move(value)); return *this;}

    inline const IotSiteWiseAction& GetIotSiteWise() const{ return m_iotSiteWise; }

    inline bool IotSiteWiseHasBeenSet() const { return m_iotSiteWiseHasBeenSet; }

    inline void SetIotSiteWise(const IotSiteWiseAction& value) { m_iotSiteWiseHasBeenSet = true; m_iotSiteWise = value; }

    inline void SetIotSiteWise(IotSiteWiseAction&& value) { m_iotSiteWiseHasBeenSet = true; m_iotSiteWise = std::move(value); }

    inline AlarmAction& WithIotSiteWise(const IotSiteWiseAction& value) { SetIotSiteWise(value); return *this;}

    inline AlarmAction& WithIotSiteWise(IotSiteWiseAction&& value) { SetIotSiteWise(std::move(value)); return *this;}

  private:

    SNSTopicPublishAction m_sns;
    bool m_snsHasBeenSet;

    IotTopicPublishAction m_iotTopicPublish;
    bool m_iotTopicPublishHasBeenSet;

    LambdaAction m_lambda;
    bool m_lambdaHasBeenSet;

    IotEventsAction m_iotEvents;
    bool m_iotEventsHasBeenSet;

    SqsAction m_sqs;
    bool m_sqsHasBeenSet;

    FirehoseAction m_firehose;
    bool m_firehoseHasBeenSet;

    DynamoDBAction m_dynamoDB;
    bool m_dynamoDBHasBeenSet;

    DynamoDBv2Action m_dynamoDBv2;
    bool m_dynamoDBv2HasBeenSet;

    IotSiteWiseAction m_iotSiteWise;
    bool m_iotSiteWiseHasBeenSet;
  };

} // namespace Model
} // namespace IoTEvents
} // namespace Aws


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HDFSWriter (Apache Flume 1.7.0 API)</title>
<meta name="date" content="2016-10-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.flume.sink.hdfs

Interface HDFSWriter

All Superinterfaces:

Configurable

All Known Implementing Classes:

AbstractHDFSWriter, HDFSCompressedDataStream, HDFSDataStream, HDFSSequenceFile

@InterfaceAudience.Private
@InterfaceStability.Evolving
public interface HDFSWriter
extends Configurable

Method Summary

Methods

Modifier and Type
Method and Description

void
append(Event e)

void
close()

boolean
isUnderReplicated()

void
open(String filePath)

void
open(String filePath,
    org.apache.hadoop.io.compress.CompressionCodec codec,
    org.apache.hadoop.io.SequenceFile.CompressionType cType)

void
sync()

Methods inherited from interface org.apache.flume.conf.Configurable

configure

Method Detail

open

void open(String filePath)
          throws IOException

Throws:

IOException

open

void open(String filePath,
        org.apache.hadoop.io.compress.CompressionCodec codec,
        org.apache.hadoop.io.SequenceFile.CompressionType cType)
          throws IOException

Throws:

IOException

append

void append(Event e)
            throws IOException

Throws:

IOException

sync

void sync()
          throws IOException

Throws:

IOException

close

void close()
           throws IOException

Throws:

IOException

isUnderReplicated

boolean isUnderReplicated()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2009-2016 Apache Software Foundation. All Rights Reserved.


text:
require "monet/version"
require 'monet/config'
require 'monet/capture'
require 'monet/baseline_control'
require 'monet/router'
require 'monet/image'

module Monet
end


text:
.leaflet-label {
	background: rgb(255, 255, 255);
	background: rgba(255, 255, 255, 0.9);
	background-clip: padding-box;
	border-color: #777;
	border-color: rgba(0,0,0,0.25);
	border-radius: 4px;
        box-shadow: 4px 4px 2px gray;
	border-style: none;
	border-width: 1px;
	color: #111;
	display: block;
	font: 12px/20px "Helvetica Neue", Arial, Helvetica, sans-serif;
	font-weight: normal;
        text-align: left;
	padding: 6px 12px;
	position: absolute;
	-webkit-user-select: none;
	   -moz-user-select: none;
	    -ms-user-select: none;
	        user-select: none;
        left: 20px;
	pointer-events: none;
	white-space: nowrap;
	z-index: 1000;
}

.leaflet-label.leaflet-clickable {
	cursor: pointer;
	pointer-events: auto;
}

.leaflet-label:before,
.leaflet-label:after {
	border-top: 6px solid transparent;
	border-bottom: 6px solid transparent;
	content: none;
	position: absolute;
	top: 5px;
}

.leaflet-label:before {
	border-right: 6px solid black;
	border-right-color: inherit;
	left: -10px;
}

.leaflet-label:after {
	border-left: 6px solid black;
	border-left-color: inherit;
	right: -10px;
}

.leaflet-label-right:before,
.leaflet-label-left:after {
	content: "";
}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Offering = mongoose.model('Offering');

/**
 * Globals
 */
var user, offering;

/**
 * Unit tests
 */
describe('Offering Model Unit Tests:', function() {
	beforeEach(function(done) {
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: 'username',
			password: 'password'
		});

		user.save(function() {
			offering = new Offering({
				name: 'Offering Name',
				description: 'Offering description',
				user: user
			});

			done();
		});
	});

	describe('Method Save', function() {
		it('should be able to save without problems', function(done) {
			return offering.save(function(err) {
				should.not.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save without name', function(done) {
			offering.name = '';

			return offering.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save without description', function(done) {
			offering.description = '';

			return offering.save(function(err) {
				should.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save price as String', function(done) {
			offering.price = '5 dollars';

			return offering.save(function(err) {
				should.exist(err);
				done();
			});
		});

	});

	afterEach(function(done) {
		Offering.remove().exec();
		User.remove().exec();

		done();
	});
});


text:
import React from 'react'
import { mount } from 'enzyme'
import Header from '../Page.Header'
import { PageContext } from '../Page'

describe('ClassName', () => {
  test('Has default className', () => {
    const wrapper = mount(<Header />)

    expect(wrapper.getDOMNode().classList.contains('c-PageHeader')).toBe(true)
  })

  test('Applies custom className if specified', () => {
    const className = 'channel-4'
    const wrapper = mount(<Header className={className} />)

    expect(wrapper.getDOMNode().classList.contains(className)).toBe(true)
  })
})

describe('Content', () => {
  test('Does not renders child content', () => {
    const wrapper = mount(<Header>Channel 4</Header>)

    expect(wrapper.text()).not.toBe('Channel 4')
  })
})

describe('Title and Subtitle', () => {
  test('Can render a title', () => {
    const wrapper = mount(
      <Header render={({ Title }) => <Title>Channel 4</Title>} />
    )

    expect(wrapper.find('h1').text()).toContain('Channel 4')
  })
  test('Can render a subtitle', () => {
    const wrapper = mount(
      <Header
        render={({ Title, Subtitle }) => <Subtitle>Channel 4</Subtitle>}
      />
    )

    expect(wrapper.find('span').text()).toContain('Channel 4')
  })

  test('Title is primary heading (h1) by default', () => {
    const wrapper = mount(
      <Header render={({ Title }) => <Title>Channel 4</Title>} />
    )

    expect(wrapper.find('h1').length).toBe(1)
  })

  test('Title can render h2', () => {
    const wrapper = mount(
      <Header
        render={({ Title }) => <Title headingLevel="h2">Channel 4</Title>}
      />
    )

    expect(wrapper.find('h2').length).toBe(1)
  })

  test('Title can render smaller (secondary)', () => {
    const wrapper = mount(
      <Header
        render={({ Title }) => (
          <Title headingLevel="h2" isSecondary>
            Channel 4
          </Title>
        )}
      />
    )

    expect(wrapper.find('h2').hasClass('is-h4')).toBe(true)
  })

  test('Can render the title with "title" prop', () => {
    const wrapper = mount(<Header title="Channel 4" />)

    expect(wrapper.text()).toContain('Channel 4')
  })

  test('Can render the subtitle with "subtitle" prop', () => {
    const wrapper = mount(<Header title="Channel 4" subtitle="News team" />)

    expect(wrapper.text()).toContain('Channel 4')
    expect(wrapper.text()).toContain('News team')
  })
})

describe('Border', () => {
  test('Renders a border', () => {
    const wrapper = mount(
      <Header render={({ Title }) => <Title>Channel 4</Title>} />
    )

    expect(wrapper.getDOMNode().classList.contains('is-withBorder')).toBe(true)
  })

  test('Can not render a border, if specified', () => {
    const wrapper = mount(
      <Header
        render={({ Title }) => <Title>Channel 4</Title>}
        withBorder={false}
      />
    )

    expect(wrapper.getDOMNode().classList.contains('is-withBorder')).toBe(false)
  })
})

describe('Responsive', () => {
  test('Renders responsive styles, if specified', () => {
    const wrapper = mount(
      <PageContext.Provider value={{ isResponsive: true }}>
        <Header />
      </PageContext.Provider>
    )

    expect(
      wrapper
        .find(Header)
        .getDOMNode()
        .classList.contains('is-responsive')
    ).toBe(true)
  })

  test('Does not render responsive styles, if specified', () => {
    const wrapper = mount(
      <PageContext.Provider value={{ isResponsive: false }}>
        <Header />
      </PageContext.Provider>
    )

    expect(
      wrapper
        .find(Header)
        .getDOMNode()
        .classList.contains('is-responsive')
    ).toBe(false)
  })
})

describe('withBottomMargin', () => {
  test('Renders withBottomMargin styles, if specified', () => {
    const wrapper = mount(
      <Header
        render={({ Title }) => <Title>Channel 4</Title>}
        withBottomMargin
      />
    )

    expect(wrapper.getDOMNode().classList.contains('is-withBottomMargin')).toBe(
      true
    )
  })

  test('Does not render withBottomMargin styles, if specified', () => {
    const wrapper = mount(
      <Header
        render={({ Title }) => <Title>Channel 4</Title>}
        withBottomMargin={false}
      />
    )

    expect(wrapper.getDOMNode().classList.contains('is-withBottomMargin')).toBe(
      false
    )
  })
})


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var Button_1 = require("office-ui-fabric-react/lib/Button");
var Panel_1 = require("office-ui-fabric-react/lib/Panel");
var PanelMediumExample = (function (_super) {
    __extends(PanelMediumExample, _super);
    function PanelMediumExample() {
        var _this = _super.call(this) || this;
        _this.state = { showPanel: false };
        return _this;
    }
    PanelMediumExample.prototype.render = function () {
        var _this = this;
        return (React.createElement("div", null,
            React.createElement(Button_1.DefaultButton, { description: 'Opens the Sample Panel', onClick: function () { return _this.setState({ showPanel: true }); }, text: 'Open Panel' }),
            React.createElement(Panel_1.Panel, { isOpen: this.state.showPanel, onDismiss: function () { return _this.setState({ showPanel: false }); }, type: Panel_1.PanelType.medium, headerText: 'Medium Panel' },
                React.createElement("span", { className: 'ms-font-m' }, "Content goes here."))));
    };
    return PanelMediumExample;
}(React.Component));
exports.PanelMediumExample = PanelMediumExample;

//# sourceMappingURL=Panel.Medium.Example.js.map