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

namespace Koopakiller.ForumSamples.OpenXml.PowerPoint.Test
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            if (args.Length == 0) { args = new[] { @"..\..\..\Sample Files\PowerPoint.pptx" }; }
            if (args.Length != 1) { throw new ArgumentOutOfRangeException(nameof(args)); }

            Console.WriteLine($"Filename: {args[0]}");
            var path = ZipFile.Extract(args[0]);
            //Process.Start(path);

            var p = new Presentation(path);
            Print(p);

            ZipFile.Zip(path, "Test.pptx");

            Console.ReadKey();
        }

        private static void Print(Presentation p)
        {
            Console.WriteLine($"{p.Slides.Count} slides found");
            Console.WriteLine();
            for (var i = 1; i <= p.Slides.Count; i++)
            {
                Console.WriteLine($"Slide {i}");
                Console.WriteLine(" Comments: ");
                PrintComments(p.Slides[i - 1].Comments, 2);
                Console.WriteLine();
            }
        }

        private static void PrintComments(IList<Comment> comments, int x)
        {
            foreach (var comment in comments)
            {
                Console.WriteLine($"{new string(' ', x)}{comment.Author.Name} ({comment.Author.Initials}) wrote \"{comment.Text}\" at {comment.Timestamp}");
                PrintComments(comment.SubComments, x + 2);
            }
        }
    }
}


text:
For now, ether one default flow may exist with untagged traffic routing, or several flows with tagged VLANs, but not both.

## Proposal

Extend system with ability to create flows with the same port, default and VLAN tagged.

For default flow, install ingress switch rule with lower priority than VLAN tagged. It will passing port traffic, that is not matched by VLAN specific switch rule (VLAN tagged)

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * Represents a VPN gateway resource.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VpnGateway extends com.google.api.client.json.GenericJson {

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String creationTimestamp;

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String description;

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.math.BigInteger id;

  /**
   * [Output Only] Type of resource. Always compute#vpnGateway for VPN gateways.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * A fingerprint for the labels being applied to this VpnGateway, which is essentially a hash of
   * the labels set used for optimistic locking. The fingerprint is initially generated by Compute
   * Engine and changes after every request to modify or update labels. You must always provide an
   * up-to-date fingerprint hash in order to update or change labels, otherwise the request will
   * fail with error 412 conditionNotMet.
   *
   * To see the latest fingerprint, make a get() request to retrieve an VpnGateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String labelFingerprint;

  /**
   * Labels to apply to this VpnGateway resource. These can be later modified by the setLabels
   * method. Each label key/value must comply with RFC1035. Label values may be empty.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.String> labels;

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
   * gateway is created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String network;

  /**
   * [Output Only] URL of the region where the VPN gateway resides.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String region;

  /**
   * [Output Only] Server-defined URL for the resource.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String selfLink;

  /**
   * [Output Only] A list of interfaces on this VPN gateway.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<VpnGatewayVpnGatewayInterface> vpnInterfaces;

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * @return value or {@code null} for none
   */
  public java.lang.String getCreationTimestamp() {
    return creationTimestamp;
  }

  /**
   * [Output Only] Creation timestamp in RFC3339 text format.
   * @param creationTimestamp creationTimestamp or {@code null} for none
   */
  public VpnGateway setCreationTimestamp(java.lang.String creationTimestamp) {
    this.creationTimestamp = creationTimestamp;
    return this;
  }

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * @return value or {@code null} for none
   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * An optional description of this resource. Provide this property when you create the resource.
   * @param description description or {@code null} for none
   */
  public VpnGateway setDescription(java.lang.String description) {
    this.description = description;
    return this;
  }

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * @return value or {@code null} for none
   */
  public java.math.BigInteger getId() {
    return id;
  }

  /**
   * [Output Only] The unique identifier for the resource. This identifier is defined by the server.
   * @param id id or {@code null} for none
   */
  public VpnGateway setId(java.math.BigInteger id) {
    this.id = id;
    return this;
  }

  /**
   * [Output Only] Type of resource. Always compute#vpnGateway for VPN gateways.
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * [Output Only] Type of resource. Always compute#vpnGateway for VPN gateways.
   * @param kind kind or {@code null} for none
   */
  public VpnGateway setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * A fingerprint for the labels being applied to this VpnGateway, which is essentially a hash of
   * the labels set used for optimistic locking. The fingerprint is initially generated by Compute
   * Engine and changes after every request to modify or update labels. You must always provide an
   * up-to-date fingerprint hash in order to update or change labels, otherwise the request will
   * fail with error 412 conditionNotMet.
   *
   * To see the latest fingerprint, make a get() request to retrieve an VpnGateway.
   * @see #decodeLabelFingerprint()
   * @return value or {@code null} for none
   */
  public java.lang.String getLabelFingerprint() {
    return labelFingerprint;
  }

  /**
   * A fingerprint for the labels being applied to this VpnGateway, which is essentially a hash of
   * the labels set used for optimistic locking. The fingerprint is initially generated by Compute
   * Engine and changes after every request to modify or update labels. You must always provide an
   * up-to-date fingerprint hash in order to update or change labels, otherwise the request will
   * fail with error 412 conditionNotMet.
   *
   * To see the latest fingerprint, make a get() request to retrieve an VpnGateway.
   * @see #getLabelFingerprint()
   * @return Base64 decoded value or {@code null} for none
   *
   * @since 1.14
   */
  public byte[] decodeLabelFingerprint() {
    return com.google.api.client.util.Base64.decodeBase64(labelFingerprint);
  }

  /**
   * A fingerprint for the labels being applied to this VpnGateway, which is essentially a hash of
   * the labels set used for optimistic locking. The fingerprint is initially generated by Compute
   * Engine and changes after every request to modify or update labels. You must always provide an
   * up-to-date fingerprint hash in order to update or change labels, otherwise the request will
   * fail with error 412 conditionNotMet.
   *
   * To see the latest fingerprint, make a get() request to retrieve an VpnGateway.
   * @see #encodeLabelFingerprint()
   * @param labelFingerprint labelFingerprint or {@code null} for none
   */
  public VpnGateway setLabelFingerprint(java.lang.String labelFingerprint) {
    this.labelFingerprint = labelFingerprint;
    return this;
  }

  /**
   * A fingerprint for the labels being applied to this VpnGateway, which is essentially a hash of
   * the labels set used for optimistic locking. The fingerprint is initially generated by Compute
   * Engine and changes after every request to modify or update labels. You must always provide an
   * up-to-date fingerprint hash in order to update or change labels, otherwise the request will
   * fail with error 412 conditionNotMet.
   *
   * To see the latest fingerprint, make a get() request to retrieve an VpnGateway.
   * @see #setLabelFingerprint()
   *
   *

   * The value is encoded Base64 or {@code null} for none.
   *

   *
   * @since 1.14
   */
  public VpnGateway encodeLabelFingerprint(byte[] labelFingerprint) {
    this.labelFingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(labelFingerprint);
    return this;
  }

  /**
   * Labels to apply to this VpnGateway resource. These can be later modified by the setLabels
   * method. Each label key/value must comply with RFC1035. Label values may be empty.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.String> getLabels() {
    return labels;
  }

  /**
   * Labels to apply to this VpnGateway resource. These can be later modified by the setLabels
   * method. Each label key/value must comply with RFC1035. Label values may be empty.
   * @param labels labels or {@code null} for none
   */
  public VpnGateway setLabels(java.util.Map<String, java.lang.String> labels) {
    this.labels = labels;
    return this;
  }

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Name of the resource. Provided by the client when the resource is created. The name must be
   * 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
   * long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
   * character must be a lowercase letter, and all following characters must be a dash, lowercase
   * letter, or digit, except the last character, which cannot be a dash.
   * @param name name or {@code null} for none
   */
  public VpnGateway setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  /**
   * URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
   * gateway is created.
   * @return value or {@code null} for none
   */
  public java.lang.String getNetwork() {
    return network;
  }

  /**
   * URL of the network to which this VPN gateway is attached. Provided by the client when the VPN
   * gateway is created.
   * @param network network or {@code null} for none
   */
  public VpnGateway setNetwork(java.lang.String network) {
    this.network = network;
    return this;
  }

  /**
   * [Output Only] URL of the region where the VPN gateway resides.
   * @return value or {@code null} for none
   */
  public java.lang.String getRegion() {
    return region;
  }

  /**
   * [Output Only] URL of the region where the VPN gateway resides.
   * @param region region or {@code null} for none
   */
  public VpnGateway setRegion(java.lang.String region) {
    this.region = region;
    return this;
  }

  /**
   * [Output Only] Server-defined URL for the resource.
   * @return value or {@code null} for none
   */
  public java.lang.String getSelfLink() {
    return selfLink;
  }

  /**
   * [Output Only] Server-defined URL for the resource.
   * @param selfLink selfLink or {@code null} for none
   */
  public VpnGateway setSelfLink(java.lang.String selfLink) {
    this.selfLink = selfLink;
    return this;
  }

  /**
   * [Output Only] A list of interfaces on this VPN gateway.
   * @return value or {@code null} for none
   */
  public java.util.List<VpnGatewayVpnGatewayInterface> getVpnInterfaces() {
    return vpnInterfaces;
  }

  /**
   * [Output Only] A list of interfaces on this VPN gateway.
   * @param vpnInterfaces vpnInterfaces or {@code null} for none
   */
  public VpnGateway setVpnInterfaces(java.util.List<VpnGatewayVpnGatewayInterface> vpnInterfaces) {
    this.vpnInterfaces = vpnInterfaces;
    return this;
  }

  @Override
  public VpnGateway set(String fieldName, Object value) {
    return (VpnGateway) super.set(fieldName, value);
  }

  @Override
  public VpnGateway clone() {
    return (VpnGateway) super.clone();
  }

}


text:
package io.realm.examples.newsreader.model.network;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.io.IOException;
import java.util.List;

import io.realm.RealmList;
import io.realm.examples.newsreader.model.entity.NYTimesMultimedium;

public class RealmListNYTimesMultimediumDeserializer extends JsonDeserializer<List<NYTimesMultimedium>> {

    private ObjectMapper objectMapper;

