text:
import { TfCommand, CoreArguments } from "../../../lib/tfcommand";
import extPub = require("../default");
import args = require("../../../lib/arguments");
import extBase = require("../default");

export function getCommand(args: string[]): TfCommand<extPub.ExtensionArguments, void> {
	return new ExtensionPublisherBase<void>(args);
}

export class ExtensionPublisherBase<T> extends extPub.ExtensionBase<T> {
	protected description = "Commands for managing Visual Studio Marketplace Publishers.";
	protected serverCommand = false;

	protected setCommandArgs(): void {
		super.setCommandArgs();
		this.registerCommandArgument(
			"serviceUrl",
			"Market URL",
			"URL to the VSS Marketplace.",
			args.StringArgument,
			extBase.ExtensionBase.getMarketplaceUrl,
		);
	}

	public exec(cmd?: any): Promise<any> {
		return this.getHelp(cmd);
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { factory } from '../../utils/factory.js'
import { deepMap } from '../../utils/collection.js'
import { log2Number } from '../../plain/number/index.js'

const name = 'log2'
const dependencies = ['typed', 'config', 'Complex']

export const createLog2 = /* #__PURE__ */ factory(name, dependencies, ({ typed, config, Complex }) => {
  /**
   * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
   *
   * For matrices, the function is evaluated element wise.
   *
   * Syntax:
   *
   *    math.log2(x)
   *
   * Examples:
   *
   *    math.log2(0.03125)           // returns -5
   *    math.log2(16)                // returns 4
   *    math.log2(16) / math.log2(2) // returns 4
   *    math.pow(2, 4)               // returns 16
   *
   * See also:
   *
   *    exp, log, log1p, log10
   *
   * @param {number | BigNumber | Complex | Array | Matrix} x
   *            Value for which to calculate the logarithm.
   * @return {number | BigNumber | Complex | Array | Matrix}
   *            Returns the 2-base logarithm of `x`
   */
  return typed(name, {
    number: function (x) {
      if (x >= 0 || config.predictable) {
        return log2Number(x)
      } else {
        // negative value -> complex value computation
        return _log2Complex(new Complex(x, 0))
      }
    },

    Complex: _log2Complex,

    BigNumber: function (x) {
      if (!x.isNegative() || config.predictable) {
        return x.log(2)
      } else {
        // downgrade to number, return Complex valued result
        return _log2Complex(new Complex(x.toNumber(), 0))
      }
    },

    'Array | Matrix': function (x) {
      return deepMap(x, this)
    }
  })

  /**
   * Calculate log2 for a complex value
   * @param {Complex} x
   * @returns {Complex}
   * @private
   */
  function _log2Complex (x) {
    const newX = Math.sqrt(x.re * x.re + x.im * x.im)
    return new Complex(
      (Math.log2) ? Math.log2(newX) : Math.log(newX) / Math.LN2,
      Math.atan2(x.im, x.re) / Math.LN2
    )
  }
})


text:
require File.expand_path(File.dirname(__FILE__)+"/spec_helper.rb")
describe Rubyvis::Layout::Cluster do
  include Rubyvis::LayoutSpec
  it "should have correct properties" do
    props=[:antialias, :bottom, :canvas, :cursor, :data, :events, :fill_style,:group,  :height, :id, :inner_radius, :left, :line_width, :links,  :nodes,   :orient, :outer_radius, :overflow, :reverse, :right, :stroke_style, :title, :top, :transform, :visible, :view_box, :width].inject({}) {|ac, v| ac[v]=true; ac}
    Rubyvis::Layout::Cluster.properties.should==props
  end
  it "should be called using Rubyvis.Layout.Cluster" do
    expect(Rubyvis.Layout.Cluster).to eql Rubyvis::Layout::Cluster
  end
  describe "html tests" do

    before  do
      color=Rubyvis.Colors.category19
      w=400
      h=400

      @vis = Rubyvis.Panel.new().
        width(w).
        height(h).
        top(20).
        bottom(10).
        left(10)

      @cluster = @vis.add(Rubyvis::Layout::Cluster).
      nodes(hier_nodes_big).
      orient("top")

      @cluster.node.add(Rubyvis::Dot).
      fill_style(lambda {|d| color[d.node_value]}).
      stroke_style("black").
      line_width(1).
      antialias(false)

      @cluster.link.add(Rubyvis::Line)

      @cluster.node_label.add(Rubyvis::Label).
        text(lambda {|d| d.node_name})
    end
    it "should render correctly 'cluster.html' custom test" do
      @vis.render
      @pv_out=fixture_svg_read("layout_cluster.svg")
      File.open("test.svg","w") {|fp| fp.write(@vis.to_svg)}
      expect(@vis.to_svg).to have_same_svg_elements(@pv_out)
    end
    it "should render correctly 'cluster_left_group_2.html' custom test" do
      @cluster.orient("left").group(2)
      @vis.render
      @pv_out=fixture_svg_read("layout_cluster_left_group_2.svg")
      expect(@vis.to_svg).to have_same_svg_elements(@pv_out)
    end
  end
end


text:
class RemoveItemsFromFeed < ActiveRecord::Migration[5.0]
  def change
    remove_column :feeds, :items, :text
  end
end


text:
import jsonschema

from mock import MagicMock
from mock import Mock
from mock import patch
from testtools.matchers import Is, Equals
from trove.cluster import models
from trove.cluster.models import Cluster, DBCluster
from trove.cluster.service import ClusterController
from trove.cluster.tasks import ClusterTasks
from trove.cluster import views
import trove.common.cfg as cfg
from trove.common import exception
from trove.common.strategies.cluster import strategy
from trove.common import utils
from trove.datastore import models as datastore_models
from trove.tests.unittests import trove_testtools

class TestClusterController(trove_testtools.TestCase):

    def setUp(self):
        super(TestClusterController, self).setUp()
        self.controller = ClusterController()
        self.locality = 'anti-affinity'
        instances = [
            {
                "flavorRef": "7",
                "volume": {
                    "size": 1
                },
                "availability_zone": "az",
                "nics": [
                    {"net-id": "e89aa5fd-6b0a-436d-a75c-1545d34d5331"}
                ]
            }
        ] * 5

        self.cluster = {
            "cluster": {
                "name": "products",
                "datastore": {
                    "type": "mongodb",
                    "version": "2.4.10"
                },
                "instances": instances,
                "locality": self.locality,
            }
        }
        self.add_shard = {
            "add_shard": {}
        }

    def test_get_schema_create(self):
        schema = self.controller.get_schema('create', self.cluster)
        self.assertIsNotNone(schema)
        self.assertIn('cluster', schema['properties'])
        self.assertTrue('cluster')

    def test_get_schema_action_add_shard(self):
        schema = self.controller.get_schema('add_shard', self.add_shard)
        self.assertIsNotNone(schema)
        self.assertIn('add_shard', schema['properties'])

    def test_validate_create(self):
        body = self.cluster
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_add_shard(self):
        body = self.add_shard
        schema = self.controller.get_schema('add_shard', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertTrue(validator.is_valid(body))

    def test_validate_create_blankname(self):
        body = self.cluster
        body['cluster']['name'] = "     "
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        self.assertThat(len(errors), Is(1))
        self.assertThat(errors[0].message,
                        Equals("'     ' does not match '^.*[0-9a-zA-Z]+.*$'"))

    def test_validate_create_blank_datastore(self):
        body = self.cluster
        body['cluster']['datastore']['type'] = ""
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        error_messages = [error.message for error in errors]
        error_paths = [error.path.pop() for error in errors]
        self.assertThat(len(errors), Is(2))
        self.assertIn("'' is too short", error_messages)
        self.assertIn("'' does not match '^.*[0-9a-zA-Z]+.*$'", error_messages)
        self.assertIn("type", error_paths)

    def test_validate_create_bad_locality(self):
        body = self.cluster
        body['cluster']['locality'] = "$%^&"
        schema = self.controller.get_schema('create', body)
        validator = jsonschema.Draft4Validator(schema)
        self.assertFalse(validator.is_valid(body))
        errors = sorted(validator.iter_errors(body), key=lambda e: e.path)
        error_messages = [error.message for error in errors]
        error_paths = [error.path.pop() for error in errors]
        self.assertThat(len(errors), Is(1))
        self.assertIn("'$%^&' does not match '^.*[0-9a-zA-Z]+.*$'",
                      error_messages)
        self.assertIn("locality", error_paths)

    @patch.object(Cluster, 'create')
    @patch.object(datastore_models, 'get_datastore_version')
    def test_create_clusters_disabled(self,
                                      mock_get_datastore_version,
                                      mock_cluster_create):
        body = self.cluster
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        datastore_version = Mock()
        datastore_version.manager = 'mysql'
        mock_get_datastore_version.return_value = (Mock(), datastore_version)

        self.assertRaises(exception.ClusterDatastoreNotSupported,
                          self.controller.create,
                          req,
                          body,
                          tenant_id)

    @patch.object(Cluster, 'create')
    @patch.object(utils, 'get_id_from_href')
    @patch.object(datastore_models, 'get_datastore_version')
    def test_create_clusters(self,
                             mock_get_datastore_version,
                             mock_id_from_href,
                             mock_cluster_create):
        body = self.cluster
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)

        req = Mock()
        req.environ = Mock()
        req.environ.__getitem__ = Mock(return_value=context)
        datastore_version = Mock()
        datastore_version.manager = 'mongodb'
        datastore = Mock()
        mock_get_datastore_version.return_value = (datastore,
                                                   datastore_version)
        instances = [
            {
                'volume_size': 1,
                'volume_type': None,
                'flavor_id': '1234',
                'availability_zone': 'az',
                'modules': None,
                'region_name': None,
                'nics': [
                    {'net-id': 'e89aa5fd-6b0a-436d-a75c-1545d34d5331'}
                ]
            }
        ] * 5
        mock_id_from_href.return_value = '1234'

        mock_cluster = Mock()
        mock_cluster.instances = []
        mock_cluster.instances_without_server = []
        mock_cluster.datastore_version.manager = 'mongodb'
        mock_cluster_create.return_value = mock_cluster

        self.controller.create(req, body, tenant_id)
        mock_cluster_create.assert_called_with(context, 'products',
                                               datastore, datastore_version,
                                               instances, {},
                                               self.locality, None)

    @patch.object(Cluster, 'load')
    def test_show_cluster(self,
                          mock_cluster_load):
        tenant_id = Mock()
        id = Mock()
        context = trove_testtools.TroveTestContext(self)
        req = Mock()
        req.environ = Mock()
        req.environ.__getitem__ = Mock(return_value=context)

        mock_cluster = Mock()
        mock_cluster.instances = []
        mock_cluster.instances_without_server = []
        mock_cluster.datastore_version.manager = 'mongodb'
        mock_cluster_load.return_value = mock_cluster
        mock_cluster.locality = self.locality

        self.controller.show(req, tenant_id, id)
        mock_cluster_load.assert_called_with(context, id)

    @patch.object(Cluster, 'load')
    @patch.object(Cluster, 'load_instance')
    def test_show_cluster_instance(self,
                                   mock_cluster_load_instance,
                                   mock_cluster_load):
        tenant_id = Mock()
        cluster_id = Mock()
        instance_id = Mock()
        context = trove_testtools.TroveTestContext(self)
        req = Mock()
        req.environ = Mock()
        req.environ.__getitem__ = Mock(return_value=context)
        cluster = Mock()
        mock_cluster_load.return_value = cluster
        cluster.id = cluster_id
        self.controller.show_instance(req, tenant_id, cluster_id, instance_id)
        mock_cluster_load_instance.assert_called_with(context, cluster.id,
                                                      instance_id)

    @patch.object(Cluster, 'load')
    def test_delete_cluster(self, mock_cluster_load):
        tenant_id = Mock()
        cluster_id = Mock()
        req = MagicMock()
        cluster = Mock()
        trove_testtools.patch_notifier(self)
        mock_cluster_load.return_value = cluster
        self.controller.delete(req, tenant_id, cluster_id)
        cluster.delete.assert_called_with()

class TestClusterControllerWithStrategy(trove_testtools.TestCase):

    def setUp(self):
        super(TestClusterControllerWithStrategy, self).setUp()
        self.controller = ClusterController()
        self.cluster = {
            "cluster": {
                "name": "products",
                "datastore": {
                    "type": "mongodb",
                    "version": "2.4.10"
                },
                "instances": [
                    {
                        "flavorRef": "7",
                        "volume": {
                            "size": 1
                        },
                    },
                    {
                        "flavorRef": "7",
                        "volume": {
                            "size": 1
                        },
                    },
                    {
                        "flavorRef": "7",
                        "volume": {
                            "size": 1
                        },
                    },
                    {
                        "flavorRef": "7",
                        "volume": {
                            "size": 1
                        },
                    },
                    {
                        "flavorRef": "7",
                        "volume": {
                            "size": 1
                        },
                    }
                ]
            }
        }

    def tearDown(self):
        super(TestClusterControllerWithStrategy, self).tearDown()
        cfg.CONF.clear_override('cluster_support', group='mongodb')
        cfg.CONF.clear_override('api_strategy', group='mongodb')

    @patch.object(datastore_models, 'get_datastore_version')
    @patch.object(models.Cluster, 'create')
    def test_create_clusters_disabled(self,
                                      mock_cluster_create,
                                      mock_get_datastore_version):

        cfg.CONF.set_override('cluster_support', False, group='mongodb',
                              enforce_type=True)

        body = self.cluster
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        datastore_version = Mock()
        datastore_version.manager = 'mongodb'
        mock_get_datastore_version.return_value = (Mock(), datastore_version)

        self.assertRaises(exception.TroveError, self.controller.create, req,
                          body, tenant_id)

    @patch.object(views.ClusterView, 'data', return_value={})
    @patch.object(datastore_models, 'get_datastore_version')
    @patch.object(models.Cluster, 'create')
    def test_create_clusters_enabled(self,
                                     mock_cluster_create,
                                     mock_get_datastore_version,
                                     mock_cluster_view_data):

        cfg.CONF.set_override('cluster_support', True, group='mongodb',
                              enforce_type=True)

        body = self.cluster
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        datastore_version = Mock()
        datastore_version.manager = 'mongodb'
        mock_get_datastore_version.return_value = (Mock(), datastore_version)

        mock_cluster = Mock()
        mock_cluster.datastore_version.manager = 'mongodb'
        mock_cluster_create.return_value = mock_cluster
        self.controller.create(req, body, tenant_id)

    @patch.object(models.Cluster, 'load')
    def test_controller_action_multi_action(self,
                                            mock_cluster_load):

        body = {'do_stuff': {}, 'do_stuff2': {}}
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)
        cluster_id = Mock()

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        cluster = Mock()
        cluster.instances_without_server = [Mock()]
        cluster.datastore_version.manager = 'test_dsv'
        mock_cluster_load.return_value = cluster

