text:
var Lab = require('lab');
var Joi = require('../lib');
var Helper = require('./helper');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;

describe('object', function () {

    it('converts a json string to an object', function (done) {

        Joi.object().validate('{"hi":true}', function (err, value) {

            expect(err).to.not.exist;
            expect(value.hi).to.equal(true);
            done();
        });
    });

    it('errors on non-object string', function (done) {

        Joi.object().validate('a string', function (err, value) {

            expect(err).to.exist;
            expect(value).to.equal('a string');
            done();
        });
    });

    it('should validate an object', function (done) {

        var schema = Joi.object().required();
        Helper.validate(schema, [
            [{}, true],
            [{ hi: true }, true],
            ['', false]
        ], done);
    });

    it('retains ignored values', function (done) {

        var schema = Joi.object();
        schema.validate({ a: 5 }, function (err, value) {

            expect(value.a).to.equal(5);
            done();
        });
    });

    it('retains skipped values', function (done) {

        var schema = Joi.object({ b: 5 }).unknown(true);
        schema.validate({ b: '5', a: 5 }, function (err, value) {

            expect(value.a).to.equal(5);
            expect(value.b).to.equal(5);
            done();
        });
    });

    it('allows any key when schema is undefined', function (done) {

        Joi.object().validate({ a: 4 }, function (err, value) {

            expect(err).to.not.exist;

            Joi.object(undefined).validate({ a: 4 }, function (err, value) {

                expect(err).to.not.exist;
                done();
            });
        });
    });

    it('allows any key when schema is null', function (done) {

        Joi.object(null).validate({ a: 4 }, function (err, value) {

            expect(err).to.not.exist;
            done();
        });
    });

    it('throws on invalid object schema', function (done) {

        expect(function () {

            Joi.object(4);
        }).to.throw('Object schema must be a valid object');
        done();
    });

    it('throws on joi object schema', function (done) {

        expect(function () {

            Joi.object(Joi.object());
        }).to.throw('Object schema cannot be a joi schema');
        done();
    });

    it('skips conversion when value is undefined', function (done) {

        Joi.object({ a: Joi.object() }).validate(undefined, function (err, value) {

            expect(err).to.not.exist;
            expect(value).to.not.exist;
            done();
        });
    });

    it('errors on array', function (done) {

        Joi.object().validate([1, 2, 3], function (err, value) {

            expect(err).to.exist;
            done();
        });
    });

    it('should prevent extra keys from existing by default', function (done) {

        var schema = Joi.object({ item: Joi.string().required() }).required();
        Helper.validate(schema, [
            [{ item: 'something' }, true],
            [{ item: 'something', item2: 'something else' }, false],
            ['', false]
        ], done);
    });

    it('should validate count when min is set', function (done) {

        var schema = Joi.object().min(3);
        Helper.validate(schema, [
            [{ item: 'something' }, false],
            [{ item: 'something', item2: 'something else' }, false],
            [{ item: 'something', item2: 'something else', item3: 'something something else' }, true],
            ['', false]
        ], done);
    });

    it('should validate count when max is set', function (done) {

        var schema = Joi.object().max(2);
        Helper.validate(schema, [
            [{ item: 'something' }, true],
            [{ item: 'something', item2: 'something else' }, true],
            [{ item: 'something', item2: 'something else', item3: 'something something else' }, false],
            ['', false]
        ], done);
    });

    it('should validate count when min and max is set', function (done) {

        var schema = Joi.object().max(3).min(2);
        Helper.validate(schema, [
            [{ item: 'something' }, false],
            [{ item: 'something', item2: 'something else' }, true],
            [{ item: 'something', item2: 'something else', item3: 'something something else' }, true],
            [{ item: 'something', item2: 'something else', item3: 'something something else', item4: 'item4' }, false],
            ['', false]
        ], done);
    });

    it('should validate count when length is set', function (done) {

        var schema = Joi.object().length(2);
        Helper.validate(schema, [
            [{ item: 'something' }, false],
            [{ item: 'something', item2: 'something else' }, true],
            [{ item: 'something', item2: 'something else', item3: 'something something else' }, false],
            ['', false]
        ], done);
    });

    it('should traverse an object and validate all properties in the top level', function (done) {

        var schema = Joi.object({
            num: Joi.number()
        });

        Helper.validate(schema, [
            [{ num: 1 }, true],
            [{ num: [1, 2, 3] }, false]
        ], done);
    });

    it('should traverse an object and child objects and validate all properties', function (done) {

        var schema = Joi.object({
            num: Joi.number(),
            obj: Joi.object({
                item: Joi.string()
            })
        });

        Helper.validate(schema, [
            [{ num: 1 }, true],
            [{ num: [1, 2, 3] }, false],
            [{ num: 1, obj: { item: 'something' } }, true],
            [{ num: 1, obj: { item: 123 } }, false]
        ], done);
    });

    it('should traverse an object several levels', function (done) {

        var schema = Joi.object({
            obj: Joi.object({
                obj: Joi.object({
                    obj: Joi.object({
                        item: Joi.boolean()
                    })
                })
            })
        });

        Helper.validate(schema, [
            [{ num: 1 }, false],
            [{ obj: {} }, true],
            [{ obj: { obj: {} } }, true],
            [{ obj: { obj: { obj: {} } } }, true],
            [{ obj: { obj: { obj: { item: true } } } }, true],
            [{ obj: { obj: { obj: { item: 10 } } } }, false]
        ], done);
    });

    it('should traverse an object several levels with required levels', function (done) {

        var schema = Joi.object({
            obj: Joi.object({
                obj: Joi.object({
                    obj: Joi.object({
                        item: Joi.boolean()
                    })
                }).required()
            })
        });

        Helper.validate(schema, [
            [null, false],
            [undefined, true],
            [{}, true],
            [{ obj: {} }, false],
            [{ obj: { obj: {} } }, true],
            [{ obj: { obj: { obj: {} } } }, true],
            [{ obj: { obj: { obj: { item: true } } } }, true],
            [{ obj: { obj: { obj: { item: 10 } } } }, false]
        ], done);
    });

    it('should traverse an object several levels with required levels (without Joi.obj())', function (done) {

        var schema = {
            obj: {
                obj: {
                    obj: {
                        item: Joi.boolean().required()
                    }
                }
            }
        };

        Helper.validate(schema, [
            [null, false],
            [undefined, true],
            [{}, true],
            [{ obj: {} }, true],
            [{ obj: { obj: {} } }, true],
            [{ obj: { obj: { obj: {} } } }, false],
            [{ obj: { obj: { obj: { item: true } } } }, true],
            [{ obj: { obj: { obj: { item: 10 } } } }, false]
        ], done);
    });

    it('errors on unknown keys when functions allows', function (done) {

        var schema = Joi.object({ a: Joi.number() }).options({ skipFunctions: true });
        var obj = { a: 5, b: 'value' };
        schema.validate(obj, function (err, value) {

            expect(err).to.exist;
            done();
        });
    });

    it('validates both valid() and with()', function (done) {

        var schema = Joi.object({
            first: Joi.valid('value'),
            second: Joi.any()
        }).with('first', 'second');

        Helper.validate(schema, [
            [{ first: 'value' }, false]
        ], done);
    });

    describe('#keys', function () {

        it('allows any key', function (done) {

            var a = Joi.object({ a: 4 });
            var b = a.keys();
            a.validate({ b: 3 }, function (err, value) {

                expect(err).to.exist;
                b.validate({ b: 3 }, function (err, value) {

                    expect(err).to.not.exist;
                    done();
                });
            });
        });

        it('forbids all keys', function (done) {

            var a = Joi.object();
            var b = a.keys({});
            a.validate({ b: 3 }, function (err, value) {

                expect(err).to.not.exist;
                b.validate({ b: 3 }, function (err, value) {

                    expect(err).to.exist;
                    done();
                });
            });
        });

        it('adds to existing keys', function (done) {

            var a = Joi.object({ a: 1 });
            var b = a.keys({ b: 2 });
            a.validate({ a: 1, b: 2 }, function (err, value) {

                expect(err).to.exist;
                b.validate({ a: 1, b: 2 }, function (err, value) {

                    expect(err).to.not.exist;
                    done();
                });
            });
        });
    });

    describe('#unknown', function () {

        it('allows local unknown without applying to children', function (done) {

            var schema = Joi.object({
                a: {
                    b: Joi.number()
                }
            }).unknown();

            Helper.validate(schema, [
                [{ a: { b: 5 } }, true],
                [{ a: { b: 'x' } }, false],
                [{ a: { b: 5 }, c: 'ignore' }, true],
                [{ a: { b: 5, c: 'ignore' } }, false]
            ], done);
        });

        it('forbids local unknown without applying to children', function (done) {

            var schema = Joi.object({
                a: Joi.object({
                    b: Joi.number()
                }).unknown()
            }).options({ allowUnknown: false });

            Helper.validate(schema, [
                [{ a: { b: 5 } }, true],
                [{ a: { b: 'x' } }, false],
                [{ a: { b: 5 }, c: 'ignore' }, false],
                [{ a: { b: 5, c: 'ignore' } }, true]
            ], done);
        });
    });

    describe('#rename', function () {

        it('allows renaming multiple times with multiple enabled', function (done) {

            var schema = Joi.object({
                test: Joi.string()
            }).rename('test1', 'test').rename('test2', 'test', { multiple: true });

            Joi.compile(schema).validate({ test1: 'a', test2: 'b' }, function (err, value) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('errors renaming multiple times with multiple disabled', function (done) {

            var schema = Joi.object({
                test: Joi.string()
            }).rename('test1', 'test').rename('test2', 'test');

            Joi.compile(schema).validate({ test1: 'a', test2: 'b' }, function (err, value) {

                expect(err.message).to.equal('value cannot rename child test2 because multiple renames are disabled and another key was already renamed to test');
                done();
            });
        });

        it('errors multiple times when abortEarly is false', function (done) {

            Joi.object().rename('a', 'b').rename('c', 'b').rename('d', 'b').options({ abortEarly: false }).validate({ a: 1, c: 1, d: 1 }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('value cannot rename child c because multiple renames are disabled and another key was already renamed to b. value cannot rename child d because multiple renames are disabled and another key was already renamed to b');
                done();
            });
        });

        it('aliases a key', function (done) {

            var schema = Joi.object({
                a: Joi.number(),
                b: Joi.number()
            }).rename('a', 'b', { alias: true });

            var obj = { a: 10 };

            Joi.compile(schema).validate(obj, function (err, value) {

                expect(err).to.not.exist;
                expect(value.a).to.equal(10);
                expect(value.b).to.equal(10);
                done();
            });
        });

        it('with override disabled should not allow overwriting existing value', function (done) {

            var schema = Joi.object({
                test1: Joi.string()
            }).rename('test', 'test1');

            schema.validate({ test: 'b', test1: 'a' }, function (err, value) {

                expect(err.message).to.equal('value cannot rename child test because override is disabled and target test1 exists');
                done();
            });
        });

        it('with override enabled should allow overwriting existing value', function (done) {

            var schema = Joi.object({
                test1: Joi.string()
            }).rename('test', 'test1', { override: true });

            schema.validate({ test: 'b', test1: 'a' }, function (err, value) {

                expect(err).to.not.exist;
                done();
            });
        });

        it('renames when data is nested in an array via includes', function (done) {

            var schema = {
                arr: Joi.array().includes(Joi.object({
                    one: Joi.string(),
                    two: Joi.string()
                }).rename('uno', 'one').rename('dos', 'two'))
            };

            var data = { arr: [{ uno: '1', dos: '2' }] };
            Joi.object(schema).validate(data, function (err, value) {

                expect(err).to.not.exist;
                expect(value.arr[0].one).to.equal('1');
                expect(value.arr[0].two).to.equal('2');
                done();
            });
        });

        it('applies rename and validation in the correct order regardless of key order', function (done) {

            var schema1 = Joi.object({
                a: Joi.number()
            }).rename('b', 'a');

            var input1 = { b: '5' };

            schema1.validate(input1, function (err1, value1) {

                expect(err1).to.not.exist;
                expect(value1.b).to.not.exist;
                expect(value1.a).to.equal(5);

                var schema2 = Joi.object({ a: Joi.number(), b: Joi.any() }).rename('b', 'a');
                var input2 = { b: '5' };

                schema2.validate(input2, function (err2, value2) {

                    expect(err2).to.not.exist;
                    expect(value2.b).to.not.exist;
                    expect(value2.a).to.equal(5);

                    done();
                });
            });
        });

        it('sets the default value after key is renamed', function (done) {

            var schema = Joi.object({
                foo2: Joi.string().default('test')
            }).rename('foo', 'foo2');

            var input = {};

            Joi.validate(input, schema, function (err, value) {

                expect(err).to.not.exist;
                expect(value.foo2).to.equal('test');

                done();
            });
        });

        it('should be able to rename keys that are empty strings', function (done) {

            var schema = Joi.object().rename('', 'notEmpty');
            var input = {
                '': 'something'
            };

            schema.validate(input, function (err, value) {

                expect(err).to.not.exist;
                expect(value['']).to.not.exist;
                expect(value.notEmpty).to.equal('something');
                done();
            });
        });

        it('should not create new keys when they key in question does not exist', function (done) {

            var schema = Joi.object().rename('b', '_b');

            var input = {
                a: 'something'
            };

            schema.validate(input, function (err, value) {

                expect(err).to.not.exist;
                expect(value).to.have.keys(['a']);
                expect(value.a).to.equal('something');
                done();
            });
        });
    });

    describe('#describe', function () {

        it('return empty description when no schema defined', function (done) {

            var schema = Joi.object();
            var desc = schema.describe();
            expect(desc).to.deep.equal({
                type: 'object'
            });
            done();
        });

        it('respects the shallow parameter', function (done) {

            var schema = Joi.object({
                name: Joi.string(),
                child: Joi.object({
                    name: Joi.string()
                })
            });

            expect(schema.describe(true)).to.not.contain.key('children');
            expect(schema.describe()).to.contain.key('children');

            done();
        });
    });

    describe('#length', function () {

        it('throws when length is not a number', function (done) {

            expect(function () {

                Joi.object().length('a');
            }).to.throw('limit must be a positive integer');
            done();
        });
    });

    describe('#min', function () {

        it('throws when limit is not a number', function (done) {

            expect(function () {

                Joi.object().min('a');
            }).to.throw('limit must be a positive integer');
            done();
        });
    });

    describe('#max', function () {

        it('throws when limit is not a number', function (done) {

            expect(function () {

                Joi.object().max('a');
            }).to.throw('limit must be a positive integer');
            done();
        });
    });

    describe('#pattern', function () {

        it('validates unknown keys using a pattern', function (done) {

            var schema = Joi.object({
                a: Joi.number()
            }).pattern(/\d+/, Joi.boolean()).pattern(/\w\w+/, 'x');

            Joi.validate({ bb: 'y', 5: 'x' }, schema, { abortEarly: false }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('5 must be a boolean. bb must be one of x');

                Helper.validate(schema, [
                    [{ a: 5 }, true],
                    [{ a: 'x' }, false],
                    [{ b: 'x' }, false],
                    [{ bb: 'x' }, true],
                    [{ 5: 'x' }, false],
                    [{ 5: false }, true],
                    [{ 5: undefined }, true]
                ], done)
            });
        });

        it('validates unknown keys using a pattern (nested)', function (done) {

            var schema = {
                x: Joi.object({
                    a: Joi.number()
                }).pattern(/\d+/, Joi.boolean()).pattern(/\w\w+/, 'x')
            };

            Joi.validate({ x: { bb: 'y', 5: 'x' } }, schema, { abortEarly: false }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('5 must be a boolean. bb must be one of x');
                done();
            });
        });

        it('errors when using a pattern on empty schema with unknown(false) and pattern mismatch', function (done) {

            var schema = Joi.object().pattern(/\d/, Joi.number()).unknown(false);

            Joi.validate({ a: 5 }, schema, { abortEarly: false }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('a is not allowed');
                done();
            });
        });
    });

    describe('#with', function () {

        it('should throw an error when a parameter is not a string', function (done) {

            try {
                Joi.object().with({});
                var error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);

            try {
                Joi.object().with(123);
                error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);
            done();
        });

        it('should validate correctly when key is an empty string', function (done) {

            var schema = Joi.object().with('', 'b');
            Helper.validate(schema, [
                [{ c: 'hi', d: 'there' }, true],
            ]);
            done();
        });
    });

    describe('#without', function () {

        it('should throw an error when a parameter is not a string', function (done) {

            try {
                Joi.object().without({});
                var error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);

            try {
                Joi.object().without(123);
                error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);

            done();
        });

        it('should validate correctly when key is an empty string', function (done) {

            var schema = Joi.object().without('', 'b');
            Helper.validate(schema, [
                [{ a: 'hi', b: 'there' }, true]
            ]);
            done();
        });
    });

    describe('#xor', function () {

        it('should throw an error when a parameter is not a string', function (done) {

            try {
                Joi.object().xor({});
                var error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);

            try {
                Joi.object().xor(123);
                error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);
            done();
        });
    });

    describe('#or', function () {

        it('should throw an error when a parameter is not a string', function (done) {

            try {
                Joi.object().or({});
                var error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);

            try {
                Joi.object().or(123);
                error = false;
            }
            catch (e) {
                error = true;
            }
            expect(error).to.equal(true);
            done();
        });

        it('errors multiple levels deep', function (done) {

            Joi.object({
                a: {
                    b: Joi.object().or('x', 'y')
                }
            }).validate({ a: { b: { c: 1 } } }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('value must contain at least one of x, y');
                done();
            });
        });
    });

    describe('#assert', function () {

        it('validates upwards reference', function (done) {

            var schema = Joi.object({
                a: {
                    b: Joi.string(),
                    c: Joi.number()
                },
                d: {
                    e: Joi.any()
                }
            }).assert(Joi.ref('d/e', { separator: '/' }), Joi.ref('a.c'), 'equal to a.c');

            schema.validate({ a: { b: 'x', c: 5 }, d: { e: 6 } }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('value validation failed because d.e failed to equal to a.c');

                Helper.validate(schema, [
                    [{ a: { b: 'x', c: 5 }, d: { e: 5 } }, true]
                ], done);
            });
        });

        it('validates upwards reference with implicit context', function (done) {

            var schema = Joi.object({
                a: {
                    b: Joi.string(),
                    c: Joi.number()
                },
                d: {
                    e: Joi.any()
                }
            }).assert('d.e', Joi.ref('a.c'), 'equal to a.c');

            schema.validate({ a: { b: 'x', c: 5 }, d: { e: 6 } }, function (err, value) {

                expect(err).to.exist;
                expect(err.message).to.equal('value validation failed because d.e failed to equal to a.c');

                Helper.validate(schema, [
                    [{ a: { b: 'x', c: 5 }, d: { e: 5 } }, true]
                ], done);
            });
        });

        it('throws when context is at root level', function (done) {

            expect(function () {

                var schema = Joi.object({
                    a: {
                        b: Joi.string(),
                        c: Joi.number()
                    },
                    d: {
                        e: Joi.any()
                    }
                }).assert('a', Joi.ref('d.e'), 'equal to d.e');
            }).to.throw('Cannot use assertions for root level references - use direct key rules instead');
            done();
        });

        it('allows root level context ref', function (done) {

            expect(function () {

                var schema = Joi.object({
                    a: {
                        b: Joi.string(),
                        c: Joi.number()
                    },
                    d: {
                        e: Joi.any()
                    }
                }).assert('$a', Joi.ref('d.e'), 'equal to d.e');
            }).to.not.throw();
            done();
        });
    });
});


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication5;