    public RealmListNYTimesMultimediumDeserializer() {
        objectMapper = new ObjectMapper();
    }

    @Override
    public List<NYTimesMultimedium> deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        RealmList<NYTimesMultimedium> list = new RealmList<>();

        TreeNode treeNode = parser.getCodec().readTree(parser);
        if (!(treeNode instanceof ArrayNode)) {
            return list;
        }

        ArrayNode arrayNode = (ArrayNode) treeNode;
        for (JsonNode node : arrayNode) {
            NYTimesMultimedium nyTimesMultimedium =
                    objectMapper.treeToValue(node, NYTimesMultimedium.class);
            list.add(nyTimesMultimedium);
        }
        return list;
    }
}


text:
require 'test_helper'

class KindsHelperTest < ActionView::TestCase
end


text:
ApiController = RouteController.extend({

});


text:
module Sequel
  module Plugins
    # The association_pks plugin adds association_pks and association_pks=
    # instance methods to the model class for each association added.  These
    # methods allow for easily returning the primary keys of the associated
    # objects, and easily modifying which objects are associated:
    #
    #   Artist.one_to_many :albums
    #   artist = Artist[1]
    #   artist.album_pks # [1, 2, 3]
    #   artist.album_pks = [2, 4]
    #   artist.album_pks # [2, 4]
    #
    # Note that it uses the singular form of the association name. Also note
    # that the setter both associates to new primary keys not in the assocation
    # and disassociates from primary keys not provided to the method.
    #
    # This plugin makes modifications directly to the underlying tables,
    # it does not create or return any model objects, and therefore does
    # not call any callbacks.  If you have any association callbacks,
    # you probably should not use the setter methods.
    #
    # If an association uses the :delay_pks option, you can set the associated
    # pks for new objects, and the setting will not be persisted until after the
    # object has been created in the database.  Additionally, if an association
    # uses the :delay_pks=>:all option, you can set the associated pks for existing
    # objects, and the setting will not be persisted until after the object has
    # been saved.
    #
    # Usage:
    #
    #   # Make all model subclass *_to_many associations have association_pks
    #   # methods (called before loading subclasses)
    #   Sequel::Model.plugin :association_pks
    #
    #   # Make the Album *_to_many associations have association_pks
    #   # methods (called before the association methods)
    #   Album.plugin :association_pks
    module AssociationPks
      module ClassMethods
        private

        # Define a association_pks method using the block for the association reflection
        def def_association_pks_methods(opts)
          association_module_def(:"#{singularize(opts[:name])}_pks", opts){_association_pks_getter(opts)}
          association_module_def(:"#{singularize(opts[:name])}_pks=", opts){|pks| _association_pks_setter(opts, pks)} unless opts[:read_only]
        end

        # Add a getter that checks the join table for matching records and
        # a setter that deletes from or inserts into the join table.
        def def_many_to_many(opts)
          super

          return if opts[:type] == :one_through_one

          # Grab values from the reflection so that the hash lookup only needs to be
          # done once instead of inside every method call.
          lk, lpk, rk = opts.values_at(:left_key, :left_primary_key, :right_key)
          clpk = lpk.is_a?(Array)
          crk = rk.is_a?(Array)

          opts[:pks_getter] = if clpk
            lambda do
              h = {}
              lk.zip(lpk).each{|k, pk| h[k] = get_column_value(pk)}
              _join_table_dataset(opts).filter(h).select_map(rk)
            end
          else
            lambda do
              _join_table_dataset(opts).filter(lk=>get_column_value(lpk)).select_map(rk)
            end
          end

          opts[:pks_setter] = lambda do |pks|
            pks = send(crk ? :convert_cpk_array : :convert_pk_array, opts, pks)
            checked_transaction do
              if clpk
                lpkv = lpk.map{|k| get_column_value(k)}
                cond = lk.zip(lpkv)
              else
                lpkv = get_column_value(lpk)
                cond = {lk=>lpkv}
              end
              ds = _join_table_dataset(opts).filter(cond)
              ds.exclude(rk=>pks).delete
              pks -= ds.select_map(rk)
              lpkv = Array(lpkv)
              key_array = crk ? pks.map{|pk| lpkv + pk} : pks.map{|pk| lpkv + [pk]}
              key_columns = Array(lk) + Array(rk)
              ds.import(key_columns, key_array)
            end
          end

          def_association_pks_methods(opts)
        end

        # Add a getter that checks the association dataset and a setter
        # that updates the associated table.
        def def_one_to_many(opts)
          super

          return if opts[:type] == :one_to_one

          key = opts[:key]

          opts[:pks_getter] = lambda do
            send(opts.dataset_method).select_map(opts.associated_class.primary_key)
          end

          opts[:pks_setter] = lambda do |pks|
            primary_key = opts.associated_class.primary_key

            pks = if primary_key.is_a?(Array)
              convert_cpk_array(opts, pks)
            else
              convert_pk_array(opts, pks)
            end

            pkh = {primary_key=>pks}

            if key.is_a?(Array)
              h = {}
              nh = {}
              key.zip(pk).each do|k, v|
                h[k] = v
                nh[k] = nil
              end
            else
              h = {key=>pk}
              nh = {key=>nil}
            end

            checked_transaction do
              ds = send(opts.dataset_method)
              ds.unfiltered.filter(pkh).update(h)
              ds.exclude(pkh).update(nh)
            end
          end

          def_association_pks_methods(opts)
        end
      end

      module InstanceMethods
        # After creating an object, if there are any saved association pks,
        # call the related association pks setters.
        def after_save
          if assoc_pks = @_association_pks
            assoc_pks.each do |name, pks|
              instance_exec(pks, &model.association_reflection(name)[:pks_setter]) unless pks.empty?
            end
            @_association_pks = nil
          end
          super
        end

        # Clear the associated pks if explicitly refreshing.
        def refresh
          @_association_pks = nil
          super
        end

        private

        # Return the primary keys of the associated objects.
        # If the receiver is a new object, return any saved
        # pks, or an empty array if no pks have been saved.
        def _association_pks_getter(opts)
          delay = opts[:delay_pks]
          if new? && delay
            (@_association_pks ||= {})[opts[:name]] ||= []
          elsif delay == :always && @_association_pks && (objs = @_association_pks[opts[:name]])
            objs
          else
            instance_exec(&opts[:pks_getter])
          end
        end

        # Update which objects are associated to the receiver.
        # If the receiver is a new object, save the pks
        # so the update can happen after the received has been saved.
        def _association_pks_setter(opts, pks)
          delay = opts[:delay_pks]
          if (new? && delay) || (delay == :always)
            modified!
            (@_association_pks ||= {})[opts[:name]] = pks
          else
            instance_exec(pks, &opts[:pks_setter])
          end
        end

        # If any of associated class's composite primary key column types is integer,
        # typecast the appropriate values to integer before using them.
        def convert_cpk_array(opts, cpks)
          if klass = opts.associated_class and sch = klass.db_schema and (cols = sch.values_at(*klass.primary_key)).all? and (convs = cols.map{|c| c[:type] == :integer}).any?
            cpks.map do |cpk|
              cpk.zip(convs).map do |pk, conv|
                conv ? model.db.typecast_value(:integer, pk) : pk
              end
            end
          else
            cpks
          end
        end

        # If the associated class's primary key column type is integer,
        # typecast all provided values to integer before using them.
        def convert_pk_array(opts, pks)
          if klass = opts.associated_class and sch = klass.db_schema and col = sch[klass.primary_key] and col[:type] == :integer
            pks.map{|pk| model.db.typecast_value(:integer, pk)}
          else
            pks
          end
        end
      end
    end
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.javaee7.json.object.reader;

import java.io.File;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.json.JSONException;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;

/**
 * @author Arun Gupta
 */
@RunWith(Arquillian.class)
public class JsonReaderFromReaderTest {

    @Deployment
    public static Archive<?> deploy() {
        File[] requiredLibraries = Maven.resolver().loadPomFromFile("pom.xml")
                .resolve("org.json:json", "org.skyscreamer:jsonassert")
                .withTransitivity().asFile();

        return ShrinkWrap.create(WebArchive.class)
                .addAsLibraries(requiredLibraries);
    }

    @Test
    public void testEmptyObject() throws JSONException {
        JsonReader jsonReader = Json.createReader(new StringReader("{}"));
        JsonObject json = jsonReader.readObject();

        assertNotNull(json);
        assertTrue(json.isEmpty());
    }

    @Test
    public void testSimpleObjectWithTwoElements() throws JSONException {
        JsonReader jsonReader = Json.createReader(new StringReader("{"
                + "  \"apple\":\"red\","
                + "  \"banana\":\"yellow\""
                + "}"));
        JsonObject json = jsonReader.readObject();

        assertNotNull(json);
        assertFalse(json.isEmpty());
        assertTrue(json.containsKey("apple"));
        assertEquals("red", json.getString("apple"));
        assertTrue(json.containsKey("banana"));
        assertEquals("yellow", json.getString("banana"));
    }

    @Test
    public void testArray() throws JSONException {
        JsonReader jsonReader = Json.createReader(new StringReader("["
                + "  { \"apple\":\"red\" },"
                + "  { \"banana\":\"yellow\" }"
                + "]"));
        JsonArray jsonArr = jsonReader.readArray();
        assertNotNull(jsonArr);
        assertEquals(2, jsonArr.size());

        JSONAssert.assertEquals("{\"apple\":\"red\"}", jsonArr.get(0).toString(), JSONCompareMode.STRICT);
        JSONAssert.assertEquals("{\"banana\":\"yellow\"}", jsonArr.get(1).toString(), JSONCompareMode.STRICT);
    }