        self.assertRaisesRegexp(exception.TroveError,
                                'should have exactly one action specified',
                                self.controller.action, req,
                                body, tenant_id, cluster_id)

    @patch.object(models.Cluster, 'load')
    def test_controller_action_no_strategy(self,
                                           mock_cluster_load):

        body = {'do_stuff2': {}}
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)
        cluster_id = Mock()

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        db_info = DBCluster(ClusterTasks.NONE, id=cluster_id,
                            tenant_id=tenant_id)
        cluster = Cluster(context, db_info, datastore='test_ds',
                          datastore_version='test_dsv')
        mock_cluster_load.return_value = cluster

        self.assertRaisesRegexp(exception.TroveError,
                                'Action do_stuff2 not supported',
                                self.controller.action, req,
                                body, tenant_id, cluster_id)

    @patch.object(strategy, 'load_api_strategy')
    @patch.object(models.Cluster, 'load')
    def test_controller_action_found(self,
                                     mock_cluster_load,
                                     mock_cluster_api_strategy):

        body = {'grow': {}}
        tenant_id = Mock()
        context = trove_testtools.TroveTestContext(self)
        cluster_id = 'test_uuid'

        req = Mock()
        req.environ = MagicMock()
        req.environ.get = Mock(return_value=context)

        cluster = Mock()
        cluster.instances_without_server = [Mock()]
        cluster.datastore_version.manager = 'test_dsv'
        mock_cluster_load.return_value = cluster

        self.controller.action(req, body, tenant_id, cluster_id)
        self.assertEqual(1, cluster.action.call_count)


text:
package nam.service.src.main.java;

import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import nam.client.ClientLayerHelper;
import nam.model.Element;
import nam.model.ModelLayerHelper;
import nam.model.Operation;
import nam.model.Parameter;
import nam.model.Result;
import nam.model.Service;
import nam.model.Services;
import nam.model.TransportType;
import nam.model.util.OperationUtil;
import nam.model.util.ServiceUtil;
import nam.model.util.ServicesUtil;
import nam.model.util.TypeUtil;
import nam.service.ServiceLayerHelper;

import org.aries.util.NameUtil;

import aries.codegen.AbstractBeanBuilder;
import aries.codegen.util.CodeUtil;
import aries.generation.engine.GenerationContext;
import aries.generation.model.AnnotationUtil;
import aries.generation.model.ModelAnnotation;
import aries.generation.model.ModelAttribute;
import aries.generation.model.ModelClass;
import aries.generation.model.ModelOperation;
import aries.generation.model.ModelParameter;

/**
 * Builds a Client Interceptor (i.e. client-side) Implementation {@link ModelClass} object given a {@link Service} Specification as input;
 *
 * Model construction properties:
 *

 *
generateJavadoc

 *

 *
 * @author tfisher
 */
public class MessageInterceptorBuilder extends AbstractBeanBuilder {

	private MessageInterceptorProvider messageInterceptorProvider;

	public MessageInterceptorBuilder(GenerationContext context) {
		super(context);
		initialize();
	}

	protected void initialize() {
		messageInterceptorProvider = new MessageInterceptorProvider(context);
	}

	public List<ModelClass> buildClasses(Services services) throws Exception {
		List<ModelClass> modelClasses = new ArrayList<ModelClass>();
		List<Service> list = ServicesUtil.getServices(services);
		Iterator<Service> iterator = list.iterator();
		while (iterator.hasNext()) {
			Service service = iterator.next();
			ModelClass modelClass = buildClass(service);
			modelClasses.add(modelClass);
		}
		return modelClasses;
	}

	public ModelClass buildClass(Service service) throws Exception {
		Element element = null;
		if (service.getElement() != null)
			element = context.getElementByType(service.getElement());

		String namespace = ClientLayerHelper.getNamespace(service);
		String packageName = ServiceLayerHelper.getServicePackageName(service);
		String interfaceName = ServiceLayerHelper.getServiceInterfaceName(service);
		String className = ServiceLayerHelper.getServiceInterfaceName(service) + "Interceptor";
		String rootName = ServiceUtil.getRootName(service);
		String beanName = NameUtil.capName(className);

		setRootName(rootName);
		setBeanName(beanName);
		setPackageName(packageName);
		setClassName(className);
		ModelClass modelClass = new ModelClass();
		modelClass.setType(org.aries.util.TypeUtil.getTypeFromNamespaceAndLocalPart(namespace, beanName));
		modelClass.setPackageName(packageName);
		modelClass.setClassName(className);
		modelClass.setName(beanName);
		modelClass.setNamespace(namespace);
		modelClass.setParentClassName("MessageInterceptor<"+interfaceName+">");
		modelClass.addImportedClass("org.aries.message.MessageInterceptor");
		//modelClass.addImplementedInterface(interfaceName);
		initializeClass(modelClass, service, element);
		return modelClass;
	}