/**
 *
 * @author awzurn
 */
public class JavaApplication5 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
}

redpajama_set_name: RedPajamaGithub


text:
// ***********************************************************************
// Assembly         : ACBr.Net.CTe
// Author           : RFTD
// Created          : 11-10-2016
//
// Last Modified By : RFTD
// Last Modified On : 06-22-2018
// ***********************************************************************
// <copyright file="CTeServiceManager.cs" company="ACBr.Net">
//		        		   The MIT License (MIT)
//	     		    Copyright (c) 2016 Grupo ACBr.Net
//
//	 Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//	 The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//	 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using ACBr.Net.Core;
using ACBr.Net.Core.Exceptions;
using ACBr.Net.Core.Extensions;
using ACBr.Net.DFe.Core.Collection;
using ACBr.Net.DFe.Core.Common;
using ACBr.Net.DFe.Core.Service;

namespace ACBr.Net.CTe.Services
{
    /// <summary>
    /// Classe responsavel pelo gerenciamento das url dos serviço da CTe.
    /// </summary>
    public static class CTeServiceManager
    {
        #region Constructors

        static CTeServiceManager()
        {
            Servicos = new DFeServices<TipoServicoCTe, CTeVersao>
            {
                Webservices = new DFeCollection<DFeServiceInfo<TipoServicoCTe, CTeVersao>>
                {
                    new DFeServiceInfo<TipoServicoCTe, CTeVersao>
                    {
                        Versao = CTeVersao.v300,
                        Tipo = DFeTipoServico.CTe,
                        TipoEmissao = DFeTipoEmissao.Normal
                    },
                    new DFeServiceInfo<TipoServicoCTe, CTeVersao>
                    {
                        Versao = CTeVersao.v300,
                        Tipo = DFeTipoServico.CTe,
                        TipoEmissao = DFeTipoEmissao.DPEC
                    },
                    new DFeServiceInfo<TipoServicoCTe, CTeVersao>
                    {
                        Versao = CTeVersao.v300,
                        Tipo = DFeTipoServico.CTe,
                        TipoEmissao = DFeTipoEmissao.SVCRS
                    },
                    new DFeServiceInfo<TipoServicoCTe, CTeVersao>
                    {
                        Versao = CTeVersao.v300,
                        Tipo = DFeTipoServico.CTe,
                        TipoEmissao = DFeTipoEmissao.SVCSP
                    }
                }
            };

            var dataSource = (from DFeSiglaUF value in Enum.GetValues(typeof(DFeSiglaUF))
                              where !value.IsIn(DFeSiglaUF.EX, DFeSiglaUF.AN, DFeSiglaUF.SU)
                              orderby value.GetDescription()
                              select value).ToArray();

            var servicoCTes = (from TipoServicoCTe value in Enum.GetValues(typeof(TipoServicoCTe)) select value).ToArray();

            foreach (var serviceInfo in Servicos.Webservices)
            {
                foreach (var siglaUF in dataSource)
                {
                    var ambiente = serviceInfo.Ambientes.AddNew();
                    ambiente.UF = siglaUF;
                    ambiente.Ambiente = DFeTipoAmbiente.Homologacao;

                    foreach (var servicoCTe in servicoCTes)
                    {
                        ambiente.Enderecos.Add(servicoCTe, "");
                    }

                    ambiente = serviceInfo.Ambientes.AddNew();
                    ambiente.UF = siglaUF;
                    ambiente.Ambiente = DFeTipoAmbiente.Producao;

                    foreach (var servicoCTe in servicoCTes)
                    {
                        ambiente.Enderecos.Add(servicoCTe, "");
                    }
                }
            }

            Load();
        }