    @Test
    public void testNestedStructure() throws JSONException {
        JsonReader jsonReader = Json.createReader(new StringReader("{"
                + "  \"title\":\"The Matrix\","
                + "  \"year\":1999,"
                + "  \"cast\":["
                + "    \"Keanu Reaves\","
                + "    \"Laurence Fishburne\","
                + "    \"Carrie-Anne Moss\""
                + "  ]"
                + "}"));
        JsonObject json = jsonReader.readObject();

        assertNotNull(json);
        assertFalse(json.isEmpty());
        assertTrue(json.containsKey("title"));
        assertEquals("The Matrix", json.getString("title"));
        assertTrue(json.containsKey("year"));
        assertEquals(1999, json.getInt("year"));
        assertTrue(json.containsKey("cast"));
        JsonArray jsonArr = json.getJsonArray("cast");
        assertNotNull(jsonArr);
        assertEquals(3, jsonArr.size());

        JSONAssert.assertEquals("["
                + "    \"Keanu Reaves\","
                + "    \"Laurence Fishburne\","
                + "    \"Carrie-Anne Moss\""
                + "  ]", jsonArr.toString(), JSONCompareMode.STRICT);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.client;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.util.Base64;
import java.util.List;

import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature;
import static com.google.common.collect.Lists.newArrayList;
import static org.testng.Assert.assertEquals;

public class TestQueryResults
{
    @Test
    public void testFixData()
    {
        assertQueryResult("bigint", 1000, 1000L);
        assertQueryResult("integer", 100, 100);
        assertQueryResult("smallint", 10, (short) 10);
        assertQueryResult("tinyint", 1, (byte) 1);
        assertQueryResult("boolean", true, true);
        assertQueryResult("date", "2017-07-01", "2017-07-01");
        assertQueryResult("decimal", "2.15", "2.15");
        assertQueryResult("real", 100.23456, (float) 100.23456);
        assertQueryResult("double", 100.23456D, 100.23456);
        assertQueryResult("interval day to second", "INTERVAL '2' DAY", "INTERVAL '2' DAY");
        assertQueryResult("interval year to month", "INTERVAL '3' MONTH", "INTERVAL '3' MONTH");
        assertQueryResult("timestamp", "2001-08-22 03:04:05.321", "2001-08-22 03:04:05.321");
        assertQueryResult("timestamp with time zone", "2001-08-22 03:04:05.321 America/Los_Angeles", "2001-08-22 03:04:05.321 America/Los_Angeles");
        assertQueryResult("time", "01:02:03.456", "01:02:03.456");
        assertQueryResult("time with time zone", "01:02:03.456 America/Los_Angeles", "01:02:03.456 America/Los_Angeles");
        assertQueryResult("varbinary", "garbage", Base64.getDecoder().decode("garbage"));
        assertQueryResult("varchar", "teststring", "teststring");
        assertQueryResult("char", "abc", "abc");
        assertQueryResult("row(foo bigint,bar bigint)", ImmutableList.of(1, 2), ImmutableMap.of("foo", 1L, "bar", 2L));
        assertQueryResult("array(bigint)", ImmutableList.of(1, 2, 4), ImmutableList.of(1L, 2L, 4L));
        assertQueryResult("map(bigint,bigint)", ImmutableMap.of(1, 3, 2, 4), ImmutableMap.of(1L, 3L, 2L, 4L));
        assertQueryResult("json", "{\"json\": {\"a\": 1}}", "{\"json\": {\"a\": 1}}");
        assertQueryResult("ipaddress", "1.2.3.4", "1.2.3.4");
    }

    private void assertQueryResult(String type, Object data, Object expected)
    {
        List<List<Object>> rows = newArrayList(QueryResults.fixData(
                ImmutableList.of(new Column("test", type, new ClientTypeSignature(parseTypeSignature(type)))),
                ImmutableList.of(ImmutableList.of(data))));
        assertEquals(rows.size(), 1);
        assertEquals(rows.get(0).size(), 1);
        assertEquals(rows.get(0).get(0), expected);
    }
}


text:
using System.Collections.Immutable;
using System.Text;
using System.Threading;
using CodeContractNullability.Utilities;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;

namespace CodeContractNullability.Test.TestDataBuilders
{
    internal sealed class AnalyzerSettingsBuilder : ITestDataBuilder<AnalyzerSettings>
    {
        private bool disableReportOnNullableValueTypes;

        [NotNull]
        public AnalyzerSettingsBuilder DisableReportOnNullableValueTypes
        {
            get
            {
                disableReportOnNullableValueTypes = true;
                return this;
            }
        }

        public AnalyzerSettings Build()
        {
            return new AnalyzerSettings(disableReportOnNullableValueTypes);
        }

        [NotNull]
        public static AnalyzerOptions ToOptions([NotNull] AnalyzerSettings settings)
        {
            Guard.NotNull(settings, nameof(settings));

            string content = SettingsProvider.ToFileContent(settings);
            return ToOptions(content);
        }

        [NotNull]
        public static AnalyzerOptions ToOptions([NotNull] string settingsText)
        {
            Guard.NotNull(settingsText, nameof(settingsText));

            AdditionalText additionalText = new FakeAdditionalText(settingsText);
            return new AnalyzerOptions(ImmutableArray.Create(additionalText));
        }

        private sealed class FakeAdditionalText : AdditionalText
        {
            [NotNull]
            private readonly SourceText sourceText;

            [NotNull]
            public override string Path { get; } = SettingsProvider.SettingsFileName;

            public FakeAdditionalText([NotNull] string content)
            {
                sourceText = new FakeSourceText(content, SettingsProvider.CreateEncoding());
            }

            [NotNull]
            public override SourceText GetText(CancellationToken cancellationToken = default)
            {
                return sourceText;
            }

            private sealed class FakeSourceText : SourceText
            {
                [NotNull]
                private readonly string content;

                [NotNull]
                public override Encoding Encoding { get; }

                public override int Length => content.Length;

                public override char this[int position] => content[position];

                public FakeSourceText([NotNull] string content, [NotNull] Encoding encoding)
                {
                    Guard.NotNull(content, nameof(content));
                    Guard.NotNull(encoding, nameof(encoding));

                    this.content = content;
                    Encoding = encoding;
                }

                public override void CopyTo(int sourceIndex, [NotNull] char[] destination, int destinationIndex, int count)
                {
                    content.CopyTo(sourceIndex, destination, destinationIndex, count);
                }
            }
        }
    }
}


text:
namespace caffe2 {

// Storage orders that are often used in the image applications.
enum StorageOrder {
  UNKNOWN = 0,
  NHWC = 1,
  NCHW = 2,
};

inline StorageOrder StringToStorageOrder(const string& str) {
  if (str == "NHWC" || str == "nhwc") {
    return StorageOrder::NHWC;
  } else if (str == "NCHW" || str == "nchw") {
    return StorageOrder::NCHW;
  } else {
    LOG(ERROR) << "Unknown storage order string: " << str;
    return StorageOrder::UNKNOWN;
  }
}

inline constexpr char NameScopeSeparator() { return '/'; }

// From TypeMeta to caffe2::DataType protobuffer enum.
CAFFE2_API TensorProto::DataType TypeMetaToDataType(const TypeMeta& meta);

// From caffe2::DataType protobuffer enum to TypeMeta
CAFFE2_API const TypeMeta& DataTypeToTypeMeta(const TensorProto::DataType& dt);

}  // namespace caffe2

///////////////////////////////////////////////////////////////////////////////
// at::Half is defined in ATen/core/Half.h. Currently half float operators are
// mainly on CUDA gpus.
// The reason we do not directly use the cuda __half data type is because that
// requires compilation with nvcc. The float16 data type should be compatible
// with the cuda __half data type, but will allow us to refer to the data type
// without the need of cuda.
static_assert(sizeof(unsigned short) == 2,
              "Short on this platform is not 16 bit.");
namespace caffe2 {
// Helpers to avoid using typeinfo with -rtti
template <typename T>
inline bool fp16_type();

template <>
inline bool fp16_type<at::Half>() {
  return true;
}

template <typename T>
inline bool fp16_type() {
  return false;
}

}  // namespace caffe2

#endif  // CAFFE2_CORE_TYPES_H_


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using File = System.IO.File;

namespace hoTools.Utils.Configuration
{
    public sealed class HoToolsGlobalCfg: IHoToolsGlobalCfg
    {
        string _sqlPaths;
        string[] _lSqlPaths;
        string _linqPaths;
        string[] _lLinqPaths;

        string _extensionPaths;
        string[] _lExtensionPaths;

        // Class to administer Extensions

        // the owner of the windows, used to prevent modal windows in background

        HoToolsGlobalCfg()
        {

        }

        public Extensions.Extension Extensions { get; set; }

        /// <summary>
        /// Access HoToolsGlobalCfg.Instance to get the singleton object.
        /// Then call methods on that instance.
        /// </summary>
        public static HoToolsGlobalCfg Instance { get; } = new HoToolsGlobalCfg();

        /// <summary>
        /// The owner of all windows. Used to prevent modal windows stuck in background.
        /// </summary>
        public Control Owner { get; set; }

        /// <summary>
        /// IsLinqSupported
        /// </summary>
        public bool IsLinqPadSupported { get; set; }

        /// <summary>
        /// Use the LINQPad connection and not the EA connection
        /// </summary>
        public bool UseLinqPadConnection { get; set; }

        /// <summary>
        /// Use the LINQPad connection and not the EA connection
        /// </summary>
        public string LinqPadConnectionPath { get; set; }

        /// <summary>
        /// Output LINQPad results to HTML
        /// </summary>
        public bool LinqPadOutputHtml { get; set; }

        /// <summary>
        /// LINQPad LPRun.exe path to run a query from hoTools
        /// </summary>
        public string LprunPath { get; set; }

        /// <summary>
        /// Temp folder hoTools for e.g storing temporary query results from LINQPad
        /// </summary>
        public string TempFolder { get; set; }

        /// <summary>
        /// hoTools config path (..user\<users>\AppData\Roaming\ho\hoTools\)
        /// </summary>
        public string ConfigPath { get; set; }

        /// <summary>
        /// JasonFilePath to load configurations
        /// </summary>
        public string JasonFilePath { get; set; }

        #region ExtensionPath

        /// <summary>
        ///  Set hoTools SQL path from Settings to search for SQL files.
        /// </summary>
        /// <param name="paths"></param>
        public void SetExtensionPaths(string paths)
        {
            _extensionPaths = paths;
            _lExtensionPaths = paths.Split(';');
        }
        #endregion
        /// <summary>
        /// Get the absolute file name. It searches according to the in settings specified SQL path. If the file don't exists it return "".
        /// </summary>
        /// <param name="extensionFileName"></param>
        /// <returns></returns>
        public string GetExtensionFileName(string extensionFileName)
        {
            return GetFileNameFromPath(_lExtensionPaths, extensionFileName);

        }
        /// <summary>
        /// Get complete extension filepath from file name
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string GetExtensionFileLong(string fileName)
        {
            return FileNameLong(GetExtensionListFileCompleteName(), fileName);
        }

        /// <summary>
        /// Get list of Extension files of SQL path
        /// </summary>
        /// <returns></returns>
        public List<string> GetExtensionListFileCompleteName()
        {
            return ExtentionFiles(_lExtensionPaths);

        }
        /// <summary>
        /// returns extension file names (*.exe,*.dll) according to the specified path parameter
        /// </summary>
        /// <param name="lPaths"></param>
        /// <returns></returns>
        private List<string> ExtentionFiles(string[] lPaths)
        {
            List<string> files = new List<string>();
            // over all files
            foreach (string path in lPaths)
            {
                if (Directory.Exists(path))
                {
                    files.AddRange(Directory.GetFiles(path, "*.exe"));
                    files.AddRange(Directory.GetFiles(path, "*.dll"));
                }
            }
            for (int i = files.Count - 1; i >= 0; i = i - 1)
            {
               if ( files[i].ToLower().Contains("interop") || files[i].ToLower().Contains("sparxsystem")) files.RemoveAt(i);
            }
            return files;
        }

        /// <summary>
        /// Get list of sql paths
        /// </summary>
        /// <returns></returns>
        public List<string> GetListExtensionPaths()
        {
            return _lExtensionPaths.ToList();
        }

        #region SqlPath
        public string GetSqlPaths()
        {
            return _sqlPaths;
        }
        /// <summary>
        /// Get list of sql paths
        /// </summary>
        /// <returns></returns>
        public List<string> GetListSqlPaths()
        {
            return _lSqlPaths.ToList();
        }
        /// <summary>
        /// Get initial SQL path
        /// </summary>
        /// <returns></returns>
        public string GetInitialSqlPath()
        {
            if (_lSqlPaths.Length == 0) return @"c:\temp\";
            return _lSqlPaths[0];
        }
        /// <summary>
        ///  Set hoTools SQL path from Settings to search for SQL files.
        /// </summary>
        /// <param name="paths"></param>
        public void SetSqlPaths(string paths)
        {
            _sqlPaths = paths;
            _lSqlPaths = paths.Split(';');
        }
        #endregion

        #region LinqPath
        public string GetLinqPaths()
        {
            return _linqPaths;
        }
        /// <summary>
        /// Get list of sql paths
        /// </summary>
        /// <returns></returns>
        public List<string> GetListLinqPaths()
        {
            return _lLinqPaths.ToList();
        }
        /// <summary>
        ///  Set hoTools SQL path from Settings to search for SQL files.
        /// </summary>
        /// <param name="paths"></param>
        public void SetLinqPadQueryPaths(string paths)
        {
            _linqPaths = paths;
            _lLinqPaths = paths.Split(';');
        }

        /// <summary>
        /// Read the SQL file. If it is an absolute path it uses this. If not it uses the SQL Path to find the complete sql file name.
        /// <para />
        /// In case of IO errors or file not found it return "". If a not existing absolute patch is used an error message is output
        /// (if withErrMessage = true, default)
        /// </summary>
        /// <param name="sqlFileName"></param>
        /// <param name="withErrMessage"></param>
        /// <returns></returns>
        public string ReadSqlFile(string sqlFileName, bool withErrMessage = true)
        {
            string absFileName = GetSqlFileName(sqlFileName);
            // normalize newline, insert a blank
            if (absFileName != "" || File.Exists(absFileName))
            {
                string  originalString = Util.ReadAllText(absFileName);
                // normalize according to linefeed
                return Regex.Replace(originalString, @"\r\n |\r\n|\n\r|\n|\r", "\r\n ");
            }
            if ( absFileName == ""  ) return "";
            if (withErrMessage)
            {
               MessageBox.Show($@"Error reading sql file '{sqlFileName}'", @"Error Reading *.sql file");
            }
            return "";

        }

        /// <summary>
        /// Get the absolute file name. It searches according to the in settings specified SQL path. If the file don't exists it return "".
        /// </summary>
        /// <param name="sqlFileName"></param>
        /// <returns></returns>
        public string GetSqlFileName(string sqlFileName)
        {
            return GetFileNameFromPath(_lSqlPaths, sqlFileName, ".sql");

        }

        /// <summary>
        /// Get the absolute file name. It searches according to the in settings specified LinqPadQuery path. If the file don't exists it return "".
        /// </summary>
        /// <param name="linqPadQueryFileName"></param>
        /// <returns></returns>
        public string GetLinqPadQueryFileName(string linqPadQueryFileName)
        {
            if (!IsLinqPadSupported) return "";
            return GetFileNameFromPath(_lLinqPaths, linqPadQueryFileName, ".linq");

        }

        /// <summary>
        /// Get the absolute file name. It searches according to the in settings specified path. If the file don't exists it return "".
        /// - If the file name doesn't contain the fileExtension (default=".sql") is added
        /// - If the path contains an absolute file path the extension has to match to wanted
        /// </summary>
        /// <param name="lPaths"></param>
        /// <param name="fileName"></param>
        /// <param name="fileExtension"></param>
        /// <returns>"" if noting found or file extension doesn't match</returns>
        private string GetFileNameFromPath(string[] lPaths, string fileName, string fileExtension= ".sql")
        {
            if (!Path.HasExtension(fileName)) fileName = fileName.Trim() + fileExtension;
            // Absolute path
            if (Path.IsPathRooted(fileName))
            {
                if (Path.GetExtension(fileName) != fileExtension) return "";
                if (File.Exists(fileName)) return fileName;
                else return "";

            }
            else
            {

                // over all files
                foreach (string path in lPaths)
                {
                    string f = Path.Combine(path, fileName);
                    if (File.Exists(f))
                    {
                        return f;
                    }

                }
            }
            // nothing found
            return "";
        }

        /// <summary>
        /// Get complete sql filepath from file name
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public string GetSqlFileLong(string fileName )
        {
            return FileNameLong(GetSqlListFileCompleteName(), fileName);
        }

        private string FileNameLong(List<string> liFileCompleteName, string fileName)
        {
            // compare complete file name with extension
            foreach (string fileNameLong in liFileCompleteName)
            {
                if (Path.GetFileName(fileNameLong) == fileName) return fileNameLong;
            }

            // compare file name without extension
            fileName = Path.GetFileNameWithoutExtension(fileName);
            foreach (string fileNameLong in liFileCompleteName)
            {
                if (Path.GetFileNameWithoutExtension(fileNameLong) == fileName) return fileNameLong;
            }
            return "";
        }

        /// <summary>
        /// Get list of *.sql files of SQL path
        /// </summary>
        /// <returns></returns>
        public List<string> GetSqlListFileCompleteName()
        {
            return FileBasedQueryFiles(_lSqlPaths);

        }
        /// <summary>
        /// Get list of *.sql files of SQL path
        /// </summary>
        /// <returns></returns>
        public List<string> GetLinqPadQueryListFileCompleteName()
        {
            if (!IsLinqPadSupported) return new List<string>();
            return FileBasedQueryFiles(_lLinqPaths, "*.linq");

        }

        /// <summary>
        /// Get list of file based query files
        /// </summary>
        /// <param name="lPaths"></param>
        /// <param name="fileExtension"></param>
        /// <returns></returns>
        private List<string> FileBasedQueryFiles(string[] lPaths, string fileExtension= "*.sql")
        {
            List<string> files = new List<string>();
            // over all files
            foreach (string path in lPaths)
            {
                if (Directory.Exists(path))
                    files.AddRange(Directory.GetFiles(path, fileExtension));
            }
            return files;
        }

        public AutoCompleteStringCollection GetListFileName()
        {
            AutoCompleteStringCollection files = new AutoCompleteStringCollection();
            foreach (string file in GetSqlListFileCompleteName())
            {
                files.Add(Path.GetFileName(file));
            }
            return files;
        }
        #endregion

    }
}


text:
package com.google.android.accessibility.braille.interfaces;

/** Allows TalkBack to signal to BrailleIme. */
public interface BrailleImeForTalkBack {
  /** Callbacks when TalkBack state changes from active to suspended or to inactive. */
  void onTalkBackSuspended();

  /** Callbacks when TalkBack state changes from inactive or suspended to active. */
  void onTalkBackResumed();

  /** Returns the callback of BrailleIme to BrailleDisplay. */
  BrailleImeForBrailleDisplay getBrailleImeForBrailleDisplay();
}


text:
require_relative '../../../puppet_x/bsd/hostname_if/vlan'

module Puppet::Parser::Functions
  newfunction(:get_hostname_if_vlan,
              type: :rvalue) do |args|

    config      = args.shift

    c           = {}
    c[:id]      = config['id'] if config['id']
    c[:address] = config['address'] if config['address']
    c[:device]  = config['device'] if config['device']

    return HostnameIf::Vlan.new(c).content
  end
end


text:
<?php

namespace Fobia\Collections\Test;

use Fobia\Collections\ItemList;

/**
 * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-09-08 at 02:10:21.
 */
class ItemListTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var ItemList
     */
    protected $object;
   protected $handler_error_level;

    const DEFAULT_COUNT = 10;

    /**
     * Создает список элементов
     * Каждый элемент имеет
     *  id   - порядковый номер
     *  name - имя (на основе id)
     *  type - типо (у всех new)
     *  group - группа элемента (Общее кол. создаваемых элементов деляться на 5 групп)
     *  param1 - каждая группа имеет параметры paramX, кол. которых возрвстают с возрвстанием группы
     *  param2, param3...
     *
     * @param int $count
     * @param bool $create_obj
     * @return array
     */
    public function createArrayItems($count = null, $create_obj = false)
    {
        $groups = 5;
        if ($count === null) {
            $count = self::DEFAULT_COUNT;
        }
        $data = array();
        $group_count = ceil($count / $groups);

        for ($i = 0; $i < $count; $i++ ) {
            $_current_group =  ceil(($i + 1) / $group_count);
            $item = array(
                'id'   => $i,
                'name' => "name_" . $i,
                'type' => 'new',
                'group' => $_current_group,
            );
            for($g = 1; $g < $_current_group; $g++) {
                $item["param$g"] = null;
            }

            if ($create_obj) {
                $item = (object) $item;
            }
            $data[] = $item;
        }

        return $data;
    }

    protected function setErrorHandler($errno_level = 256)
    {
        $this->handler_error_level = error_reporting(0);
        set_error_handler(function($errno) use ($errno_level) {
            if ( ! ($errno & $errno_level)) {
                return;
            }
            throw new \Exception("Error", $errno);
        });
    }

    protected function restoreErrorHandler()
    {
        if ($this->handler_error_level !== null) {
            restore_error_handler();
            error_reporting($this->handler_error_level);
            $this->handler_error_level = null;
        }
    }

    protected function setUp()
    {
        $this->object = new ItemList($this->createArrayItems());
    }

    protected function tearDown()
    {
        $this->restoreErrorHandler();
    }
    ///////////////////////////////////////////////////////////////////////////

    /**
     * @covers Fobia\Collections\ItemList::getIterator
     */
    public function testGetIterator()
    {
        $this->assertInstanceOf('Traversable', $this->object);
        $this->assertInstanceOf('Traversable', $this->object->getIterator());
    }

    /**
     * @covers Fobia\Collections\ItemList::count
     */
    public function testCount()
    {
        $this->assertCount(self::DEFAULT_COUNT, $this->object);
    }

    /**
     * @covers Fobia\Collections\ItemList::getCount
     */
    public function testGetCount()
    {
        $this->assertEquals(10, $this->object->getCount());
    }

    /**
     * @covers Fobia\Collections\ItemList::itemAt
     */
    public function testItemAt()
    {
        $item = $this->object->itemAt(1);

        $this->assertArrayHasKey('id', $item);
        $this->assertArrayHasKey('name', $item);
        $this->assertEquals(1, $item['id']);
        $this->assertEquals('name_1', $item['name']);
    }

    /**
     * @covers Fobia\Collections\ItemList::add
     * @todo   Implement testAdd().
     */
    public function testAdd()
    {
        $index = $this->object->add(array(
            'id' => 10,
            'name' => 'name_10',
            'type' => 'add'
        ));

        $this->assertEquals(self::DEFAULT_COUNT, $index);
    }

    /**
     * @covers Fobia\Collections\ItemList::insertAt
     */
    public function testInsertAt()
    {
        $item = array(
            'id' => 10,
            'name' => 'name_10',
            'type' => 'add'
        );
        $this->object->insertAt(1, $item);

        $this->assertCount(self::DEFAULT_COUNT + 1, $this->object);
        $this->assertSame($item, $this->object->itemAt(1));
    }

    /**
     * @covers Fobia\Collections\ItemList::eq
     */
    public function testEq()
    {
        $this->assertEquals(
                $this->object->eq(0),
                $this->object->eq( -5 )
        );
        $this->assertEquals(
                $this->object->eq(0),
                $this->object->eq( 'none' )
        );
        $this->assertEquals(
                $this->object->eq($this->object->count() - 1),
                $this->object->eq($this->object->count() + 5 )
        );
        $this->assertEquals(
                $this->object->eq(5),
                $this->object->itemAt(5)
        );
    }

    /**
     * @covers Fobia\Collections\ItemList::remove
     * @todo   Implement testRemove().
     */
    public function testRemove()
    {
        $item = array(
            'id' => 10,
            'name' => 'name_10',
            'type' => 'add'
        );
        $this->object->insertAt(1, $item);
        $index = $this->object->remove($item);
        $this->assertEquals(1, $index);
    }

    /**
     * @covers Fobia\Collections\ItemList::removeAt
     * @todo   Implement testRemoveAt().
     */
    public function testRemoveAt()
    {
        $item0 = $this->object->itemAt(0);
        $this->assertEquals('name_0', $item0['name']);

        $item = $this->object->removeAt(0);
        $this->assertCount(self::DEFAULT_COUNT - 1, $this->object);
        $this->assertSame($item0, $item);

        $item = $this->object->itemAt(0);
        $this->assertEquals('name_1', $item['name']);
    }

    /**
     * @covers Fobia\Collections\ItemList::clear
     */
    public function testClear()
    {
        $this->object->clear();
        $this->assertCount(0, $this->object);
    }

    /**
     * @covers Fobia\Collections\ItemList::contains
     * @todo   Implement testContains().
     */
    public function testContains()
    {
        $item = array(
            'id' => 10,
            'name' => 'name_10',
            'type' => 'add'
        );
        $this->assertFalse($this->object->contains($item));
        $this->object->add($item);
        $this->assertTrue($this->object->contains($item));
    }

    /**
     * @covers Fobia\Collections\ItemList::indexOf
     * @todo   Implement testIndexOf().
     */
    public function testIndexOf()
    {
        $item_new = array(
            'id' => 11,
            'name' => 'name_11',
            'type' => 'add'
        );
        $index = $this->object->add($item_new);
        $this->assertSame($index, $this->object->indexOf($item_new));
    }

    /**
     * @covers Fobia\Collections\ItemList::indexOf
     * @todo   Implement testIndexOf().
     */
    public function testIndexOfOrigin()
    {
        $item = $this->object->itemAt(0);
        $index = $this->object->indexOf($item);
        $this->assertEquals(0, $index);
    }

    /**
     * @covers Fobia\Collections\ItemList::indexOf
     * @todo   Implement testIndexOf().
     */
    public function testIndexOfOther()
    {
        $item = $this->object->itemAt(0);
        $item_clone = array();
        foreach ($item as $key => $value) {
            $item_clone[$key] = $value;
        }

        $this->assertEquals(0, $this->object->indexOf($item_clone));
    }

    /**
     * @covers Fobia\Collections\ItemList::toArray
     * @todo   Implement testToArray().
     */
    public function testToArray()
    {
        $arr = $this->object->toArray();
        $this->assertInternalType('array', $arr);

        foreach ($this->object as $k => $v) {
            $this->assertSame($arr[$k], $v);
        }
    }

    /**
     * @covers Fobia\Collections\ItemList::copyFrom
     * @todo   Implement testCopyFrom().
     */
    public function testCopyFrom()
    {
        // Remove the following lines when you implement this test.
        $this->assertCount(self::DEFAULT_COUNT, $this->object);

        $data = $this->createArrayItems(5);
        foreach ($data as $k => $v) {
            $data[$k]['type'] = 'test';
        }
        $this->object->copyFrom($data);
        $this->assertCount(5, $this->object);
    }

    /**
     * @covers Fobia\Collections\ItemList::mergeWith
     * @todo   Implement testMergeWith().
     */
    public function testMergeWith()
    {
        $arr = $this->createArrayItems(5);
        $arr[] = array(
            'id' => 22,
            'name' => 'name_22',
            'type' => 'merge'
        );
        $this->object->mergeWith($arr);

        $this->assertCount(self::DEFAULT_COUNT + 5 + 1, $this->object);
        //$this->assertSame($arr, $this->object->itemAt($this->object->getCount() - 1));
    }

    /**
     * @covers Fobia\Collections\ItemList::each
     */
    public function testEachFull()
    {
        $this->object->each(function(&$item, $index) {
            $item['type'] = 'each_' . $index;
        });

        $item = $this->object->itemAt(0);
        $this->assertEquals('each_0', $item['type']);

        $lastIndex = $this->object->count() - 1;
        $item = $this->object->itemAt($lastIndex);
        $this->assertEquals('each_' . $lastIndex, $item['type']);
    }

    /**
     * @covers Fobia\Collections\ItemList::each
     */
    public function testEachReturnFallse()
    {
        $this->object->each(function(&$item, $index) {
            $item['type'] = 'each_' . $index;
            if ($index >= 5) {
                return false;
            }
        });

        $item = $this->object->itemAt(5);
        $this->assertEquals('each_5', $item['type']);

        $item = $this->object->itemAt(6);
        $this->assertEquals('new', $item['type']);
    }

    /**
     * @covers Fobia\Collections\ItemList::each
     */
    public function testEachWithArg()
    {
        $this->object->each(function(&$item, $index, $arg) {
            $item['type'] = $arg . '_' . $index;
        }, 'arg');

        $item = $this->object->itemAt(0);
        $this->assertEquals('arg_0', $item['type']);
    }

    /**
     * @covers Fobia\Collections\ItemList::set
     */
    public function testSet()
    {
        $this->object->set('type', 'set')
                ->set('name', 'set');

        $item = $this->object->itemAt(0);
        $this->assertEquals('set', $item['type']);
        $this->assertEquals('set', $item['name']);
    }

    /**
     * @covers Fobia\Collections\ItemList::get
     */
    public function testGetKey()
    {
        for ($i = 0; $i < self::DEFAULT_COUNT; $i++ ) {
            $arr[] = $i;
        }
        $this->assertSame($arr, $this->object->get('id'));
    }

    /**
     * @covers Fobia\Collections\ItemList::get
     */
    public function testGetKeys()
    {
        for ($i = 0; $i < self::DEFAULT_COUNT; $i++ ) {
            $arr[] = array(
                'id' => $i,
                'name' => 'name_' . $i
            );
        }
        $this->assertSame($arr, $this->object->get(array('id', 'name')));
    }

    /**
     * @covers Fobia\Collections\ItemList::get
     */
    public function testGetNameKey()
    {
        for ($i = 0; $i < self::DEFAULT_COUNT; $i++ ) {
            $k = 'name_' . $i;
            $arr[$k] = $k;
        }
        $this->assertSame($arr, $this->object->get('name', 'name'));
    } /* */

    /**
     * @covers Fobia\Collections\ItemList::get
     */
    public function testGetNameKeys()
    {
        for ($i = 0; $i < self::DEFAULT_COUNT; $i++ ) {
            $k = 'name_' . $i;
            $arr[$k] = array(
                'id' => $i,
                'name' => 'name_' . $i
            );
        }
        $this->assertSame($arr, $this->object->get('name', array('id', 'name')));
    } /*  */

    /**
     * @covers Fobia\Collections\ItemList::find
     */
    public function testFind()
    {
        // isset property
        $this->assertCount(4, $this->object->find('param3'));
        $this->assertCount(2, $this->object->find('param4'));

        // eq
        $this->assertCount(2, $this->object->find('group', 4));

        // callback function
        $cb = function($item) {
            return ($item['group'] == 5);
        };
        $this->assertCount(2, $this->object->find($cb));
    }

    public function testFindEx()
    {
        // callback function
        $cb = function($item) {
            return ($item['id'] % 2);
        };
        $collection = $this->object
                ->find($cb)
                ->find('param3')
                ->find('group', 5);
        $this->assertCount(1, $collection);
    }
}


text:
package org.mindinformatics.gwt.framework.src;

public interface ICommandCompleted {