	protected void initializeClass(ModelClass modelClass, Service service, Element element) throws Exception {
		//modelClass.setParentClassName("org.aries.action.AbstractAction");
		initializeClassAnnotations(modelClass, service, element);
		initializeImportedClasses(modelClass, service, element);
		initializeInstanceFields(modelClass, service, element);
		initializeInstanceOperations(modelClass, service, element);
	}

	protected void initializeClassAnnotations(ModelClass modelClass, Service service, Element element) throws Exception {
		List<ModelAnnotation> classAnnotations = modelClass.getClassAnnotations();
		classAnnotations.add(AnnotationUtil.createStatelessAnnotation());
		classAnnotations.add(AnnotationUtil.createLocalBeanAnnotation());
		classAnnotations.add(AnnotationUtil.createConcurrencyManagementAnnotation());
		classAnnotations.add(AnnotationUtil.createTransactionManagementAnnotation());

//		switch (context.getClientLayerBeanType()) {
//		case POJO: initializeClassAnnotations_POJO(modelClass, service, element); break;
//		case EJB: initializeClassAnnotations_EJB(modelClass, service, element); break;
//		case SEAM: initializeClassAnnotations_SEAM(modelClass, service, element); break;
//		}
	}

	protected void initializeClassAnnotations_POJO(ModelClass modelClass, Service service, Element element) throws Exception {
		//nothing for now
	}

	protected void initializeClassAnnotations_EJB(ModelClass modelClass, Service service, Element element) throws Exception {
		List<ModelAnnotation> classAnnotations = modelClass.getClassAnnotations();
		classAnnotations.add(AnnotationUtil.createAnnotation("Stateless"));
		classAnnotations.add(AnnotationUtil.createAnnotation("Local", service.getInterfaceName()+".class"));
		modelClass.addImportedClass("javax.ejb.Stateless");
		modelClass.addImportedClass("javax.ejb.Local");
	}

	protected void initializeClassAnnotations_SEAM(ModelClass modelClass, Service service, Element element) throws Exception {
		List<ModelAnnotation> classAnnotations = modelClass.getClassAnnotations();
		//classAnnotations.add(AnnotationUtil.createAnnotation("AutoCreate"));
		//classAnnotations.add(AnnotationUtil.createBypassInterceptorsAnnotation());
		//classAnnotations.add(AnnotationUtil.createScopeAnnotation(ScopeType.SESSION));
		//String serviceContextName = ClientLayerHelper.getClientContextName(service);
		//classAnnotations.add(AnnotationUtil.createNameAnnotation(serviceContextName));
		//modelClass.addImportedClass("org.jboss.seam.ScopeType");
		//modelClass.addImportedClass("org.jboss.seam.annotations.AutoCreate");
		//modelClass.addImportedClass("org.jboss.seam.annotations.Name");
		//modelClass.addImportedClass("org.jboss.seam.annotations.Scope");
		//modelClass.addImportedClass("org.jboss.seam.annotations.intercept.BypassInterceptors");
	}

	protected void initializeImportedClasses(ModelClass modelClass, Service service, Element element) throws Exception {
		modelClass.addImportedClasses(CodeUtil.getImportedClasses(service));

		modelClass.addImportedClass("org.aries.message.Message");
		modelClass.addImportedClass("org.aries.message.MessageInterceptor");
		//modelClass.addImportedClass("org.aries.util.ExceptionUtil");
		//modelClass.addImportedClass("org.aries.Assert");

		modelClass.addStaticImportedClass("javax.ejb.ConcurrencyManagementType.BEAN");
		modelClass.addStaticImportedClass("javax.ejb.TransactionAttributeType.REQUIRED");
		modelClass.addStaticImportedClass("javax.ejb.TransactionManagementType.CONTAINER");

		modelClass.addImportedClass("javax.ejb.LocalBean");
		modelClass.addImportedClass("javax.ejb.Stateless");
		modelClass.addImportedClass("javax.ejb.ConcurrencyManagement");
		modelClass.addImportedClass("javax.ejb.TransactionAttribute");
		modelClass.addImportedClass("javax.ejb.TransactionManagement");
		modelClass.addImportedClass("javax.inject.Inject");

		if (element != null)
			modelClass.addImportedClass(ModelLayerHelper.getElementQualifiedName(element));
		//modelClass.addImportedClass("java.io.Serializable");
		//addImportedClassesForFaults(modelClass, ServiceUtil.getFaults(service));
		//initializeImportedClasses(modelClass, ServiceUtil.getOperations(service));
	}

	protected void initializeImportedClasses(ModelClass modelClass, List<Operation> operations) throws Exception {
		Iterator<Operation> iterator = operations.iterator();
		while (iterator.hasNext()) {
			Operation operation = iterator.next();
			initializeImportedClasses(modelClass, operation);
		}
	}

	protected void initializeImportedClasses(ModelClass modelClass, Operation operation) throws Exception {
		List<Parameter> parameters = operation.getParameters();
		Iterator<Parameter> parameterIterator = parameters.iterator();
		while (parameterIterator.hasNext()) {
			Parameter parameter = parameterIterator.next();
			Element element = context.findElement(parameter);
			if (element != null)
				addImportedClass(modelClass, element.getType());
			else addImportedClass(modelClass, parameter.getType());
		}
		List<Result> results = operation.getResults();
		Result result = null;
		if (!results.isEmpty())
			result = results.get(0);
		if (result != null) {
			Element element = context.findElement(result);
			if (element != null)
				addImportedClass(modelClass, element.getType());
			else addImportedClass(modelClass, result.getType());
		}
	}

	protected void initializeInstanceFields(ModelClass modelClass, Service service, Element element) throws Exception {
		CodeUtil.addStaticLoggerField(modelClass, className);
		//CodeUtil.addSerialVersionUIDField(modelClass);
		modelClass.addStaticAttribute(createHandlerAttribute(service));
	}

	public ModelAttribute createHandlerAttribute(Service service) {
		String packageName = ServiceLayerHelper.getServicePackageName(service);
		String interfaceName = ServiceLayerHelper.getServiceInterfaceName(service);
		String className = interfaceName + "Handler";
		String beanName = NameUtil.uncapName(className);

		ModelAttribute attribute = new ModelAttribute();
		attribute.addAnnotation(AnnotationUtil.createInjectAnnotation());
		attribute.setModifiers(Modifier.PROTECTED);
		attribute.setPackageName(packageName);
		attribute.setClassName(className);
		attribute.setName(beanName);
		attribute.setGenerateGetter(false);
		attribute.setGenerateSetter(false);
		return attribute;
	}

	protected void initializeInstanceOperations(ModelClass modelClass, Service service, Element element) throws Exception {
		//add service location method
		//createModelOperation_CreateMessage(modelClass, service);
		//createModelOperation_GetProxy(modelClass, service);
		//createModelOperation_GetHandler(modelClass, service);

		//modelClass.addInstanceOperation(createActionOperation(service));
		//modelClass.addInstanceOperation(createValidateOperation());
		List<Operation> operations = ServiceUtil.getOperations(service);
		Iterator<Operation> iterator = operations.iterator();
		while (iterator.hasNext()) {
			Operation operation = iterator.next();
			ModelOperation modelOperation = new ModelOperation();
			modelOperation.addAnnotation(AnnotationUtil.createTransactionAttributeAnnotation());
			modelOperation.setName(OperationUtil.getUniqueOperationName(operation));
			ModelParameter modelParameter = new ModelParameter();
			modelParameter.setPackageName("org.aries.message");
			modelParameter.setClassName("Message");
			modelParameter.setName("message");
			modelOperation.addParameter(modelParameter);
			modelOperation.setResultType("Message");

			messageInterceptorProvider.setService(service);
			String serviceName = messageInterceptorProvider.getServiceName(operation.getName());
			messageInterceptorProvider.generateSourceCode_ProxyInvocation(modelOperation, operation);
			modelClass.addInstanceOperation(modelOperation);
		}
	}

	protected void createModelOperation_CreateMessage(ModelClass modelClass, Service service) {
		ModelOperation modelOperation = new ModelOperation();
		modelOperation.setName("createMessage");
		modelOperation.setModifiers(Modifier.PUBLIC);
		modelOperation.setResultType("Message");
		messageInterceptorProvider.generateSourceCode_CreateMessage(modelOperation, service);
		modelClass.addInstanceOperation(modelOperation);
	}

	protected void createModelOperation_GetProxy(ModelClass modelClass, Service service) {
		ModelOperation modelOperation = new ModelOperation();
		modelOperation.setName("getProxy");
		modelOperation.setModifiers(Modifier.PUBLIC);
		modelOperation.setResultType("ServiceProxy");
		ModelParameter modelParameter = new ModelParameter();
		modelParameter.setPackageName("java.lang");
		modelParameter.setClassName("String");
		modelParameter.setName("serviceId");
		modelOperation.addParameter(modelParameter);
		messageInterceptorProvider.generateSourceCode_GetProxy(modelOperation, TransportType.RMI);
		modelClass.addInstanceOperation(modelOperation);
	}

	protected void createModelOperation_GetHandler(ModelClass modelClass, Service service) {
		String interfaceName = ServiceLayerHelper.getServiceInterfaceName(service);

		ModelOperation modelOperation = new ModelOperation();
		modelOperation.setName("getHandler");
		modelOperation.setModifiers(Modifier.PROTECTED);
		modelOperation.setResultType(interfaceName + "Handler");
		messageInterceptorProvider.generateSourceCode_GetHandler(modelOperation, service);
		modelClass.addInstanceOperation(modelOperation);
	}

}