        #endregion Constructors

        #region Propriedades

        /// <summary>
        /// Lista de serviços CTe.
        /// </summary>
        public static DFeServices<TipoServicoCTe, CTeVersao> Servicos { get; private set; }

        #endregion Propriedades

        #region Methods

        /// <summary>
        /// Retorna a url do serviço de acordo com os dados passados.
        /// </summary>
        /// <param name="versao">Versão da CTe</param>
        /// <param name="uf">UF do serviço</param>
        /// <param name="tipo">Tipo de serviço</param>
        /// <param name="tipoEmissao"></param>
        /// <param name="ambiente">Ambiente</param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static string GetServiceAndress(CTeVersao versao, DFeSiglaUF uf, TipoServicoCTe tipo, DFeTipoEmissao tipoEmissao, DFeTipoAmbiente ambiente)
        {
            switch (tipo)
            {
                case TipoServicoCTe.DistribuicaoDFe:
                    switch (ambiente)
                    {
                        case DFeTipoAmbiente.Homologacao: return @"https://hom1.cte.fazenda.gov.br/CTeDistribuicaoDFe/CTeDistribuicaoDFe.asmxhttps://hom1.cte.fazenda.gov.br/CTeDistribuicaoDFe/CTeDistribuicaoDFe.asmx";
                        default: return @"https://www1.cte.fazenda.gov.br/CTeDistribuicaoDFe/CTeDistribuicaoDFe.asmxhttps://www1.cte.fazenda.gov.br/CTeDistribuicaoDFe/CTeDistribuicaoDFe.asmx";
                    }

                default:
                    var service = Servicos[versao, tipoEmissao];
                    Guard.Against<ACBrException>(service == null, "Versão ou tipo de emissão não encontrada no arquivo de serviços.");
                    return service[ambiente, uf]?[tipo];
            }
        }