	public void notifyStageCompletion();
}


text:
Splockets
=========

Read a subset of Sprockets directives to concatenate your JavaScript to stdout.

This was written so that I could concatenate JavaScript files in a Rails app and pass them on to Jasmine for testing, and do so faster than Sprockets could in our existing setup.  It was also an excuse to write something in Node and my first real attempt, so caveat emptor.  But if it's useful to anyone else, great!

Related projects
=========
The name is a complete rip off of Snockets (https://github.com/TrevorBurnham/snockets).  If you're looking at this project you should probably check out that page since it does some similar and probably much better.


text:
<?php

namespace Cron\Job;

use Cron\Report\JobReport;
use Symfony\Component\Process\Process;

/**
 * AbstractProcessJob Base for all process jobs.
 *
 * @author Dries De Peuter <dries@nousefreak.be>
 */
abstract class AbstractProcessJob extends AbstractJob
{
    /**
     * The symfony process instance.
     *
     * @var Process
     */
    protected $process;

    /**
     * @var JobReport
     */
    protected $report;

    /**
     * The process id.
     *
     * @var int
     */
    protected $pid;

    /**
     * @return Process
     */
    public function getProcess()
    {
        return $this->process;
    }

    /**
     * @param int $pid
     */
    protected function setPid($pid)
    {
        $this->pid = $pid;
    }

    /**
     * Start the process.
     *
     * @param JobReport $report
     */
    public function run(JobReport $report)
    {
        $this->report = $report;
        $report->setStartTime(microtime(true));
        $this->getProcess()->start(function ($type, $buffer) use ($report) {
            if (Process::ERR === $type) {
                $report->addError($buffer);
            } else {
                $report->addOutput($buffer);
            }
        });
    }

    /**
     * Validate the job.
     *
     * Will check if we have a process and make sure it isn't already running.
     *
     * @param \DateTime $now
     *
     * @return bool
     */
    public function valid(\DateTime $now)
    {
        return parent::valid($now) && $this->getProcess() && !$this->isRunning();
    }

    /**
     * Validate if the process is running.
     *
     * @return bool
     */
    public function isRunning()
    {
        $running = $this->isProcessRunning();

        if (!$running && $this->getProcess()->isStarted()) {
            $this->registerEnd();
            $this->registerSuccessful();
        }

        return $running;
    }

    /**
     * @return bool
     */
    protected function isProcessRunning()
    {
        if (is_null($this->pid)) {
            return $this->getProcess()->isRunning();
        }

        return (bool) posix_getpgid($this->pid);
    }

    /**
     * Register the end of a job to the report.
     */
    protected function registerEnd()
    {
        if (is_null($this->report->getEndTime())) {
            $this->report->setEndTime(microtime(true));
        }
    }

    /**
     * Register the end state.
     */
    protected function registerSuccessful()
    {
        $this->report->setSuccessful($this->getProcess()->isSuccessful());
    }
}


text:
package ru.home.fedr.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.home.fedr.db.models.User;

import java.util.ArrayList;
import java.util.Collection;

@Service("securityService")
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails getCurrectUser() {
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User userCredentials = userService.loadUserByUsername(username);
        if (userCredentials != null) {
            return new UserDetails() {
                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    GrantedAuthority grantedAuthority = new GrantedAuthority() {
                        @Override
                        public String getAuthority() {
                            return userCredentials.getRole().getRoleName();
                        }
                    };
                    ArrayList<GrantedAuthority> authorities = new ArrayList<>();
                    authorities.add(grantedAuthority);
                    return authorities;
                }

                @Override
                public String getPassword() {
                    return userCredentials.getPassword();
                }

                @Override
                public String getUsername() {
                    return userCredentials.getEmail();
                }

                @Override
                public boolean isAccountNonExpired() {
                    return true;
                }

                @Override
                public boolean isAccountNonLocked() {
                    return true;
                }

                @Override
                public boolean isCredentialsNonExpired() {
                    return true;
                }

                @Override
                public boolean isEnabled() {
                    return true;
                }
            };
        }
        throw new UsernameNotFoundException(String.format("User with email: %s not found!", username));
    }
}