text:
#ifndef SkBitmapSourceDeserializer_DEFINED
#define SkBitmapSourceDeserializer_DEFINED

#include "SkFlattenable.h"

// A temporary utility class to support deserializing legacy SkBitmapSource as SkImageSource.
// Should be removed when SKP versions which may contain SkBitmapSource records are phased out.
class SkBitmapSourceDeserializer : public SkFlattenable {
public:
    SK_DEFINE_FLATTENABLE_TYPE(SkImageFilter)
    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBitmapSource)
};

#endif


text:
<?php

declare(strict_types=1);

namespace Artisanry\Database\Schema;

use Artisanry\Database\Traits\Schema\RelationsTrait;
use Artisanry\Database\Traits\Schema\TypesTrait;
use Illuminate\Database\Schema\Blueprint as BaseBlueprint;

class Blueprint extends BaseBlueprint
{
    use RelationsTrait;
    use TypesTrait;
}


text:
var banner = require('../widget/banner');

function layout () {
    banner.display();
}

exports.layout = layout;


text:
<?php namespace CobwebInfo\Cobra5Sdk;

interface Cobra5Interface
{

    /**
     * Get all the datastores for the current organisation
     *
     * @param boolean $forceGroup
     * @return array
     */
    public function getStores($forceGroup = true);

    /**
     * Get a single datastore by it's id
     *
     * @param int $id
     * @return array
     */
    public function getStore($id);

    /**
     * Get a single datastore by it's name
     *
     * @param string $name
     * @return array
     */
    public function getStoreByName($name);

    /**
     * Get all the documents for the current datastore
     *
     * @param int $store_id
     * @param array $filters
     * @return array
     */
    public function getDocuments($store_id = null, $filters = array());

    /**
     * Get a single document by it's id
     *
     * @param int $id
     * @return array
     */
    public function getDocument($id);

    /**
     * Get the last edited document
     *
     * @return array
     */
    public function getLastEditedDocument();

    /**
     * Get edited documents between two unix timestamps
     *
     * @param string $start
     * @param string $end
     * @return array
     */
    public function getEditedDocuments($start, $end);

    /**
     * Get the documents for a specific datastore
     *
     * @param int $store_id
     * @return array
     */
    public function getDocumentsByDataStore($datastore_id);

    /**
     * Get the documents for a specific category
     *
     * @param int $category_id
     * @param int $store_id
     * @return array
     */
    public function getDocumentsForCategory($category_id, $store_id = null);

    /**
     * Get a specific category by it's id
     *
     * @param int $category_id
     * @param int $store_id
     * @return array
     */
    public function getCategory($category_id, $store_id = null);

    /**
     * Get the categories for a specific datastore
     *
     * @param int $store_id
     * @return array
     */
    public function getCategoriesForStore($store_id);

    /**
     * Get the XML version of a document
     *
     * @param int $id
     * @return string
     */
    public function getDocumentXml($id);

    /**
     * Get the PDF version of a document
     *
     * @param int $id
     * @param int $datastore_id
     * @return string
     */
    public function getDocumentPdf($id, $datastore_id = null);

    /**
     * Get the HTML version of a document
     *
     * @param int $id
     * @param int $datastore_id
     * @return string
     */
    public function getDocumentHtml($id, $datastore_id = null);

    /**
     * Search the API for a particular term
     *
     * @param string $term
     * @param int $start
     * @param int $limit
     * @param string $type
     * @return array
     */
    public function documentSearch($term, $start = 0, $limit = 10, $type = false);

    /**
     * Fetch all events from the API not just the current ones
     *
     * @return array
     */
    public function fetchAllEvents();

}


text:
cd strict-csp && npm install && npm run-script build && cd ..
cd strict-csp && npm link && cd ..
cd strict-csp-html-webpack-plugin && npm link 'strict-csp' && cd ..
cd strict-csp-html-webpack-plugin && npm link && cd ..


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>test.sprockets.stl.lib.DifferentFrom</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package test ::
        Package sprockets ::
        Package stl ::
        Module lib ::
        Class DifferentFrom

[hide private]

[frames] | no frames]

Class DifferentFrom

source code

object --+
         |
 Qualifier --+
             |
            DifferentFrom

Qualify a string which is different from the previous one.

        Nested Classes
        [hide private]

Inherited from Qualifier:
      __metaclass__

        Instance Methods
        [hide private]

          Generate(self,
        prev)

      Generage a valid value.

            source code

          Validate(self,
        value,
        prev)

      Validate a value.

            source code

          __init__(self)

      x.__init__(...) initializes x; see help(type(x)) for signature

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Class Variables
        [hide private]

        __abstractmethods__ = frozenset([])

Inherited from Qualifier (private):
      _abc_cache,
      _abc_negative_cache,
      _abc_negative_cache_version,
      _abc_registry

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

Generate(self,
        prev)

  	source code

Generage a valid value.

Args:
  *args: External arguments necessary for generation.

Returns: The generated value.

Overrides:
        Qualifier.Generate

(inherited documentation)

Validate(self,
        value,
        prev)

  	source code

Validate a value.

Args:
  value: The value to validate
  *args: External arguments necessary for validation.

Returns:
  True if the value is valid, False otherwise.

Overrides:
        Qualifier.Validate

(inherited documentation)

__init__(self)

(Constructor)

  	source code

x.__init__(...) initializes x; see help(type(x)) for signature

Overrides:
        object.__init__

(inherited documentation)

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Mon Feb 27 15:08:41 2017

      http://epydoc.sourceforge.net


text:
<?php
namespace Oro\Component\Testing;

trait ClassExtensionTrait
{
    public function assertClassExtends($expected, $actual)
    {
        $rc = new \ReflectionClass($actual);

        $this->assertTrue(
            $rc->isSubclassOf($expected),
            sprintf('Failed assert that class %s extends %s class.', $actual, $expected)
        );
    }

    public function assertClassImplements($expected, $actual)
    {
        $rc = new \ReflectionClass($actual);

        $this->assertTrue(
            $rc->implementsInterface($expected),
            sprintf('Failed assert that class %s implements %s interface.', $actual, $expected)
        );
    }
}


text:
using System;

namespace basicOptions3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


text:
/*

---------------------------------------------------------------------------------

                                               oooo
                                               `888
                oooo d8b  .ooooo.  oooo    ooo  888  oooo  oooo
                `888""8P d88' `88b  `88b..8P'   888  `888  `888
                 888     888   888    Y888'     888   888   888
                 888     888   888  .o8"'88b    888   888   888
                d888b    `Y8bod8P' o88'   888o o888o  `V88V"V8P'

                                                  www.roxlu.com
                                             www.apollomedia.nl
                                          www.twitter.com/roxlu

---------------------------------------------------------------------------------

  # AudioEncoderFAAC

  Simple wrapper around libfaac to support AAC bsed audio encoding for the streamer.
  This project started out using MP3 for the audio encoding, but it turns out that
  HTTP Live Streamer (HLS) does not work with MP3 on iOS devices.

  This encoder API work similar to the others, you first make sure that all necessary
  settings are set using setup() (or other functions which might be added later). Then
  you call initialize() to actually create an encoder instance using all the provided
  settings. Then start feeding audio packets and when ready you call shutdown() to free
  up all the used memory.

*/

#ifndef ROXLU_VIDEOSTREAMER_AUDIOENCODER_FAAC_H
#define ROXLU_VIDEOSTREAMER_AUDIOENCODER_FAAC_H

#include <streamer/core/Log.h>
#include <streamer/core/EncoderTypes.h>
#include <streamer/core/AudioEncoder.h>
#include <streamer/flv/FLVTypes.h>
#include <faac.h>
#include <string>
#include <stdint.h>
#include <fstream>
#include <vector>

std::string faac_debug_mpeg_version_to_string(int v);
std::string faac_debug_object_type_to_string(int v);
std::string faac_debug_input_format_to_string(int v);
std::string faac_debug_output_format_to_string(int v);

class AudioEncoderFAAC : public AudioEncoder {
 public:
  AudioEncoderFAAC();
  ~AudioEncoderFAAC();
  void setOutputFile(std::string filepath); /* when you want to write the encoded data to a file, set the output file. */
  bool setup(AudioSettings s); /* provide the AudioEncoderFAAC encoder with all the necessary settings; it will return when the settings are invalid OR when libfaac cannot handle them */
  bool initialize(); /* after specifying all the settings, call initialize to create an instance of the encoder; this allocates memory which should be freed by shutdown, which closes the encoder */
  bool shutdown(); /* frees all allocated memory */
  void print(); /* provide us with some debug info */
  bool encodePacket(AVPacket* p, FLVTag& tag); /* encode the given data into "tag" */
  unsigned long getSamplesNeededForEncoding(); /* get the number of framers we need to pass into encodePacket(). You should use this value for your audio input callback, so you get this number of samples everytime you want to encode something; or you need to keep a custom buffer and make sure it has enough data in it before encoding it */
  std::vector<uint8_t> getAudioSpecificConfig(); /* return the AAC audio specific config. This is e.g. used in the FLV stream, we simple return the result from `faacEncGetDecoderSpecificInfo()` */
 private:
  bool validateSettings(AudioSettings& s); /* validates the given audio settings so we're sure that libfaac can use them */
  uint8_t getNumChannels(); /* determines the number of channels that we need to use, base on the settings.mode member. only detect 1 or 2 channels  */
 private:
  unsigned long nsamples_needed; /* the number of samples that the faac encoder needs for each encode() call */
  unsigned long nbytes_out; /* the total number of bytes that can be produces by a encoder() call */
  unsigned char* faac_buffer; /* the buffer into which we write the faac data, is created in initialize(), freed in shutdown() */
  faacEncHandle encoder;
  AudioSettings settings;
  std::string output_file; /* when setOutputFile() is called this is set to that value */
  std::ofstream ofs; /* used for debugging purposes, when setOutputFile() is used we write the encoded data to this file. */
  std::vector<uint8_t> audio_specific_config; /* the AAC specific config, used in the FLV bitstream when AAC is used. */
};