        /// <summary>
        /// Salva o arquivo de serviços.
        /// </summary>
        /// <param name="path">Caminho para salvar o arquivo</param>
        public static void Save(string path = "services.cte")
        {
            Guard.Against<ArgumentNullException>(path == null, "Path invalido.");

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (var fileStream = new FileStream(path, FileMode.CreateNew))
            {
                Save(fileStream);
            }
        }

        /// <summary>
        /// Salva o arquivo de serviços.
        /// </summary>
        /// <param name="stream">O stream.</param>
        public static void Save(Stream stream)
        {
            Servicos.Save(stream);
        }

        /// <summary>
        /// Carrega o arquivo de serviços.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="clean">if set to <c>true</c> [clean].</param>
        public static void Load(string path = "")
        {
            byte[] buffer = null;
            if (path.IsEmpty())
            {
                var assembly = Assembly.GetExecutingAssembly();
                using (var stream = assembly.GetManifestResourceStream("ACBr.Net.CTe.Resources.services.cte"))
                {
                    if (stream != null)
                    {
                        buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, buffer.Length);
                    }
                }
            }
            else if (File.Exists(path))
            {
                buffer = File.ReadAllBytes(path);
            }

            Guard.Against<ArgumentException>(buffer == null, "Arquivo de serviços não encontrado");