text:
layout: null
published: true
title: Resource
abstract: "The resource module contains functions that allow you to iterate over the attributes of your application's resources."
author: Bediako George, Serena Lei
categories: api
---

Airlift is a restful framework.  Resources are the center of Airlift application development.  When designing an application, developers are encouraged to create as many resources as they like.  The resource.js module contains functions that allow developers to traverse the application resources' attributes.  In Airlift a resource is represented as a simple JavaScript object ({}).

Whenever a iterative function is executed in resource, the iterator function that you provide is executed within a context that governs the traversal of that resource.  This context is set as the 'this' for the iterator function.  It makes available following:

* resourceName - the name of the resource being traversed.
* resourceMetadata - metadata describing the resource being traversed.  It contains a list of attributes this resource holds.
* attributesMetadata - metadata describing each individual attribute this resource holds.
* foreignKeys - a list of names of all the foreign keys in this resource.
* attributes - a list of names of all the attributes in this resource.
* web - a web object that gives access to the web context.  The web context contains information about the current request.
* report - a function used to report errors.
* allErrors - a function that returns all errors reported so far.
* getErrors - a function that returns all errors reported for a given attribute of this resource.

All iterative functions in resource.js allow for the replacement of any of the attributes of the context object by optionally providing an object at invocation time.