inline uint8_t AudioEncoderFAAC::getNumChannels() {

#if !defined(NDEBUG)
  if(settings.mode == AV_AUDIO_MODE_UNKNOWN) {
    STREAMER_ERROR("Cannot determine the number of channels in AudioEncoderFAAC because the AudioSettings.mode is set to AV_AUDIO_MODE_UNKNOWN. Did you call setup()?");
    ::exit(EXIT_FAILURE);
  }
#endif

  return (settings.mode ==  AV_AUDIO_MODE_MONO) ? 1 : 2;
}

inline unsigned long AudioEncoderFAAC::getSamplesNeededForEncoding() {
  return nsamples_needed;
}

inline void AudioEncoderFAAC::setOutputFile(std::string filepath) {
  output_file = filepath;
}

inline std::vector<uint8_t> AudioEncoderFAAC::getAudioSpecificConfig() {
  return audio_specific_config;
}

#endif


text:
#ifndef RBTREE_H
#define RBTREE_H

#include <types.h>

/*
 * red-black tree node
 */
struct rb_node_t {
	int color;
	struct rb_node_t *parent;
	struct rb_node_t *left;
	struct rb_node_t *right;
};

/*
 * red-black tree root
 */
struct rb_tree_t {
	struct rb_node_t *root;
};

/*
 * get a pointer to the record in which the node is embedded
 */
#define rb_item(node, type, field) (container_of(node, type, field))

/*
 * get a pointer to link between a node and it's parent -- if it's the root
 * return the address of the tree
 */
#define rb_ptr(n, r) \
	((n)->parent ? ((n)->parent->left == (n) ? &(n)->parent->left : &(n)->parent->right) : &r)

void rb_tree_init(struct rb_tree_t *tree);
void rb_link(struct rb_node_t *node, struct rb_node_t *parent,
		struct rb_node_t **link);
void rb_insert(struct rb_tree_t *tree, struct rb_node_t *ins);
void rb_remove(struct rb_tree_t *tree, struct rb_node_t *rem);
struct rb_node_t* rb_next(struct rb_node_t *node);
struct rb_node_t* rb_prev(struct rb_node_t *node);

#endif /* RBTREE_H */


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\search\UserSearch */
/* @var $form yii\bootstrap\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?php echo $form->field($model, 'id') ?>

    <?php echo $form->field($model, 'username') ?>

    <?php echo $form->field($model, 'auth_key') ?>

    <?php echo $form->field($model, 'email') ?>

    <?php echo $form->field($model, 'role') ?>

    <?php echo $form->field($model, 'status') ?>

    <?php echo $form->field($model, 'created_at') ?>

    <?php echo $form->field($model, 'updated_at') ?>

        <?php echo Html::submitButton(Yii::t('app/backend', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?php echo Html::resetButton(Yii::t('app/backend', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_share"
        android:icon="@android:drawable/ic_menu_share"
        android:title="@string/menu_share"/>
    <item
        android:id="@+id/menu_delete"
        android:icon="@android:drawable/ic_menu_delete"
        android:title="@string/menu_delete"/>
    <item
        android:id="@+id/menu_about"
        android:icon="@android:drawable/ic_menu_info_details"
        android:title="@string/menu_about"/>

</menu>


text:
title: 'Amazingly Designed Places Worth Looking Into'
date: 2011-04-04T18:46:00.000-06:00
draft: false
slug: amazingly-designed-places-worth-looking
tags: [Great Design]
---

[Curitiba, Brazil](http://en.wikipedia.org/wiki/Curitiba)
[Appirampattu Village Center, Tamil Nadu, India](http://farm4.static.flickr.com/3196/3822555612_808fcaaf18.jpg)


text:
package io.datalayer.data.queue;

/**
 * A generic interface for queues.
 *
 */
public interface Queue {
    /**
     * Stores a value in the queue. The size of the queue will increase by one.
     *
     * @param value The value to add.
     */
    public void enqueue(Object value);

    /**
     * Retrieves the value at the head of the queue. The size of the queue will decrease by one.
     *
     * @return The value at the head of the queue.
     * @throws EmptyQueueException If the queue is empty (isEmpty() == true).
     */
    public Object dequeue() throws EmptyQueueException;

    /**
     * Deletes all elements from the queue. The size of the queue will be reset to zero (0).
     */
    public void clear();

    /**
     * Obtains the number of elements in the queue.
     *
     * @return The number of elements in the queue.
     */
    public int size();

    /**
     * Determines if the queue is empty or not.
     *
     * @return true if the queue is empty (size() == 0); otherwise returns false.
     */
    public boolean isEmpty();
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.ai.formrecognizer.v3;

import com.azure.ai.formrecognizer.FormRecognizerClient;
import com.azure.ai.formrecognizer.FormRecognizerClientBuilder;
import com.azure.ai.formrecognizer.models.FieldValueType;
import com.azure.ai.formrecognizer.models.FormField;
import com.azure.ai.formrecognizer.models.FormRecognizerOperationResult;
import com.azure.ai.formrecognizer.models.RecognizedForm;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

/**
 * Sample for recognizing business card information from a document given through a file.
 */
public class RecognizeBusinessCard {

    /**
     * Main method to invoke this demo.
     *
     * @param args Unused. Arguments to the program.
     *
     * @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
     */
    public static void main(final String[] args) throws IOException {
        // Instantiate a client that will be used to call the service.
        FormRecognizerClient client = new FormRecognizerClientBuilder()
                                          .credential(new AzureKeyCredential("{key}"))
                                          .endpoint("https://{endpoint}.cognitiveservices.azure.com/")
                                          .buildClient();

        File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/resources"
            + "/sample-forms/businessCards/businessCard.jpg");
        byte[] fileContent = Files.readAllBytes(sourceFile.toPath());
        InputStream targetStream = new ByteArrayInputStream(fileContent);

        SyncPoller<FormRecognizerOperationResult, List<RecognizedForm>> recognizeBusinessCardPoller =
            client.beginRecognizeBusinessCards(targetStream, sourceFile.length());

        List<RecognizedForm> businessCardPageResults = recognizeBusinessCardPoller.getFinalResult();