            using (var stream = new MemoryStream(buffer))
            {
                Load(stream);
            }
        }

        /// <summary>
        /// Carrega o arquivo de serviços.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="clean">if set to <c>true</c> [clean].</param>
        public static void Load(Stream stream)
        {
            Guard.Against<ArgumentException>(stream == null, "Arquivo de serviços não encontrado");

            Servicos = DFeServices<TipoServicoCTe, CTeVersao>.Load(stream);
        }

        /// <summary>
        /// Função para importar endereços no padrão de Ini do ACBr.
        /// </summary>
        /// <param name="path">Caminho para o ini</param>
        public static void ImportIniACBr(string path = "")
        {
            using (var stream = File.OpenRead(path))
            {
                ImportIniACBr(stream);
            }
        }

        /// <summary>
        /// Função para importar endereços no padrão de Ini do ACBr.
        /// </summary>
        /// <param name="stream"></param>
        public static void ImportIniACBr(Stream stream)
        {
            var ini = ACBrIniFile.Load(stream);

            var dataSource = (from DFeSiglaUF value in Enum.GetValues(typeof(DFeSiglaUF))
                              where !value.IsIn(DFeSiglaUF.EX, DFeSiglaUF.AN, DFeSiglaUF.SU)
                              orderby value.GetDescription()
                              select value).ToArray();

            var servicoCTes =
                (from TipoServicoCTe value in Enum.GetValues(typeof(TipoServicoCTe)) select value).ToArray();

            var getVersion = new Func<CTeVersao, string>(versao =>
            {
                switch (versao)
                {
                    case CTeVersao.v200: return "2.00";
                    case CTeVersao.v300: return "3.00";
                    default: throw new ArgumentOutOfRangeException(nameof(versao), versao, null);
                }
            });

            // Emissão Normal
            foreach (var codUf in dataSource)
            {
                var sectionName = $"CTe_{codUf}_H";

                var sessao = ini[sectionName];
                var sessaoUsar = ini[sectionName];

                while (sessaoUsar.ContainsKey("Usar"))
                {
                    sessaoUsar = ini[sessaoUsar["Usar"]];
                }

                foreach (var service in servicoCTes)
                {
                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao.ContainsKey(key) ? sessao[key] : sessaoUsar.ContainsKey(key) ? sessaoUsar[key] : "";

                    Servicos[CTeVersao.v300, DFeTipoEmissao.Normal][DFeTipoAmbiente.Homologacao, codUf].Enderecos[service] = url;
                }

                sectionName = $"CTe_{codUf.GetDescription()}_P";
                sessao = ini[sectionName];
                sessaoUsar = ini[sectionName];

                while (sessaoUsar.ContainsKey("Usar"))
                {
                    sessaoUsar = ini[sessaoUsar["Usar"]];
                }

                foreach (var service in servicoCTes)
                {
                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao.ContainsKey(key) ? sessao[key] :
                        sessaoUsar.ContainsKey(key) ? sessaoUsar[key] : "";

                    Servicos[CTeVersao.v300, DFeTipoEmissao.Normal][DFeTipoAmbiente.Producao, codUf]
                        .Enderecos[service] = url;
                }
            }

            //Emissão DPEC
            foreach (var codUf in dataSource)
            {
                var sectionName = string.Empty;

                switch (codUf)
                {
                    case DFeSiglaUF.PE:
                    case DFeSiglaUF.SP:
                    case DFeSiglaUF.MS:
                    case DFeSiglaUF.MT:
                        sectionName = "CTe_SVC-RS_";
                        break;

                    default:
                        sectionName = "CTe_SVC-SP_";
                        break;
                }

                var sessao = ini[sectionName + "H"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.DPEC][DFeTipoAmbiente.Homologacao, codUf][service] = url;
                }

                sessao = ini[sectionName + "P"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.DPEC][DFeTipoAmbiente.Producao, codUf][service] = url;
                }
            }

            //Emissão SVCRS
            foreach (var codUf in dataSource)
            {
                var sectionName = "CTe_SVC-RS_";

                var sessao = ini[sectionName + "H"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.SVCRS][DFeTipoAmbiente.Homologacao, codUf][service] = url;
                }

                sessao = ini[sectionName + "P"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.SVCRS][DFeTipoAmbiente.Producao, codUf][service] = url;
                }
            }

            //Emissão SVCSP
            foreach (var codUf in dataSource)
            {
                var sectionName = "CTe_SVC-SP_";

                var sessao = ini[sectionName + "H"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.SVCSP][DFeTipoAmbiente.Homologacao, codUf][service] = url;
                }

                sessao = ini[sectionName + "P"];
                foreach (var service in servicoCTes)
                {
                    if (service == TipoServicoCTe.RecepcaoEventoAN) continue;

                    var key = $"{service.GetDescription()}_{getVersion(CTeVersao.v300)}";
                    var url = sessao[key];

                    Servicos[CTeVersao.v300, DFeTipoEmissao.SVCSP][DFeTipoAmbiente.Producao, codUf][service] = url;
                }
            }
        }

        #endregion Methods
    }
}