The functions available in this module are described below. They can be accessed by providing the following code:

     var resource = require('airlift/resource');

### each(String resourceName, Object resource, Function function, Function callback, Object context)
#### Return Type: n/A

 Added in 2.0
Iterates over a resource, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed, along with the attributes provided in the default context. Each invocation of iterator is called with four arguments: value, attributeName, resource, and metadata. An optional callback can be supplied.  If the callback is supplied, it will be called at the end of the iteration cycle with two arguments: resourceName, resource.

     var attributes = [];

     resource.each('person', bediako,
           function iterator(_value, _attributeName, _resource, _metadata)
               {
                    attributes.push(_attributeName);
               },
           function callback(_resourceName, resource)
               {
                    attributes.push('finished');
               }, context);

     => ["fullName", "shortName", "status", "birthDate", "id", "finished"]

### map(String resourceName, Object resource, Function function, Function callback, Object context)
#### Return type: Object

 Added in 2.0
Iterates over a resource, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed, along with the attributes provided in the default context. Each invocation of iterator is called with four arguments: value, attributeName, resource, and metadata. The result of each iterator invocation is saved to a new resource object.

     var attributes = [];

     //create a person resource using map ...
     var person = resource.map('person', bediako,
         function(_value, _attributeName, _resource, _metadata)
         {
             attributes.push(_attributeName);
	     return _value;
         }, undefined, context);

     => ["fullName","shortName","status","birthDate","age","friendList","familySet",
         "auditPostDate","auditPutDate","auditUserId","id"]

### transform(Object dictionary, String resourceName, Object resource, Function function, Function callback, Object context)
#### Return type: Object

 Added in 2.0
Transforms the attribute names of a resource into a new set of names as defined by the 'dictionary'.

     var attributes = [];
     var bediako = {fullName: 'Bediako George', shortName: 'Bediako',
          status: 'middle aged', id: 1};
     var dictionary = {fullName: 'name'};

     //create a person resource using transform ...
     resource.transform(dictionary, 'person', bediako,
         function(_value, _attributeName, _resource, _metadata)
         {
               attributes.push(_attributeName);
               return _value;
         }, undefined, context);

     => {name: 'Bediako George', shortName: 'Bediako', status: 'middle aged', id: 1}

### reduce(String base, String resourceName, Object resource, Function function, Function callback, Object context)
#### Return type: String

 Added in 2.0