        for (int i = 0; i < businessCardPageResults.size(); i++) {
            RecognizedForm recognizedForm = businessCardPageResults.get(i);
            Map<String, FormField> recognizedFields = recognizedForm.getFields();
            System.out.printf("----------- Recognized business card info for page %d -----------%n", i);
            FormField contactNamesFormField = recognizedFields.get("ContactNames");
            if (contactNamesFormField != null) {
                if (FieldValueType.LIST == contactNamesFormField.getValue().getValueType()) {
                    List<FormField> contactNamesList = contactNamesFormField.getValue().asList();
                    contactNamesList.stream()
                        .filter(contactName -> FieldValueType.MAP == contactName.getValue().getValueType())
                        .map(contactName -> {
                            System.out.printf("Contact name: %s%n", contactName.getValueData().getText());
                            return contactName.getValue().asMap();
                        })
                        .forEach(contactNamesMap -> contactNamesMap.forEach((key, contactName) -> {
                            if ("FirstName".equals(key)) {
                                if (FieldValueType.STRING == contactName.getValue().getValueType()) {
                                    String firstName = contactName.getValue().asString();
                                    System.out.printf("\tFirst Name: %s, confidence: %.2f%n",
                                        firstName, contactName.getConfidence());
                                }
                            }
                            if ("LastName".equals(key)) {
                                if (FieldValueType.STRING == contactName.getValue().getValueType()) {
                                    String lastName = contactName.getValue().asString();
                                    System.out.printf("\tLast Name: %s, confidence: %.2f%n",
                                        lastName, contactName.getConfidence());
                                }
                            }
                        }));
                }
            }

            FormField jobTitles = recognizedFields.get("JobTitles");
            if (jobTitles != null) {
                if (FieldValueType.LIST == jobTitles.getValue().getValueType()) {
                    List<FormField> jobTitlesItems = jobTitles.getValue().asList();
                    jobTitlesItems.forEach(jobTitlesItem -> {
                        if (FieldValueType.STRING == jobTitlesItem.getValue().getValueType()) {
                            String jobTitle = jobTitlesItem.getValue().asString();
                            System.out.printf("Job Title: %s, confidence: %.2f%n",
                                jobTitle, jobTitlesItem.getConfidence());
                        }
                    });
                }
            }

            FormField departments = recognizedFields.get("Departments");
            if (departments != null) {
                if (FieldValueType.LIST == departments.getValue().getValueType()) {
                    List<FormField> departmentsItems = departments.getValue().asList();
                    departmentsItems.forEach(departmentsItem -> {
                        if (FieldValueType.STRING == departmentsItem.getValue().getValueType()) {
                            String department = departmentsItem.getValue().asString();
                            System.out.printf("Department: %s, confidence: %.2f%n",
                                department, departmentsItem.getConfidence());
                        }
                    });
                }
            }

            FormField emails = recognizedFields.get("Emails");
            if (emails != null) {
                if (FieldValueType.LIST == emails.getValue().getValueType()) {
                    List<FormField> emailsItems = emails.getValue().asList();
                    emailsItems.forEach(emailsItem -> {
                        if (FieldValueType.STRING == emailsItem.getValue().getValueType()) {
                            String email = emailsItem.getValue().asString();
                            System.out.printf("Email: %s, confidence: %.2f%n", email, emailsItem.getConfidence());
                        }
                    });
                }
            }

            FormField websites = recognizedFields.get("Websites");
            if (websites != null) {
                if (FieldValueType.LIST == websites.getValue().getValueType()) {
                    List<FormField> websitesItems = websites.getValue().asList();
                    websitesItems.forEach(websitesItem -> {
                        if (FieldValueType.STRING == websitesItem.getValue().getValueType()) {
                            String website = websitesItem.getValue().asString();
                            System.out.printf("Web site: %s, confidence: %.2f%n",
                                website, websitesItem.getConfidence());
                        }
                    });
                }
            }

            FormField mobilePhones = recognizedFields.get("MobilePhones");
            if (mobilePhones != null) {
                if (FieldValueType.LIST == mobilePhones.getValue().getValueType()) {
                    List<FormField> mobilePhonesItems = mobilePhones.getValue().asList();
                    mobilePhonesItems.forEach(mobilePhonesItem -> {
                        if (FieldValueType.PHONE_NUMBER == mobilePhonesItem.getValue().getValueType()) {
                            String mobilePhoneNumber = mobilePhonesItem.getValue().asPhoneNumber();
                            System.out.printf("Mobile phone number: %s, confidence: %.2f%n",
                                mobilePhoneNumber, mobilePhonesItem.getConfidence());
                        }
                    });
                }
            }

            FormField otherPhones = recognizedFields.get("OtherPhones");
            if (otherPhones != null) {
                if (FieldValueType.LIST == otherPhones.getValue().getValueType()) {
                    List<FormField> otherPhonesItems = otherPhones.getValue().asList();
                    otherPhonesItems.forEach(otherPhonesItem -> {
                        if (FieldValueType.PHONE_NUMBER == otherPhonesItem.getValue().getValueType()) {
                            String otherPhoneNumber = otherPhonesItem.getValue().asPhoneNumber();
                            System.out.printf("Other phone number: %s, confidence: %.2f%n",
                                otherPhoneNumber, otherPhonesItem.getConfidence());
                        }
                    });
                }
            }

            FormField faxes = recognizedFields.get("Faxes");
            if (faxes != null) {
                if (FieldValueType.LIST == faxes.getValue().getValueType()) {
                    List<FormField> faxesItems = faxes.getValue().asList();
                    faxesItems.forEach(faxesItem -> {
                        if (FieldValueType.PHONE_NUMBER == faxesItem.getValue().getValueType()) {
                            String faxPhoneNumber = faxesItem.getValue().asPhoneNumber();
                            System.out.printf("Fax phone number: %s, confidence: %.2f%n",
                                faxPhoneNumber, faxesItem.getConfidence());
                        }
                    });
                }
            }

            FormField addresses = recognizedFields.get("Addresses");
            if (addresses != null) {
                if (FieldValueType.LIST == addresses.getValue().getValueType()) {
                    List<FormField> addressesItems = addresses.getValue().asList();
                    addressesItems.forEach(addressesItem -> {
                        if (FieldValueType.STRING == addressesItem.getValue().getValueType()) {
                            String address = addressesItem.getValue().asString();
                            System.out.printf("Address: %s, confidence: %.2f%n", address, addressesItem.getConfidence());
                        }
                    });
                }
            }

            FormField companyName = recognizedFields.get("CompanyNames");
            if (companyName != null) {
                if (FieldValueType.LIST == companyName.getValue().getValueType()) {
                    List<FormField> companyNameItems = companyName.getValue().asList();
                    companyNameItems.forEach(companyNameItem -> {
                        if (FieldValueType.STRING == companyNameItem.getValue().getValueType()) {
                            String companyNameValue = companyNameItem.getValue().asString();
                            System.out.printf("Company name: %s, confidence: %.2f%n", companyNameValue, companyNameItem.getConfidence());
                        }
                    });
                }
            }
        }
    }
}


text:
import { ApplicationRef, Component, isDevMode } from '@angular/core';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: `

AngularFire kitchen sink (samples/advanced)

    <router-outlet></router-outlet>
  `,
  styles: []
})
export class AppComponent {
  title = 'sample';
  constructor(
    appRef: ApplicationRef,
  ) {
    if (isDevMode()) {
      appRef.isStable.pipe(
        debounceTime(200),
        distinctUntilChanged(),
      ).subscribe(it => {
        console.log('isStable', it);
      });
    }
  }
}


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/google/apis-client-generator/
 * Modify at your own risk.
 */

package com.google.testing.model;

/**
 * The matrix of environments in which the test is to be executed.
 *
 *
 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 Cloud Testing 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 EnvironmentMatrix extends com.google.api.client.json.GenericJson {

  /**
   * A list of Android devices; the test will be run only on the specified devices.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private AndroidDeviceList androidDeviceList;

  /**
   * A matrix of Android devices.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private AndroidMatrix androidMatrix;

  /**
   * A list of iOS devices.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private IosDeviceList iosDeviceList;

  /**
   * A list of Android devices; the test will be run only on the specified devices.
   * @return value or {@code null} for none
   */
  public AndroidDeviceList getAndroidDeviceList() {
    return androidDeviceList;
  }

  /**
   * A list of Android devices; the test will be run only on the specified devices.
   * @param androidDeviceList androidDeviceList or {@code null} for none
   */
  public EnvironmentMatrix setAndroidDeviceList(AndroidDeviceList androidDeviceList) {
    this.androidDeviceList = androidDeviceList;
    return this;
  }

  /**
   * A matrix of Android devices.
   * @return value or {@code null} for none
   */
  public AndroidMatrix getAndroidMatrix() {
    return androidMatrix;
  }

  /**
   * A matrix of Android devices.
   * @param androidMatrix androidMatrix or {@code null} for none
   */
  public EnvironmentMatrix setAndroidMatrix(AndroidMatrix androidMatrix) {
    this.androidMatrix = androidMatrix;
    return this;
  }

  /**
   * A list of iOS devices.
   * @return value or {@code null} for none
   */
  public IosDeviceList getIosDeviceList() {
    return iosDeviceList;
  }

  /**
   * A list of iOS devices.
   * @param iosDeviceList iosDeviceList or {@code null} for none
   */
  public EnvironmentMatrix setIosDeviceList(IosDeviceList iosDeviceList) {
    this.iosDeviceList = iosDeviceList;
    return this;
  }

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

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

}


text:
#ifndef TTOY_COMMON_GL_ERROR_H_
#define TTOY_COMMON_GL_ERROR_H_

#include <assert.h>

#include <GL/glew.h>

/* Checking for errors significantly affects performance with WebGL, so we
 * disable checking when compiling with Emscripten. */
#ifdef __EMSCRIPTEN__
#define DISABLE_CHECK_GL_ERROR 1
#else
#define DISABLE_CHECK_GL_ERROR 0
#endif

#define FORCE_CHECK_GL_ERROR() \
  (ttoy_checkGLError(__FILE__, __LINE__))

#define FORCE_ASSERT_GL_ERROR() \
  if (ttoy_checkGLError(__FILE__, __LINE__)) \
    assert(0);

#if DISABLE_CHECK_GL_ERROR

#define CHECK_GL_ERROR() (0)

#define ASSERT_GL_ERROR() ;

#else  // DISABLE_CHECK_GL_ERROR

#define CHECK_GL_ERROR() \
  (ttoy_checkGLError(__FILE__, __LINE__))

#define ASSERT_GL_ERROR() \
  if (ttoy_checkGLError(__FILE__, __LINE__)) \
    assert(0);

#endif  // DISABLE_CHECK_GL_ERROR

int ttoy_checkGLError(const char *file, int line);
const char *ttoy_glErrorToString(GLenum error);

#endif


text:
import social from './social'
import {openUserProvider} from './providers'

export default exports

export function getProfile(site, access_token) {
  console.log('oauthService.getProfile')
  if (social[site]) {
    return social[site].getProfile(access_token)
  }
  return Promise.reject(new Error('no support site:'+site))
}

export async function getOrCreateUser(site, access_token, props) {
  var profile = await getProfile(site, access_token)
  return await openUserProvider.getOrCreateUser(site, profile, props)
}


text:
package sdk.chat.firebase.adapter.utils;

import com.google.firebase.database.GenericTypeIndicator;

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

public class Generic {
    public class ContactHashMap extends HashMap<String, Long> {
        public ContactHashMap(){}
    }
    static public GenericTypeIndicator<HashMap<String, Long>> contactType() {
        return new GenericTypeIndicator<HashMap<String, Long>>() {};
    }
    public static GenericTypeIndicator<Map<String, Object>> mapStringObject() {
        return new GenericTypeIndicator<Map<String, Object>>() {};
    }

    public static GenericTypeIndicator<Map<String, String>> mapStringString() {
        return new GenericTypeIndicator<Map<String, String>>() {};
    }

//    public static GenericTypeIndicator<Map<String, Map<String, Object>>> mapStringMapStringObject() {
//        return new GenericTypeIndicator<Map<String, Map<String, Object>>>() {};
//    }

    public static GenericTypeIndicator<Map<String, Map<String, Long>>> readReceiptHashMap() {
        return new GenericTypeIndicator<Map<String, Map<String, Long>>>() {};
    }
}