text: Common code for the Podio Objective-C SDKs.


text:
package hr.fer.zari.rasip.tiger.handler;

import hr.fer.zari.rasip.tiger.domain.CollectingUnit;

public class CollectingUnitHandlerFactory {

	public static CollectingUnitHandler handler(CollectingUnit cu) {
		if(cu == null || cu.getType() == null){
			return null;
		}
		String type = cu.getType().getName();

		switch (type) {
		case "GSN":
			return new GSNHandler();
		default:
			return null;
		}
	}
}


text:
<?php

namespace Tests\Homie\Remote;

use BrainExe\Core\EventDispatcher\EventDispatcher;
use Homie\Remote\Controller;
use Homie\Remote\Event\ReceivedEvent;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

class ControllerTest extends TestCase
{
    /**
     * @var Controller
     */
    private $subject;

    /**
     * @var EventDispatcher|MockObject
     */
    private $dispatcher;

    public function setUp()
    {
        $this->dispatcher = $this->createMock(EventDispatcher::class);

        $this->subject = new Controller();
        $this->subject->setEventDispatcher($this->dispatcher);
    }

    public function testAction()
    {
        $code    = 'code';
        $event   = new ReceivedEvent($code);
        $request = new Request();

        $this->dispatcher
            ->expects($this->once())
            ->method('dispatchEvent')
            ->with($event);

        $actual = $this->subject->action($request, $code);

        $this->assertTrue($actual);
    }
}