Iterates over a resource, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed, along with the attributes provided in the default context. Each invocation of iterator is called with five arguments: base, value, attributeName, resource, and metadata. The result of each iterator invocation replaces the base value. Reduce returns the value of base at the end.

     var attributes = [];

     var reducedResult = resource.reduce('person:', 'person', bediako,
          function(_base, _value, _attributeName, _resource, _metadata)
          {
               attributes.push(_attributeName);
               var formattedValue = Packages.airlift.util.FormatUtil.format(_value||"");
               return _base + ':' + _attributeName + '=' + formattedValue;
          }, undefined, context);

     => "person::fullName=Bediako George:shortName=Bediako:status=middle aged
         :birthDate=01-01-1970:age=43.0:friendList=[\"friend1\",\"friend2\",\"friend3\"]
         :familySet=[\"family1\"]:auditPostDate=:auditPutDate=:auditUserId=
         :id=6524d6f79d19"

### sequence(Function f1, Function f2, ... , Function fN)
#### Return type: Function

 Added in 2.0
Returns a function that is the composition of the passed function arguments. The functions are executed in the order they are passed into sequence. Sequence's returned function can be used in a iterative manner on a resource or executed as a standalone. Sequence returns the value of the last function's execution.

     var results = [];
     var sequence = resource.sequence(
          function() { results.push(1); },
          function() { results.push(2); },
          function() { results.push(3); },
          function() { results.push(4); }
     );
     sequence();

     => [1,2,3,4]

### compose(Function f1, Function f2, ..., Function fN)
####Return type: Function

 Added in 2.0
Returns a function that is the composition of the passed function arguments. The functions are executed in the order they are passed in to Compose. Compose's returned function can be used in a iterative manner on a resource or executed as a standalone. On execution, the function returned by Compose passes its arguments to the first function executed. Each function after that will get the return value of the previous function as a replacement for the first argument of the original arguments. Compose returns the value of the last function's execution.

    var results = [];

    var compose = resource.compose(
        function() { results.push(1); },
        function() { results.push(2); },
        function() { results.push(3); },
        function() { results.push(4); }
    );

    compose();

    => [1,2,3,4]

### toString(String resourceName, Object resource, Object context)
#### Return type: String

 Added in 2.0
Returns a string representation of a resource.

     var bediako = {fullName: 'Bediako George', shortName: 'Bediako'};
     resource.toString('person', bediako);

     => [** person
     	fullName: Bediako George
	shortName: Bediako
        ]

### watch(String attributeName1, ..., String attributeNameN, Function watchFunction)
#### Return type: Function

 Added in 2.0
Returns a function that will only be executed once and only once when the all the attributes in the argument list of nameList are visited by the iterative function.  If an attribute list is not passed as arguments or as an array, watch will execute once and only once all the attributes of the iterative context are visited.

     var executionTest = [], attributes = {};
     var watchFunction = function(_value, _attributeName, _resource, _metadata)
          {
               executionTest.push(1);
               attributes[_attributeName] = (attributes[_attributeName]
                    && attributes[_attributeName] + 1)||1;
     };
     var watch = resource.watch('birthDate', 'age', watchFunction);
     resource.each('person', bediako, watch, undefined, context);
     var result = {age: 1};

     => attributes: {age: 1}

### json(Object resource, Object replacer)
#### Return type: Function

 Added in 2.0
Converts an object into a string by calling JSON.stringify().

     resource.json({});
     => '{}'

     resource.json(['bediako']);
     => '["bediako"]'

     resource.json({number: new Packages.java.lang.Integer(1)});
     => '{"number":1}'

     resource.json({time: new Date(5)});
     => '{"time":"1970-01-01T00:00:00.005Z"}'

### audit(Object config)
#### Return type: n/A

 Added in 2.0
Records audit information associated with an action on a particular resource.  The 'config' object is a set of key/value pairs that configure the audit request.  It includes an entity (com.google.appengine.api.datastore.Entity), an id (java.lang.String|String), an action (java.lang.String|String), and a resourceName (java.lang.String|String).

     var in = require('airlift/incoming')
     var entity = in.createEntity('person', 'Bediako');
     entity.setProperty('fullName', 'Bediako George');
     entity.setProperty('shortName', 'Bediako');
     resource.audit({entity: entity, action: 'INSERT'});
     => undefined //records information to datastore

### copy(Object target, Object value, String attributeName)
#### Return type: n/A

 Added in 2.0
Copies each 'attributeName' of 'value' into 'target'.

     var target = {};

     resource.each('person', bediako, resource.copy.partial(target), undefined, context);

     => {"fullName":"Bediako George","shortName":"Bediako","status":"middle aged",
         "birthDate":"1970-01-01T05:00:00.000Z","age":43,
         "friendList":["friend1","friend2","friend3"],"familySet":["family1"],
         "id":"6524d6f79d19"}

### clone(Object value)
#### Return type: Object

 Added in 2.0
Creates a new instance of 'value', copies all the attributes to the new instance and returns it.

     var target = resource.map('person', bediako, resource.clone, undefined, context);

     => {"fullName":"Bediako George","shortName":"Bediako","status":"middle aged",
         "birthDate":"1970-01-01T05:00:00.000Z","age":43,
         "friendList":["friend1","friend2","friend3"],"familySet":["family1"],
         "id":"6524d6f79d19"}

### stream(Function iterator, Function serialize, Function write, Array separators)
#### Return type: n/A

 Added in 2.0
Streams content from the iterator using the provided serializer and writer until all the items in the iterator are processed.

     var da = require('airlift/da/collect').create(_web);
     var persons = da.collect('person');
     var serialize = function(_person) {
          return JSON.stringify(_person);
     };
     var writer =
     {
          this.write = function(_content) {
               util.info(_content);
          };
          this.end = function() {
          };
     };
     resource.stream(persons, serialize, writer, '[',',',']');
     => undefined //writes data to stream


text:
<?php

namespace Placephant;

use Symfony\Component\Finder\Finder;

/**
 * Resource Helper Class
 */
class ResourceHelper
{

    protected $resources_dir;
    protected $resources;

    public function __construct($resources_dir = null)
    {
        $this->resources_dir = $resources_dir ?: __DIR__ . "/Resources/images";
        $this->resources = array();
    }

    public function loadResources()
    {
        $finder = new Finder();
        $finder->files()->in($this->resources_dir)->name('*.jpg');

        foreach ($finder as $file) {
            $this->resources[] = $file->getFileName();
        }

        return $this->resources;
    }

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

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

    public function getRandom()
    {
        if (!count($this->resources)) {
            $this->loadResources();
        }

        return $this->resources_dir . "/" . $this->resources[array_rand($this->resources)];
    }
}


text:
<?php

namespace ZendTest\Http\Header;

use PHPUnit\Framework\TestCase;
use Zend\Http\Header\Exception\InvalidArgumentException;
use Zend\Http\Header\HeaderInterface;
use Zend\Http\Header\Via;

class ViaTest extends TestCase
{
    public function testViaFromStringCreatesValidViaHeader()
    {
        $viaHeader = Via::fromString('Via: xxx');
        $this->assertInstanceOf(HeaderInterface::class, $viaHeader);
        $this->assertInstanceOf(Via::class, $viaHeader);
    }

    public function testViaGetFieldNameReturnsHeaderName()
    {
        $viaHeader = new Via();
        $this->assertEquals('Via', $viaHeader->getFieldName());
    }

    public function testViaGetFieldValueReturnsProperValue()
    {
        $this->markTestIncomplete('Via needs to be completed');

        $viaHeader = new Via();
        $this->assertEquals('xxx', $viaHeader->getFieldValue());
    }

    public function testViaToStringReturnsHeaderFormattedString()
    {
        $this->markTestIncomplete('Via needs to be completed');

        $viaHeader = new Via();

        // @todo set some values, then test output
        $this->assertEmpty('Via: xxx', $viaHeader->toString());
    }

    /** Implementation specific tests here */

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaFromString()
    {
        $this->expectException(InvalidArgumentException::class);
        Via::fromString("Via: xxx\r\n\r\nevilContent");
    }

    /**
     * @see http://en.wikipedia.org/wiki/HTTP_response_splitting
     * @group ZF2015-04
     */
    public function testPreventsCRLFAttackViaConstructor()
    {
        $this->expectException(InvalidArgumentException::class);
        new Via("xxx\r\n\r\nevilContent");
    }
}


text:
<?php

namespace Indigo\Bundle\CookieConsentBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('indigo_cookie_consent');

        $rootNode
            ->children()
                ->arrayNode('options')
                    ->addDefaultsIfNotSet()
                    ->info('See valid options at https://silktide.com/tools/cookie-consent/docs/installation')
                    ->children()
                        ->scalarNode('link')->end()
                        ->scalarNode('container')->end()
                        ->scalarNode('theme')->end()
                        ->scalarNode('path')->end()
                        ->scalarNode('domain')->end()
                        ->integerNode('expiryDays')->end()
                        ->scalarNode('target')->end()
                    ->end()
                ->end()
                ->scalarNode('script')
                    ->defaultValue('//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.10/cookieconsent.min.js')
                    ->info('Set this to false to disable script (eg. when you compiled it into yours)')
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


text:
using System.Data;
using NSubstitute;
using NUnit.Framework;

namespace FluentSQLite.Tests
{
	[TestFixture]
	public class CommonTests
	{
		[Test]
		public void TestGeneralExecution()
		{
			// General run test
			Database.CreateDatabase()
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String)
						.AddField("SomeOtherData", FieldType.Integer)
				.CommitStructure()
				.SelectTable("Table1")
						.InsertRow("String 1", 42)
						.InsertRow("String 2", 1400)
				.CommitData();
		}

		[Test]
		public void CreateTableSqlExpression()
		{
			var command = Substitute.For<IDbCommand>();
			var connection = Substitute.For<IDbConnection>();
			connection.CreateCommand().Returns(command);

			Database.CreateDatabase(connection)
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String)
						.AddField("SomeOtherData", FieldType.Integer)
				.CommitStructure();

			command.Received().ExecuteNonQuery();
			Assert.AreEqual("CREATE TABLE \"Table1\" (\"PrimaryKey\" INTEGER PRIMARY KEY AUTOINCREMENT, \"SomeData\" CHAR, \"SomeOtherData\" INTEGER)", command.CommandText);
		}

		[Test]
		public void InsertDataSqlExpression()
		{
			var command = Substitute.For<IDbCommand>();
			var connection = Substitute.For<IDbConnection>();
			connection.CreateCommand().Returns(command);

			Database.CreateDatabase(connection)
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String)
						.AddField("SomeOtherData", FieldType.Integer)
				.CommitStructure()
				.SelectTable("Table1")
						.InsertRow("String 1", 42)
				.CommitData();

			command.Received().ExecuteNonQuery();
			Assert.AreEqual("INSERT INTO \"Table1\" (\"SomeData\", \"SomeOtherData\") VALUES (@SomeData, @SomeOtherData)", command.CommandText);
		}

		[Test]
		[ExpectedException(typeof(FluentSQLiteException))]
		public void AddingSameTableTwiceShouldFail()
		{
			Database.CreateDatabase()
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String)
						.AddField("SomeOtherData", FieldType.Integer)
				.CommitStructure()
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String)
						.AddField("SomeOtherData", FieldType.Integer)
				.CommitStructure();
		}

		[Test]
		public void ActualDataIsInserted()
		{
			var connection = Database.CreateDatabase()
									.AddTable("Table1")
											.AddField("PrimaryKey", FieldType.AutoInc, true, true)
											.AddField("SomeData", FieldType.String)
											.AddField("SomeOtherData", FieldType.Integer)
									.CommitStructure()
									.SelectTable("Table1")
											.InsertRow("String 1", 42)
											.InsertRow("String 2", 720)
									.CommitData()
									.Connection;

			using (var command = connection.CreateCommand())
			{
				command.CommandType = CommandType.Text;
				command.CommandText = "SELECT * FROM Table1 ORDER BY PrimaryKey";

				using (var reader = command.ExecuteReader())
				{
					reader.Read();

					Assert.AreEqual(1, reader[0]);
					Assert.AreEqual("String 1", reader[1]);
					Assert.AreEqual(42, reader[2]);

					reader.Read();

					Assert.AreEqual(2, reader[0]);
					Assert.AreEqual("String 2", reader[1]);
					Assert.AreEqual(720, reader[2]);
				}
			}
		}

		[Test]
		[ExpectedException(typeof(FluentSQLiteException))]
		public void AutoIncShouldBeTheOnlyPrimaryKey_AddedBeforeOtherFields()
		{
			// Test case #1
			// AutoInc is added before all other fields
			var table = Database.CreateDatabase()
				.AddTable("Table1")
						.AddField("PrimaryKey", FieldType.AutoInc, true, true)
						.AddField("SomeData", FieldType.String, false, true);
		}

		[Test]
		[ExpectedException(typeof(FluentSQLiteException))]
		public void AutoIncShouldBeTheOnlyPrimaryKey_AddedAfterOtherFirlds()
		{
			// Test case #2
			// AutoInc is added after other PK fields
			var table2 = Database.CreateDatabase()
				.AddTable("Table1")
						.AddField("SomeData", FieldType.String, false, true)
						.AddField("PrimaryKey", FieldType.AutoInc, true, true);
		}
	}
}