text:
class Search::Qualifier

  attr_reader :name, :col, :type, :pattern, :default, :validator, :assoc, :preprocessor

  ANDABLE_TYPES = %w(text indexed translated)

  # Looks up the qualifier for the given chunk in the given set.
  # Raises an error if not found.
  def self.find_in_set(set, chunk)
    qualifier = nil

    trans = translation_key(set)

    # also add the qualifier translations for english if the current locale is not english
    trans.merge!(translation_key(set, :en)) unless I18n.locale == :en

    # add a bunch of entries with accents removed
    normalized = {}
    trans.each do |k,v|
      k_normalized = ActiveSupport::Inflector.transliterate(k)
      normalized[k_normalized] = v if k != k_normalized
    end
    trans.merge!(normalized)

    # try looking up the chunk. this should now work even the user didn't put in the accents
    qualifier_name = trans[chunk].to_s

    # if qualifier_name is not nil, try to find the qualifier object
    unless qualifier_name.nil?
      qualifier = set.detect{|q| q.name == qualifier_name}
    end

    # if we haven't found a matching qualifier yet, look for any regexp style ones
    if qualifier.nil?
      set.find_all{|q| q.regexp?}.each do |q|
        # check against the regular expression and then against the validator (if defined)
        if q.matches(chunk)
          qualifier = q
          break
        end
      end
    end

    raise Search::ParseError.new(I18n.t("search.invalid_qualifier", chunk: chunk)) if qualifier.nil?

    qualifier
  end

  def self.translation_key(set, locale = nil)
    names = set.map(&:name)
    I18n.t("search_qualifiers", locale: locale || I18n.locale, default: {}).select{ |k,v| names.include?(k.to_s) }.invert
  end

  # name  - the name of the qualifier (required, underscored)
  # type - qualifier type (optional, defaults to 'regular' - which means exact equality is required for match)
  # pattern - a regexp that will match the qualifier text
  # col - the database column being compared against (required unless :validator defined)
  # default - whether this qualifier should be assumed for terms with no qualifier (defaults to false)
  # validator - a lambda that accepts a MatchData object and returns whether the given string should be accepted as a valid qualifier
  def initialize(attribs)
    attribs.each{|k,v| instance_variable_set("@#{k}", v)}

    @default ||= false
    @assoc = Array.wrap(@assoc)
    @subst ||= {}
    @type ||= :regular
  end

  def op_valid?(op)
    case type
    when :regular, :text, :translated then %w(= !=).include?(op)
    when :indexed then op == '='
    else true
    end
  end

  # for a regexp qualifier, checks if the given chunk matches
  def matches(chunk)
    return false unless regexp?
    # do a regexp match and save match data
    # then check the validator if given
    (md = pattern.match(chunk)) && (validator.nil? || validator.call(md))
  end

  # whether multiple ANDed terms are allowed for this qualifier
  def and_allowed?
    ANDABLE_TYPES.include?(type.to_s)
  end

  def default?
    default
  end

  def regexp?
    pattern.present?
  end
end


text:
package ischema

// Code generated by xo. DO NOT EDIT.

import (
	"database/sql"
)

// RoleUdtGrant represents a row from 'information_schema.role_udt_grants'.
type RoleUdtGrant struct {
	Grantor       sql.NullString `json:"grantor"`        // grantor
	Grantee       sql.NullString `json:"grantee"`        // grantee
	UdtCatalog    sql.NullString `json:"udt_catalog"`    // udt_catalog
	UdtSchema     sql.NullString `json:"udt_schema"`     // udt_schema
	UdtName       sql.NullString `json:"udt_name"`       // udt_name
	PrivilegeType sql.NullString `json:"privilege_type"` // privilege_type
	IsGrantable   sql.NullString `json:"is_grantable"`   // is_grantable
}


text:
package org.apache.kylin.cube.model.validation.rule;

import org.apache.kylin.metadata.MetadataConstants;

/**
 * @author jianliu
 *
 */
public interface IKylinValidationConstants extends MetadataConstants {

    public static final int DEFAULT_MAX_AGR_GROUP_SIZE = 20;
    public static final String KEY_MAX_AGR_GROUP_SIZE = "rule_max.arggregation.group.size";
    public static final String KEY_IGNORE_UNKNOWN_FUNC = "rule_ignore_unknown_func";

}


text:
package view.tabs.course;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import model.StudentRecordSystem;
import view.MainWindow;

@SuppressWarnings("serial")
public class CoursesTabPanel extends JPanel {

    private MainWindow mainWindow;
    private StudentRecordSystem srs;

    private CoursesScrollPane coursesScrollPane;
    private CoursesControlPanel coursesControlPanel;

    public CoursesTabPanel(MainWindow mainWindow, StudentRecordSystem srs) {
        super();
        this.processParameters(mainWindow, srs);
        this.setupPanel();
        this.createComponents();
        this.addComopnentsToPanel();
    }

    private void processParameters(MainWindow mainWindow,
        StudentRecordSystem srs) {
        this.mainWindow = mainWindow;
        this.srs = srs;
    }

    private void setupPanel() {
        this.setLayout(new BorderLayout());
        this.setBackground(Color.WHITE);
        this.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
    }

    private void createComponents() {
        this.coursesScrollPane = new CoursesScrollPane(mainWindow, srs);
        this.coursesControlPanel = new CoursesControlPanel(coursesScrollPane);

    }

    private void addComopnentsToPanel() {
        this.add(coursesScrollPane, BorderLayout.CENTER);
        this.add(coursesControlPanel, BorderLayout.SOUTH);
    }

    public void refresh() {
        this.coursesScrollPane.refresh();
    }

}


text:
package vos;

import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonProperty;

public class ListaUsuarios
{
	@JsonProperty(value="usuarios")
	private List<Cliente> usuarios;

	public ListaUsuarios(@JsonProperty(value="usuarios")List<Cliente> usuarios){
		this.usuarios = usuarios;
	}

	public ListaUsuarios() {
		usuarios = new ArrayList<Cliente>();
	}

	public List<Cliente> getUsuarios() {
		return usuarios;
	}

	public void setUsuarios(List<Cliente> usuarios) {
		this.usuarios = usuarios;
	}

	public void addUsuario(ListaUsuarios usuariosNew)
	{
		this.usuarios.addAll(usuariosNew.getUsuarios());
	}
}


text:
A learning programming project

## Структура

* Compiler C#, Managed Module, CLR
* Принципы OOP, Patterns, SOLID
* Реализации многозадачности, конструкции синхронизации
* DI, IoC контейнеры - Autofac, Ninject, Unity
* ADO.Net, ORM - Entity Framework, NHibernate, Dapper
* Sockets, WCF (RPC, REST), Web API 2, Service Stack, P2P
* WPF - MVVM, MVP-VM
* WinForms
* Алгоритмы, векторная математика
* Фишки по Unity


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

<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE>
org.apache.commons.io.comparator (Commons IO 2.4 API)
</TITLE>

<META NAME="date" CONTENT="2012-06-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.apache.commons.io.comparator

Classes

CompositeFileComparator

DefaultFileComparator

DirectoryFileComparator

ExtensionFileComparator

LastModifiedFileComparator

NameFileComparator

PathFileComparator

SizeFileComparator


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.
 -->
<div wicket:id="container">
  <wicket:container wicket:id="subContainer">
    <span wicket:id="label">label</span>
  </wicket:container>
</div>


text:
require('coffee-script/register');
module.exports = require('./src/black-list-token');


text:
                <img src="<?php echo site_url('assets/portraits/5.jpg'); ?>">

Terrance arnold

<a class="nav-link" data-toggle="tab" href="<?php echo site_url('user/dashboard'); ?>" aria-controls="profile"
                  role="tab">Profile

			 <?php //echo '
';print_r($userviewprofile);exit; ?>
			 <?php if($this->session->flashdata('perimisionserror')): ?>

<?php echo $this->session->flashdata('perimisionserror');?>

					<?php endif; ?>

General Information

 User Name:  <?php echo htmlentities($userviewprofile['username']);?>

 First Name:  <?php echo htmlentities($userviewprofile['firstname']);?>

 Last Name:  <?php echo htmlentities($userviewprofile['lastname']);?>

 Date of Birth:   <?php echo htmlentities($userviewprofile['birthday']);?>

 Email Address:   <?php echo htmlentities($userviewprofile['email']);?>

 Contact Number:   <?php echo htmlentities($userviewprofile['phone']);?>

 Gender:   <?php echo htmlentities($userviewprofile['gender']);?>

 Workphone:   <?php echo htmlentities($userviewprofile['work_phone']);?>

 Cellphone:   <?php echo htmlentities($userviewprofile['cell_phone']);?>

Billing Address

				<address>
                  <?php echo htmlentities($userviewprofile['address1']);?>,<?php echo htmlentities($userviewprofile['address2']);?>

 <?php echo htmlentities($userviewprofile['city']);?>,<?php echo htmlentities($userviewprofile['state']);?>

 <?php echo htmlentities($userviewprofile['country']);?>, <?php echo htmlentities($userviewprofile['zipcode']);?>
				 P: <?php echo htmlentities($userviewprofile['phone']);?>
                </address>


text: Python library to print to console with a timestamp.


text:
![dkdeploy](assets/dkdeploy-logo.png)

# Dkdeploy::Cucumber