text:
var path = require("path");
module.exports = DirectoryNamedWebpackPlugin;

function DirectoryNamedWebpackPlugin(options) {
  var optionsToUse = typeof options === "boolean" ? { honorIndex : options } : (options || {});
  this.options = {
    honorIndex: optionsToUse.honorIndex,
    honorPackage: optionsToUse.honorPackage !== false,
    transformFn: optionsToUse.transformFn,
    ignoreFn: optionsToUse.ignoreFn || noop
  };
}

DirectoryNamedWebpackPlugin.prototype.apply = function (resolver) {
  resolver.plugin("directory", resolveDirectory(this.options));
};

function resolveDirectory(options) {
  return function (request, callback) {
    if (options.ignoreFn(request)) {
      return callback();
    }
    var _this = this;
    var dirPath = _this.join(request.path, request.request);
    var dirName = dirPath.substr(dirPath.lastIndexOf(path.sep) + path.sep.length);
    _this.fileSystem.stat(dirPath, function (err, stat) {
      if (err || !stat || !stat.isDirectory()) {
        callback.log && callback.log(dirPath + " doesn't exist or is not a directory (directory named)");
        return callback();
      }

      var attempts = []

      if (options.honorPackage) {
        try {
          var mainFilePath = require(path.resolve(dirPath, 'package.json')).main;

          if (mainFilePath) {
            attempts.push(mainFilePath);
          }
        } catch (e) {
          // No problem, this is optional.
        }
      }

      if (options.honorIndex) {
        attempts.push("index");
      }

      if (options.transformFn) {
        var transformResult = options.transformFn(dirName);

        if (!Array.isArray(transformResult)) {
          transformResult = [ transformResult ];
        }

        transformResult = transformResult.filter(function (attemptName) {
          return typeof attemptName === 'string' && attemptName.length > 0;
        });

        attempts = attempts.concat(transformResult);
      } else {
        attempts.push(dirName);
      }

      _this.forEachBail(
        attempts,
        function (file, innerCallback) {
          var fileRequest = { path: dirPath, query: request.query, request: file };
          _this.doResolve("file", fileRequest, wrap(innerCallback, file));
        },
        function (result) {
          return result ? callback(null, result) : callback();
        }
      );
    });
  };
}

function wrap(callback, file) {
  function wrapper(err, result) {
    if (callback.log) {
      callback.log("directory name file " + file);
    }
    return !err && result ? callback(result) : callback();
  }
  wrapper.log = callback.log;
  wrapper.stack = callback.stack;
  wrapper.missing = callback.missing;
  return wrapper;
}

function noop() {}


text:
package util

// Bytes to Word
func B2W(most byte, least byte) uint16 {
    return uint16(most)<<8 | uint16(least)
}

// Word to Bytes
func W2B(word uint16) (most byte, least byte) {
    most = byte((word >> 8) & 0xFF)
    least = byte(word & 0xFF)
    return
}


text:
'use strict';

describe('ingeniusApp.version module', function() {
  beforeEach(module('ingeniusApp.version'));

  describe('app-version directive', function() {
    it('should print current version', function() {
      module(function($provide) {
        $provide.value('version', 'TEST_VER');
      });
      inject(function($compile, $rootScope) {
        var element = $compile('<span app-version></span>')($rootScope);
        expect(element.text()).toEqual('TEST_VER');
      });
    });
  });
});


text:
/*
 * PaymentSystem.h
 *
 *  Created on: Apr 30, 2014
 *      Author: wilfeli
 */

#ifndef PAYMENTSYSTEM_H_
#define PAYMENTSYSTEM_H_

#include "IAgent.h"
#include "Message.h"

class IPSAgent: virtual public IProducerConsumerContractBDt0{
public:

	virtual ~IPSAgent() {};
	virtual ContractBDt0*  _PS_contract() = 0;
	virtual void _PS_receive_payment(MessagePSSendPayment*) = 0;
	virtual bool _PS_accept_PO(MessagePSSendPayment*) = 0;

};

//class IIssuerPS: public IPSAgent{
//public:
//
//	virtual ~IIssuerPS();
//	virtual bool _PS_accept_PO(MessagePSSendPayment*) = 0;
//
//
//};
//
//
//class IHolderPS: public IPSAgent, virtual public Agent{
//
//};

#endif /* PAYMENTSYSTEM_H_ */


text:
addr="10.99.0.3"
# Password for UCARP communication.
pass="password"
# First node IP and interface for UCARP communication.
nodea_srcip="10.99.0.1"
nodea_ifnet="bge0"
# Second node IP and interface for UCARP communication.
nodeb_srcip="10.99.0.2"
nodeb_ifnet="em3"

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

vhid="1"
upscript="/root/hast/sbin/hastd/vip-up.sh"
downscript="/root/hast/sbin/hastd/vip-down.sh"

ifconfig "${nodea_ifnet}" 2>/dev/null | grep -q "inet ${nodea_srcip} "
if [ $? -eq 0 ]; then
	srcip="${nodea_srcip}"
	ifnet="${nodea_ifnet}"
	node="node A"
fi
ifconfig "${nodeb_ifnet}" 2>/dev/null | grep -q "inet ${nodeb_srcip} "
if [ $? -eq 0 ]; then
	if [ -n "${srcip}" -o -n "${ifnet}" ]; then
		echo "Unable to determine which node is this (both match)." >/dev/stderr
		exit 1
	fi
	srcip="${nodeb_srcip}"
	ifnet="${nodeb_ifnet}"
	node="node B"