text:
NS_DXM_BEGIN
NS_UTIL_BEGIN

class DXM_UTIL_DECL CTime{
public:
	static dxm_uint64 NowTime( void );
	static dxm_uint64 ToTime( std::string date_time_string );
	static dxm_int64 DiffTime( dxm_uint64 time1, dxm_uint64 time2 );

	static std::string ToTimeSpanString( dxm_int64 time_span );
	static std::string ToDateTimeString( dxm_uint64 time );
	static std::string ToTimeString( dxm_uint64 time );
	static std::string ToDateString( dxm_uint64 time );
};

NS_UTIL_END
NS_DXM_END
#endif // __DXM_TIMER_H__


text:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Actions, ofActionSuccessful, Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { catchError, take } from 'rxjs/operators';
import { AutoUnsubscribePage } from '../../../../components/auto-unsubscribe/auto-unsubscribe.page';
import { NavigationService } from '../../../../services/navigation.service';
import { AbstractDevice } from '../../../../states/devices/abstract-device';
import { DevicesState } from '../../../../states/devices/devices.state';
import { ErrorResponse, ErrorResponseCode } from '../../../../states/measures/error-response';
import { StartManualMeasure, StartMeasureSeriesParams } from '../../../../states/measures/measures.action';
import { LogIn } from '../../../../states/user/user.action';

export enum RedirectAfterLogin {
  ManualMeasure = 'manualMeasure',
  MeasureSeries = 'measureSeries'
}

@Component({
  selector: 'app-log-in',
  templateUrl: './log-in.page.html',
  styleUrls: ['./log-in.page.scss']
})
export class LogInPage extends AutoUnsubscribePage {
  @Select(DevicesState.connectedDevice)
  connectedDevice$: Observable<AbstractDevice | undefined>;

  loginForm: FormGroup;
  connecting = false;
  redirectAfterLogin: RedirectAfterLogin;

  url = '/tabs/settings/log-in';

  constructor(
    protected activatedRoute: ActivatedRoute,
    protected router: Router,
    private navigationService: NavigationService,
    private store: Store,
    private formBuilder: FormBuilder,
    private toastController: ToastController,
    private actions$: Actions,
    private translateService: TranslateService
  ) {
    super(router);
    this.loginForm = this.formBuilder.group({
      login: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  pageEnter() {
    super.pageEnter();
    this.activatedRoute.queryParams
      .pipe(take(1))
      .subscribe(queryParams => (this.redirectAfterLogin = queryParams.redirectAfterLogin));
    this.subscriptions.push(
      this.actions$.pipe(ofActionSuccessful(LogIn)).subscribe(() => {
        if (!this.redirectAfterLogin) {
          this.goBack();
        }
      })
    );
  }

  onSubmit() {
    this.connecting = true;
    this.store
      .dispatch(new LogIn(this.loginForm.value.login, this.loginForm.value.password))
      .pipe(
        catchError((error: ErrorResponse) => {
          this.connecting = false;
          switch (error.code) {
            case ErrorResponseCode.WrongCredentials:
              this.toastController
                .create({
                  message: this.translateService.instant('LOG_IN.WRONG_CREDENTIALS'),
                  closeButtonText: this.translateService.instant('GENERAL.OK'),
                  duration: 5000,
                  showCloseButton: true
                })
                .then(toast => toast.present());
              break;
            default:
              this.toastController
                .create({
                  message: this.translateService.instant('GENERAL.CONNEXION_ERROR', { message: error.message }),
                  closeButtonText: this.translateService.instant('GENERAL.OK'),
                  duration: 5000,
                  showCloseButton: true
                })
                .then(toast => toast.present());
          }
          throw error;
        })
      )
      .subscribe(() => {
        switch (this.redirectAfterLogin) {
          case RedirectAfterLogin.ManualMeasure:
            this.store.dispatch(new StartManualMeasure()).subscribe();
            break;
          case RedirectAfterLogin.MeasureSeries:
            this.store.dispatch(new StartMeasureSeriesParams());
            break;
        }
      });
  }

  goBack() {
    this.navigationService.goBack();
  }
}


text:
STATIC_LIBRARY_FLAGS
--------------------

Archiver (or MSVC librarian) flags for a static library target.
Targets that are shared libraries, modules, or executables need to use
the :prop_tgt:`LINK_OPTIONS` or :prop_tgt:`LINK_FLAGS` target properties.

The ``STATIC_LIBRARY_FLAGS`` property, managed as a string, can be used to add
extra flags to the link step of a static library target.
:prop_tgt:`STATIC_LIBRARY_FLAGS_<CONFIG>` will add to the configuration
``<CONFIG>``, for example, ``DEBUG``, ``RELEASE``, ``MINSIZEREL``,
``RELWITHDEBINFO``, ...

.. note::

  This property has been superseded by :prop_tgt:`STATIC_LIBRARY_OPTIONS`
  property.


text:
layout: model
title: English RobertaForTokenClassification Cased model (from obi)
author: John Snow Labs
name: roberta_ner_deid_roberta_i2b2
date: 2022-08-10
tags: [bert, ner, open_source, en]
task: Named Entity Recognition
language: en
edition: Spark NLP 4.1.0
spark_version: 3.0
supported: true
annotator: RoBertaForTokenClassification
article_header:
  type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description

Pretrained RobertaForTokenClassification model, adapted from Hugging Face and curated to provide scalability and production-readiness using Spark NLP. `deid_roberta_i2b2` is a English model originally trained by `obi`.

## Predicted Entities

`DATE`, `L-AGE`, `U-PATIENT`, `L-STAFF`, `U-OTHERPHI`, `U-ID`, `EMAIL`, `U-LOC`, `L-HOSP`, `L-PATIENT`, `PATIENT`, `PHONE`, `U-PHONE`, `L-OTHERPHI`, `HOSP`, `L-PATORG`, `AGE`, `U-EMAIL`, `L-ID`, `U-HOSP`, `U-AGE`, `OTHERPHI`, `LOC`, `ID`, `U-DATE`, `L-DATE`, `U-PATORG`, `L-PHONE`, `STAFF`, `L-EMAIL`, `PATORG`, `U-STAFF`, `L-LOC`

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/roberta_ner_deid_roberta_i2b2_en_4.1.0_3.0_1660139968678.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
documentAssembler = DocumentAssembler() \
        .setInputCol("text") \
        .setOutputCol("document")

sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")\
       .setInputCols(["document"])\
       .setOutputCol("sentence")

tokenizer = Tokenizer() \
    .setInputCols("sentence") \
    .setOutputCol("token")

tokenClassifier = BertForTokenClassification.pretrained("roberta_ner_deid_roberta_i2b2","en") \
    .setInputCols(["sentence", "token"]) \
    .setOutputCol("ner")

pipeline = Pipeline(stages=[documentAssembler, sentenceDetector, tokenizer, tokenClassifier])

data = spark.createDataFrame([["PUT YOUR STRING HERE"]]).toDF("text")

result = pipeline.fit(data).transform(data)
```
```scala
val documentAssembler = new DocumentAssembler()
          .setInputCol("text")
          .setOutputCol("document")

val sentenceDetector = SentenceDetectorDLModel.pretrained("sentence_detector_dl", "xx")
       .setInputCols(Array("document"))
       .setOutputCol("sentence")

val tokenizer = new Tokenizer()
    .setInputCols(Array("sentence"))
    .setOutputCol("token")

val tokenClassifier = BertForTokenClassification.pretrained("roberta_ner_deid_roberta_i2b2","en")
    .setInputCols(Array("sentence", "token"))
    .setOutputCol("ner")

val pipeline = new Pipeline().setStages(Array(documentAssembler,sentenceDetector, tokenizer, tokenClassifier))

val data = Seq("PUT YOUR STRING HERE").toDF("text")

val result = pipeline.fit(data).transform(data)
```
</div>

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|roberta_ner_deid_roberta_i2b2|
|Compatibility:|Spark NLP 4.1.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[document, token]|
|Output Labels:|[ner]|
|Language:|en|
|Size:|1.3 GB|
|Case sensitive:|true|
|Max sentence length:|128|

## References

- https://huggingface.co/obi/deid_roberta_i2b2
- https://arxiv.org/pdf/1907.11692.pdf
- https://github.com/obi-ml-public/ehr_deidentification/tree/master/steps/train
- https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4978170/
- https://www.hhs.gov/hipaa/for-professionals/privacy/laws-regulations/index.html
- https://github.com/obi-ml-public/ehr_deidentification
- https://github.com/obi-ml-public/ehr_deidentification/tree/master/steps/forward_pass
- https://github.com/obi-ml-public/ehr_deidentification/blob/master/AnnotationGuidelines.md