[![Build Status](https://travis-ci.org/dkdeploy/dkdeploy-cucumber.svg?branch=develop)](https://travis-ci.org/dkdeploy/dkdeploy-cucumber)
[![Gem Version](https://badge.fury.io/rb/dkdeploy-cucumber.svg)](https://badge.fury.io/rb/dkdeploy-cucumber) [![Inline docs](http://inch-ci.org/github/dkdeploy/dkdeploy-cucumber.svg?branch=develop)](http://inch-ci.org/github/dkdeploy/dkdeploy-cucumber)

## Description

This Rubygem `dkdeploy-cucumber` defines Cucumber steps for browser tests.
Tests are run with `capybara` and PhantomJS.

## Installation

Add this line to your application's Gemfile:

    gem 'dkdeploy-cucumber', '~> 4.1'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dkdeploy-cucumber

## Usage

You can see usage examples in the `features` directory.

## Testing

## Prerequisite

`rvm` to test against multiple Ruby versions.

### Running tests

1. Run `bundle exec rubocop`
2. Run `bundle exec cucumber`
3. Run `bundle exec cucumber --profile negative`

## Contributing

1. Install [git flow](https://github.com/nvie/gitflow)
2. If project is not checked out already do git clone `git@github.com:dkdeploy/dkdeploy-cucumber.git`
3. Checkout origin develop branch (`git checkout --track -b develop origin/develop`)
4. Git flow initialze `git flow init -d`
5. Installing gems `bundle update`
6. Create new feature branch (`git flow feature start my-new-feature`)
7. Run tests (README.md Testing)
8. Commit your changes (`git commit -am 'Add some feature'`)


text:
package org.jwatter.toolkit.generate.code;

public class ReturnStatement extends Statement implements Formattable
{
	public ReturnStatement ( Expression expression ) throws MalformedCodeError
	{
		super("return " + expression.format());
		if ( expression.getType() == void.class )
		{
			throw new MalformedCodeError("cannot return void value");
		}
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Org.Apache.Reef.Wake.RX.Impl;

namespace Test.Wake
{
    [TestClass]
    public class PubSubSubjectTest
    {
        [TestMethod]
        public void TestPubSubSubjectSingleThread()
        {
            int sum = 0;

            // Observer that adds sum of numbers up to and including x
            PubSubSubject<int> subject = new PubSubSubject<int>();
            subject.Subscribe(Observer.Create<int>(
                x =>
                {
                    for (int i = 0; i <= x; i++)
                    {
                        sum += i;
                    }
                }));

            subject.OnNext(10);
            subject.OnCompleted();
            Assert.AreEqual(sum, 55);
        }

        [TestMethod]
        public void TestPubSubSubjectMultipleThreads()
        {
            int sum = 0;

            PubSubSubject<int> subject = new PubSubSubject<int>();
            subject.Subscribe(Observer.Create<int>(x => sum += x));

            Thread[] threads = new Thread[10];
            for (int i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(() =>
                {
                    for (int j = 0; j < 10000; j++)
                    {
                        subject.OnNext(1);
                    }
                });

                threads[i].Start();
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }

            Assert.AreEqual(sum, 100000);
        }

        [TestMethod]
        public void TestMultipleTypes()
        {
            int sum1 = 0;
            int sum2 = 0;

            PubSubSubject<SuperEvent> subject = new PubSubSubject<SuperEvent>();
            subject.Subscribe(Observer.Create<SubEvent1>(x => sum1 += 100));
            subject.Subscribe(Observer.Create<SubEvent2>(x => sum2 += 500));

            subject.OnNext(new SubEvent1());
            subject.OnNext(new SubEvent2());
            subject.OnNext(new SubEvent2());

            Assert.AreEqual(sum1, 100);
            Assert.AreEqual(sum2, 1000);
        }

        [TestMethod]
        public void TestOnCompleted()
        {
            int sum = 0;

            PubSubSubject<int> subject = new PubSubSubject<int>();
            subject.Subscribe(Observer.Create<int>(x => sum += x));

            subject.OnNext(10);
            Assert.AreEqual(10, sum);

            subject.OnNext(10);
            Assert.AreEqual(20, sum);

            // Check that after calling OnCompleted, OnNext will do nothing
            subject.OnCompleted();
            subject.OnNext(10);
            Assert.AreEqual(20, sum);
        }

        [TestMethod]
        public void TestOnError()
        {
            int sum = 0;

            PubSubSubject<int> subject = new PubSubSubject<int>();
            subject.Subscribe(Observer.Create<int>(x => sum += x));

            subject.OnNext(10);
            Assert.AreEqual(10, sum);

            subject.OnNext(10);
            Assert.AreEqual(20, sum);

            // Check that after calling OnError, OnNext will do nothing
            subject.OnError(new Exception("error"));
            subject.OnNext(10);
            Assert.AreEqual(20, sum);
        }

        [TestMethod]
        public void TestDisposeSingleSubject()
        {
            int sum = 0;

            PubSubSubject<int> subject = new PubSubSubject<int>();
            var disposable = subject.Subscribe(Observer.Create<int>(x => sum += x));

            subject.OnNext(10);
            subject.OnNext(10);
            subject.OnNext(10);
            Assert.AreEqual(30, sum);

            // Unregister the subject and check that calling OnNext does nothing
            disposable.Dispose();
            subject.OnNext(10);
            Assert.AreEqual(30, sum);
        }

        [TestMethod]
        public void TestDisposeMultipleSubjects()
        {
            int sum1 = 0;
            int sum2 = 0;

            SubEvent1 event1 = new SubEvent1();
            SubEvent2 event2 = new SubEvent2();

            PubSubSubject<SuperEvent> subject = new PubSubSubject<SuperEvent>();
            var disposable1 = subject.Subscribe(Observer.Create<SubEvent1>(x => sum1 += 100));
            var disposable2 = subject.Subscribe(Observer.Create<SubEvent2>(x => sum2 += 500));

            subject.OnNext(event1);
            subject.OnNext(event2);
            subject.OnNext(event2);
            Assert.AreEqual(sum1, 100);
            Assert.AreEqual(sum2, 1000);

            // Check that unsubscribing from SubEvent1 does not affect other subscriptions
            disposable1.Dispose();
            subject.OnNext(event1);
            subject.OnNext(event2);
            Assert.AreEqual(sum1, 100);
            Assert.AreEqual(sum2, 1500);

            // Unsubscribe from the remaining event types
            disposable2.Dispose();
            subject.OnNext(event1);
            subject.OnNext(event2);
            Assert.AreEqual(sum1, 100);
            Assert.AreEqual(sum2, 1500);
        }

        class SuperEvent
        {
        }

        class SubEvent1 : SuperEvent
        {
        }

        class SubEvent2 : SuperEvent
        {
        }
    }
}


text:
describe Facts::Windows::Sshalgorithmkey do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Windows::Sshalgorithmkey.new }

    context 'when user is privileged' do
      let(:ssh) do
        [Facter::Util::Resolvers::Ssh.new(Facter::Util::Resolvers::FingerPrint
          .new('test', 'test'), 'ecdsa', 'test', 'ecdsa'),
         Facter::Util::Resolvers::Ssh.new(Facter::Util::Resolvers::FingerPrint
          .new('test', 'test'), 'rsa', 'test', 'rsa')]
      end
      let(:legacy_fact1) { { name: 'ecdsa', value: 'test' } }
      let(:legacy_fact2) { { name: 'rsa', value: 'test' } }

      before do
        allow(Facter::Resolvers::Identity).to receive(:resolve).with(:privileged).and_return(true)
        allow(Facter::Resolvers::Windows::Ssh).to receive(:resolve).with(:ssh).and_return(ssh)
      end

      it 'calls Facter::Resolvers::Windows::Identity' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Identity).to have_received(:resolve).with(:privileged)
      end

      it 'calls Facter::Resolvers::Windows::Ssh' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Windows::Ssh).to have_received(:resolve).with(:ssh)
      end

      it 'returns a list of resolved facts' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and \
          contain_exactly(
            an_object_having_attributes(name: "ssh#{legacy_fact1[:name]}key", value: legacy_fact1[:value]),
            an_object_having_attributes(name: "ssh#{legacy_fact2[:name]}key", value: legacy_fact2[:value])
          )
      end
    end

    context 'when user is privileged but no ssh key found' do
      let(:value) { nil }

      before do
        allow(Facter::Resolvers::Identity).to receive(:resolve).with(:privileged).and_return(true)
        allow(Facter::Resolvers::Windows::Ssh).to receive(:resolve).with(:ssh).and_return(nil)
      end

      it 'calls Facter::Resolvers::Windows::Ssh' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Windows::Ssh).to have_received(:resolve).with(:ssh)
      end

      it 'calls Facter::Resolvers::Windows::Identity' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Identity).to have_received(:resolve).with(:privileged)
      end

      it 'returns no facts' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and contain_exactly
      end
    end

    context 'when user is not privileged' do
      let(:value) { nil }

      before do
        allow(Facter::Resolvers::Identity).to receive(:resolve).with(:privileged).and_return(false)
        allow(Facter::Resolvers::Windows::Ssh).to receive(:resolve).with(:ssh).and_return(value)
      end

      it 'calls Facter::Resolvers::Windows::Identity' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Identity).to have_received(:resolve).with(:privileged)
      end

      it "doesn't call Facter::Resolvers::Windows::Ssh" do
        fact.call_the_resolver
        expect(Facter::Resolvers::Windows::Ssh).not_to have_received(:resolve).with(:ssh)
      end

      it 'returns no facts' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and contain_exactly
      end
    end
  end
end


text:
@interface MasterViewController ()

@property NSArray *demos;

@end

@implementation MasterViewController

- (void)awakeFromNib {
  [super awakeFromNib];
  if ([[UIDevice currentDevice] userInterfaceIdiom] ==
      UIUserInterfaceIdiomPad) {
    self.clearsSelectionOnViewWillAppear = NO;
    self.preferredContentSize = CGSizeMake(320.0, 600.0);
  }
}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.demos =
      @[ @"Nav Controller Blocks", @"Assert Blocks", @"Bluetooth Blocks" ];

  self.detailViewController = (DetailViewController *)
      [[self.splitViewController.viewControllers lastObject] topViewController];
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if ([[segue identifier] isEqualToString:@"showDetail"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    DetailViewController *controller = (DetailViewController *)
        [[segue destinationViewController] topViewController];
    controller.demo = indexPath.row;
    controller.title = self.demos[indexPath.row];
    controller.navigationItem.leftBarButtonItem =
        self.splitViewController.displayModeButtonItem;
    controller.navigationItem.leftItemsSupplementBackButton = YES;
  }
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section {
  return self.demos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell =
      [tableView dequeueReusableCellWithIdentifier:@"Cell"
                                      forIndexPath:indexPath];

  cell.textLabel.text = self.demos[indexPath.row];
  return cell;
}

@end