fi
if [ -z "${srcip}" -o -z "${ifnet}" ]; then
	echo "Unable to determine which node is this (none match)." >/dev/stderr
	exit 1
fi
ucarp -i ${ifnet} -s ${srcip} -v ${vhid} -a ${addr} -p ${pass} -u "${upscript}" -d "${downscript}"


text:
import {TestBed, async} from '@angular/core/testing';
import {DatatableComponent} from './datatable.component';
import {NgxDatatableModule} from '../datatable.module';
describe('Datatable component', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [NgxDatatableModule]
    });
  });

  beforeEach(async(() => {
    TestBed.compileComponents();
  }));

  describe('When the column is sorted', () => {
    it('should sort a column with Date values', () => {
      const fixture = TestBed.createComponent(DatatableComponent);
      const initialRows = [
        {birthDate: new Date(1980, 12, 1)},
        {birthDate: new Date(1978, 8, 5)},
        {birthDate: new Date(1995, 4, 3)}
      ];

      const columns = [
        {
          prop: 'birthDate'
        }
      ];

      fixture.componentInstance.rows = initialRows;
      fixture.componentInstance.columns = columns;

      fixture.detectChanges();

      fixture.componentInstance.onColumnSort({
        sorts: [{prop: 'birthDate', dir: 'desc'}]
      });

      expect(fixture.componentInstance.rows[0]).toBe(initialRows[2]);
      expect(fixture.componentInstance.rows[1]).toBe(initialRows[0]);
      expect(fixture.componentInstance.rows[2]).toBe(initialRows[1]);
    });

    it('should sort a column with number values', () => {
      const fixture = TestBed.createComponent(DatatableComponent);
      const initialRows = [
        {id: 5},
        {id: 20},
        {id: 12}
      ];

      const columns = [
        {
          prop: 'id'
        }
      ];

      fixture.componentInstance.rows = initialRows;
      fixture.componentInstance.columns = columns;

      fixture.detectChanges();

      fixture.componentInstance.onColumnSort({
        sorts: [{prop: 'id', dir: 'desc'}]
      });

      expect(fixture.componentInstance.rows[0]).toBe(initialRows[1]);
      expect(fixture.componentInstance.rows[1]).toBe(initialRows[2]);
      expect(fixture.componentInstance.rows[2]).toBe(initialRows[0]);
    });

    it('should sort a column with string values', () => {
      const fixture = TestBed.createComponent(DatatableComponent);
      const initialRows = [
        {product: 'Computers'},
        {product: 'Bikes'},
        {product: 'Smartphones'}
      ];

      const columns = [
        {
          prop: 'product'
        }
      ];

      fixture.componentInstance.rows = initialRows;
      fixture.componentInstance.columns = columns;

      fixture.detectChanges();

      fixture.componentInstance.onColumnSort({
        sorts: [{prop: 'product', dir: 'desc'}]
      });

      expect(fixture.componentInstance.rows[0]).toBe(initialRows[2]);
      expect(fixture.componentInstance.rows[1]).toBe(initialRows[0]);
      expect(fixture.componentInstance.rows[2]).toBe(initialRows[1]);
    });
  });

  describe('When the column is sorted with a custom comparator', () => {

    it('should return a new array', () => {
      const fixture = TestBed.createComponent(DatatableComponent);
      const initialRows = [
        {id: 1},
        {id: 2},
        {id: 3}
      ];

      const columns = [
        {
          prop: 'foo',
          comparator: (propA: string, propB: string) => {
            if (propA.toLowerCase() > propB.toLowerCase()) return -1;
            if (propA.toLowerCase() < propB.toLowerCase()) return 1;
          }
        }
      ];

      fixture.componentInstance.rows = initialRows;
      fixture.componentInstance.columns = columns;

      fixture.detectChanges();

      expect(fixture.componentInstance.rows).toBe(initialRows);

      fixture.componentInstance.onColumnSort({
        sorts: [{prop: 'foo', dir: 'desc'}]
      });

      fixture.componentInstance.sort
        .subscribe();

      expect(fixture.componentInstance.rows).not.toBe(initialRows);
    });
  });

  it('should set offset to 0 when sorting by a column', () => {
    const fixture = TestBed.createComponent(DatatableComponent);
    const initialRows = [
      {id: 1},
      {id: 2},
      {id: 3}
    ];

    const columns = [
      {
        prop: 'id'
      }
    ];

    fixture.componentInstance.rows = initialRows;
    fixture.componentInstance.columns = columns;
    fixture.componentInstance.offset = 1;

    fixture.detectChanges();

    fixture.componentInstance.onColumnSort({
      sorts: [{prop: 'id', dir: 'desc'}]
    });

    expect(fixture.componentInstance.offset).toBe(0);
  });

  describe('table with numeric prop', () => {
    it('should support array data', () => {
      const fixture = TestBed.createComponent(DatatableComponent);

      const tableInstance = fixture.componentInstance;
      tableInstance.rows = [
        ['Hello', 123]
      ];

      tableInstance.columns = [
        { prop: 0 },
        { prop: 1 }
      ];

      // previously, an exception was thrown from column-helper.ts setColumnDefaults()
      fixture.detectChanges();

      expect(tableInstance.columns).toBeTruthy();
    });
  });

});


text:
<?xml version="1.0"?>
<cd:ProductDefinition xmlns:cd="http://www.stcorp.nl/coda/definition/2008/07" id="CAL_LID_L2_MLay" format="hdf4" last-modified="2017-06-20">
</cd:ProductDefinition>