text:
enum class KeepAliveOrigin;
enum class KeepAliveRestartOption;

// Registers with KeepAliveRegistry on creation and unregisters them
// on destruction. Use these objects with a scoped_ptr for easy management.
class ScopedKeepAlive {
 public:
  ScopedKeepAlive(KeepAliveOrigin origin, KeepAliveRestartOption restart);
  ~ScopedKeepAlive();

 private:
  const KeepAliveOrigin origin_;
  const KeepAliveRestartOption restart_;

  DISALLOW_COPY_AND_ASSIGN(ScopedKeepAlive);
};

#endif  // CHROME_BROWSER_LIFETIME_SCOPED_KEEP_ALIVE_H_


text:
package org.sakaiproject.kernel.serialization.json;

import java.util.Collection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.PropertyFilter;

/**
 * A property filter that rejects null values.
 */
public class NullPropertyFilter implements PropertyFilter {

  /**
   * Filter the output of a property, if it should be emitted return false.
   * @param source The object containing the value
   * @param name the name of the key in the output structure
   * @param value the value of the object
   * @return true if the property should be filtered, false if not.
   */
  public boolean apply(Object source, String name, Object value) {
    if (value == null) {
      return true;
    }
    if (value instanceof JSONArray) {
      JSONArray array = (JSONArray) value;
      if (array.size() == 0) {
        return true;
      }
    }
    if (value instanceof JSONObject) {
      JSONObject object = (JSONObject) value;
      if (object.isNullObject() || object.isEmpty()) {
        return true;
      }
    }
    if (value instanceof Collection) {
      Collection<?> collection = (Collection<?>) value;
      if (collection.size() == 0) {
        return true;
      }
    }
    if (value instanceof Object[]) {
      Object[] oarray = (Object[]) value;
      if (oarray.length == 0) {
        return true;
      }
    }
    return false;
  }

}

redpajama_set_name: RedPajamaGithub


text:
package iot.jcypher.samples.domain.people.model;

public class Person extends Subject {

	private String firstName;
	private String lastName;
	private Gender gender;
	private String eyeColor;
	private Person father;
	private Person mother;

	public Person() {
		super();
	}

	public Person(String firstName, String lastName, Gender gender,
			String eyeColor) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.gender = gender;
		this.eyeColor = eyeColor;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public Gender getGender() {
		return gender;
	}

	public String getEyeColor() {
		return eyeColor;
	}

	public Person getFather() {
		return father;
	}

	public void setFather(Person father) {
		this.father = father;
	}

	public Person getMother() {
		return mother;
	}

	public void setMother(Person mother) {
		this.mother = mother;
	}

}


text:
list<const TreeNode*> list_subterms_recursively(const meta_environment& environment, const TreeNode& node) {
	list<pair<int, const TreeNode*> > prop_bindings_2 = upcast_bindings(environment.prop_bindings);
	list<const TreeNode*> temp, values(1,&node);
	list<const TreeNode*>::iterator it;

	for (it=values.begin();it!=values.end();++it) {
		temp = node.list_immediate_subterms();
		temp = list_immediate_ground_subterms(prop_bindings_2, temp);
 		values.insert(values.end(), temp.begin(), temp.end());
	}
	return values;
}

list<const Variable*> list_variables(const list<const TreeNode*>& values) {
	list<const Variable*> vars;
	list<const TreeNode*>::const_iterator it;
	const Variable* p_var;

	for (it=values.begin();it!=values.end();++it) {
		p_var = dynamic_cast<const Variable*>(*it);
		if (p_var) vars.push_back(p_var);
	}
	return vars;
}

list<const Proof*> filter_as_proof_terms(const list<const TreeNode*>& values) {
	list<const Proof*> values2;
	list<const TreeNode*>::const_iterator it;
	const Proof* p_prf;

	for (it = values.begin();it != values.end();++it) {
		p_prf = dynamic_cast<const Proof*>(*it);
		if (p_prf) values2.push_back(p_prf);
	}
	return values2;
}

const Proof& guess_quantifiers(const open_meta_environment& environment,
	list<Binding>& bindings,
	shared_ptr<const Proposition> prop,
	const list<const Proof*> values,
	list<const Variable*>::iterator it,
	list<const Variable*>::iterator end) {
	list<const Proof*>::const_iterator jt;
	list<const Variable*>::iterator next;
	meta_environment environment_2 = { environment.bindings, environment.prop_bindings };
	Proof& prf = const_cast<Proposition&>(*prop).default_prove_theorem(environment_2);
	list<const Variable*> temp_vars;

	if (it == end) return intuitionism(environment, prop);
	next = it;
	++next;
	for (jt = values.cbegin();jt != values.cend();++jt) {
		//temp_vars = list_variables(**jt);
		//if (find_equals(temp_vars.begin(), temp_vars.end(), **it)) continue; //Occurs check
		bind_variable(bindings, (*it)->get_variable(), *jt);
		prf = guess_quantifiers(environment, bindings, prop, values, next, end);
		bindings.pop_back();
		if (prf.check_proof(environment_2)) return prf;
	}
	return prf;
}

//A tactical designed to completely solve the E*A* prefix class (existential quantifiers
//preceding universal quantifiers). Intuitively for this class the universe of a sentence
//can be taken to be its existential variables and constant symbols. If a sentence has
//K such objects, then the correct instantiations can be guessed in K^N time where N
//is the number of existential variables. See Libkin 2012 for an exposition of this subject.
const Proof& quantifiers(const open_meta_environment& environment, shared_ptr<const Proposition> prop) {
	meta_environment environment_2 = { environment.bindings, environment.prop_bindings };
	list<const TreeNode*> temp, values = list_subterms_recursively(environment_2, *prop);
	list<const Variable*> vars;
	list<const Proof*> values2;
	list<PropBinding>::const_iterator it;
	list<Binding> bindings_copy = environment.bindings;
	open_meta_environment env_copy = { bindings_copy, environment.prop_bindings };

	for (it=environment.prop_bindings.cbegin();it!=environment.prop_bindings.cend();++it) {
		temp = list_subterms_recursively(environment_2, *it->second);
		values.insert(values.end(), temp.begin(), temp.end());
	}
	vars = list_variables(values);
	values2 = filter_as_proof_terms(values);
	return guess_quantifiers(env_copy, bindings_copy, prop, values2, vars.begin(), vars.end());
}


text:
<?php
return array(

    //----------------------------------------------
    // CONTROLLERS CONFIGURATION
    //-----------------------------------------------
    'controllers' => array(
        'invokables' => array(
            'Googlemap\Controller\Googlemap' => 'Googlemap\Controller\GooglemapController',
        ),
    ),

    //----------------------------------------------
    // ROUTER CONFIGURATION
    //-----------------------------------------------
    'router' => array(
        'routes' => array(
            'googlemap' => array(
                'type'    => 'Literal',
                'options' => array(
                    // Change this to something specific to your module
                    'route'    => '/googlemap',
                    'defaults' => array(
                        // Change this value to reflect the namespace in which
                        // the controllers for your module are found
                        '__NAMESPACE__' => 'Googlemap\Controller',
                        'controller'    => 'Googlemap',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    // This route is a sane default when developing a module;
                    // as you solidify the routes for your module, however,
                    // you may want to remove it and replace it with more
                    // specific routes.
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),

    //----------------------------------------------
    // VIEW MANAGER CONFIGURATION
    //-----------------------------------------------
    'view_manager' => array(
        'template_path_stack' => array(
            'Googlemap' => __DIR__ . '/../view',
        ),
    ),

    //----------------------------------------------
    // GOOGLEMAP CONFIGURATION
    //-----------------------------------------------
    'googlemap' => array(
        'account-type'		=> "free",                                              // ( free or business)
        'api-url'           => 'https://maps.googleapis.com/maps/api/js?v=3.exp',  // for free account only
    	'api-key'           => 'YOUR_API_KEY',                                     // for free account only
        'client-id'         => 'YOUR-CLIENT-ID',                                   // for business account only
        'cryptographic-key' => 'YOUR-CRYPTOGRAPHIC-KEY',                           // for business account only
        'sensor'            => "false",
        'libraries'         => array(
            'adsense',
            'drawing',
            'geometry',
            'panoramic',
            'places',
            'visualization',
            'weather',
        ),
        'map-type'          => 'ROADMAP',
    ),
);


text:
<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="head">
            <block type="channelengine/head" name="channelengine.tracking" template="channelengine/head.phtml" />
        </reference>
    </default>

    <checkout_onepage_success translate="label">
        <reference name="content">
            <block type="checkout/onepage_success" name="channelengine.checkout.success" template="channelengine/checkout/success.phtml"/>
        </reference>
    </checkout_onepage_success>

</layout>


text:
require "minitest/autorun"
require "minitest/spec"

require "google/gax"

require "google/cloud/monitoring"
require "google/cloud/monitoring/v3/group_service_client"
require "google/monitoring/v3/group_service_services_pb"

class CustomTestError_v3 < StandardError; end

# Mock for the GRPC::ClientStub class.
class MockGrpcClientStub_v3

  # @param expected_symbol [Symbol] the symbol of the grpc method to be mocked.
  # @param mock_method [Proc] The method that is being mocked.
  def initialize(expected_symbol, mock_method)
    @expected_symbol = expected_symbol
    @mock_method = mock_method
  end

  # This overrides the Object#method method to return the mocked method when the mocked method
  # is being requested. For methods that aren't being tested, this method returns a proc that
  # will raise an error when called. This is to assure that only the mocked grpc method is being
  # called.
  #
  # @param symbol [Symbol] The symbol of the method being requested.
  # @return [Proc] The proc of the requested method. If the requested method is not being mocked
  #   the proc returned will raise when called.
  def method(symbol)
    return @mock_method if symbol == @expected_symbol

    # The requested method is not being tested, raise if it called.
    proc do
      raise "The method #{symbol} was unexpectedly called during the " \
        "test for #{@expected_symbol}."
    end
  end
end

class MockGroupServiceCredentials_v3 < Google::Cloud::Monitoring::V3::Credentials
  def initialize(method_name)
    @method_name = method_name
  end

  def updater_proc
    proc do
      raise "The method `#{@method_name}` was trying to make a grpc request. This should not " \
          "happen since the grpc layer is being mocked."
    end
  end
end

describe Google::Cloud::Monitoring::V3::GroupServiceClient do

  describe 'list_groups' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#list_groups."

    it 'invokes list_groups without error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.project_path("[PROJECT]")

      # Create expected grpc response
      next_page_token = ""
      group_element = {}
      group = [group_element]
      expected_response = { next_page_token: next_page_token, group: group }
      expected_response = Google::Gax::to_proto(expected_response, Google::Monitoring::V3::ListGroupsResponse)

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::ListGroupsRequest, request)
        assert_equal(formatted_name, request.name)
        OpenStruct.new(execute: expected_response)
      end
      mock_stub = MockGrpcClientStub_v3.new(:list_groups, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("list_groups")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.list_groups(formatted_name)

          # Verify the response
          assert(response.instance_of?(Google::Gax::PagedEnumerable))
          assert_equal(expected_response, response.page.response)
          assert_nil(response.next_page)
          assert_equal(expected_response.group.to_a, response.to_a)
        end
      end
    end

    it 'invokes list_groups with error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.project_path("[PROJECT]")

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::ListGroupsRequest, request)
        assert_equal(formatted_name, request.name)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:list_groups, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("list_groups")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.list_groups(formatted_name)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end

  describe 'get_group' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#get_group."

    it 'invokes get_group without error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Create expected grpc response
      name_2 = "name2-1052831874"
      display_name = "displayName1615086568"
      parent_name = "parentName1015022848"
      filter = "filter-1274492040"
      is_cluster = false
      expected_response = {
        name: name_2,
        display_name: display_name,
        parent_name: parent_name,
        filter: filter,
        is_cluster: is_cluster
      }
      expected_response = Google::Gax::to_proto(expected_response, Google::Monitoring::V3::Group)

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::GetGroupRequest, request)
        assert_equal(formatted_name, request.name)
        OpenStruct.new(execute: expected_response)
      end
      mock_stub = MockGrpcClientStub_v3.new(:get_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("get_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.get_group(formatted_name)

          # Verify the response
          assert_equal(expected_response, response)

          # Call method with block
          client.get_group(formatted_name) do |response, operation|
            # Verify the response
            assert_equal(expected_response, response)
            refute_nil(operation)
          end
        end
      end
    end

    it 'invokes get_group with error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::GetGroupRequest, request)
        assert_equal(formatted_name, request.name)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:get_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("get_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.get_group(formatted_name)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end

  describe 'create_group' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#create_group."

    it 'invokes create_group without error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.project_path("[PROJECT]")
      group = {}

      # Create expected grpc response
      name_2 = "name2-1052831874"
      display_name = "displayName1615086568"
      parent_name = "parentName1015022848"
      filter = "filter-1274492040"
      is_cluster = false
      expected_response = {
        name: name_2,
        display_name: display_name,
        parent_name: parent_name,
        filter: filter,
        is_cluster: is_cluster
      }
      expected_response = Google::Gax::to_proto(expected_response, Google::Monitoring::V3::Group)

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::CreateGroupRequest, request)
        assert_equal(formatted_name, request.name)
        assert_equal(Google::Gax::to_proto(group, Google::Monitoring::V3::Group), request.group)
        OpenStruct.new(execute: expected_response)
      end
      mock_stub = MockGrpcClientStub_v3.new(:create_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("create_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.create_group(formatted_name, group)

          # Verify the response
          assert_equal(expected_response, response)

          # Call method with block
          client.create_group(formatted_name, group) do |response, operation|
            # Verify the response
            assert_equal(expected_response, response)
            refute_nil(operation)
          end
        end
      end
    end

    it 'invokes create_group with error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.project_path("[PROJECT]")
      group = {}

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::CreateGroupRequest, request)
        assert_equal(formatted_name, request.name)
        assert_equal(Google::Gax::to_proto(group, Google::Monitoring::V3::Group), request.group)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:create_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("create_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.create_group(formatted_name, group)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end

  describe 'update_group' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#update_group."

    it 'invokes update_group without error' do
      # Create request parameters
      group = {}

      # Create expected grpc response
      name = "name3373707"
      display_name = "displayName1615086568"
      parent_name = "parentName1015022848"
      filter = "filter-1274492040"
      is_cluster = false
      expected_response = {
        name: name,
        display_name: display_name,
        parent_name: parent_name,
        filter: filter,
        is_cluster: is_cluster
      }
      expected_response = Google::Gax::to_proto(expected_response, Google::Monitoring::V3::Group)

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::UpdateGroupRequest, request)
        assert_equal(Google::Gax::to_proto(group, Google::Monitoring::V3::Group), request.group)
        OpenStruct.new(execute: expected_response)
      end
      mock_stub = MockGrpcClientStub_v3.new(:update_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("update_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.update_group(group)

          # Verify the response
          assert_equal(expected_response, response)

          # Call method with block
          client.update_group(group) do |response, operation|
            # Verify the response
            assert_equal(expected_response, response)
            refute_nil(operation)
          end
        end
      end
    end

    it 'invokes update_group with error' do
      # Create request parameters
      group = {}

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::UpdateGroupRequest, request)
        assert_equal(Google::Gax::to_proto(group, Google::Monitoring::V3::Group), request.group)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:update_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("update_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.update_group(group)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end

  describe 'delete_group' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#delete_group."

    it 'invokes delete_group without error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::DeleteGroupRequest, request)
        assert_equal(formatted_name, request.name)
        OpenStruct.new(execute: nil)
      end
      mock_stub = MockGrpcClientStub_v3.new(:delete_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("delete_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.delete_group(formatted_name)

          # Verify the response
          assert_nil(response)

          # Call method with block
          client.delete_group(formatted_name) do |response, operation|
            # Verify the response
            assert_nil(response)
            refute_nil(operation)
          end
        end
      end
    end

    it 'invokes delete_group with error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::DeleteGroupRequest, request)
        assert_equal(formatted_name, request.name)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:delete_group, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("delete_group")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.delete_group(formatted_name)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end

  describe 'list_group_members' do
    custom_error = CustomTestError_v3.new "Custom test error for Google::Cloud::Monitoring::V3::GroupServiceClient#list_group_members."

    it 'invokes list_group_members without error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Create expected grpc response
      next_page_token = ""
      total_size = 705419236
      members_element = {}
      members = [members_element]
      expected_response = {
        next_page_token: next_page_token,
        total_size: total_size,
        members: members
      }
      expected_response = Google::Gax::to_proto(expected_response, Google::Monitoring::V3::ListGroupMembersResponse)

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::ListGroupMembersRequest, request)
        assert_equal(formatted_name, request.name)
        OpenStruct.new(execute: expected_response)
      end
      mock_stub = MockGrpcClientStub_v3.new(:list_group_members, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("list_group_members")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          response = client.list_group_members(formatted_name)

          # Verify the response
          assert(response.instance_of?(Google::Gax::PagedEnumerable))
          assert_equal(expected_response, response.page.response)
          assert_nil(response.next_page)
          assert_equal(expected_response.members.to_a, response.to_a)
        end
      end
    end

    it 'invokes list_group_members with error' do
      # Create request parameters
      formatted_name = Google::Cloud::Monitoring::V3::GroupServiceClient.group_path("[PROJECT]", "[GROUP]")

      # Mock Grpc layer
      mock_method = proc do |request|
        assert_instance_of(Google::Monitoring::V3::ListGroupMembersRequest, request)
        assert_equal(formatted_name, request.name)
        raise custom_error
      end
      mock_stub = MockGrpcClientStub_v3.new(:list_group_members, mock_method)

      # Mock auth layer
      mock_credentials = MockGroupServiceCredentials_v3.new("list_group_members")

      Google::Monitoring::V3::GroupService::Stub.stub(:new, mock_stub) do
        Google::Cloud::Monitoring::V3::Credentials.stub(:default, mock_credentials) do
          client = Google::Cloud::Monitoring::Group.new(version: :v3)

          # Call method
          err = assert_raises Google::Gax::GaxError, CustomTestError_v3 do
            client.list_group_members(formatted_name)
          end

          # Verify the GaxError wrapped the custom error that was raised.
          assert_match(custom_error.message, err.message)
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

        {% block head %}
        <meta charset="UTF-8">
        <title>{% block title %}Online reStructuredText editor{% endblock %}</title>

	<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/base.css"/>
	<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/site.css"/>
	<link rel="stylesheet" href="{{ request.script_root }}{{ MEDIA_URL }}style/menu.css"/>

        {% endblock %}

        Fork me on GitHub
        {% block body_head %}
        {% endblock %}

{% block site_title %}Online reStructuredText editor{% endblock %}

            <menu id="navigation">
                {%- block main_nav %}

Editor

About

                {% endblock -%}
            </menu>

            {%- block content %}
            {% endblock -%}

            Quick reStructuredText reference
            Copyright © rst.ninjs.org, 2011


text:
layout: "archives"
title: "Archives"
description: "Hey, this is Archives."
header-img: "img/tag-bg.jpg"
---


text:
package com.github.anno4j.schema_parsing.building;

/**
 * A resource that can be converted in some sort of Java code.
 */
interface BuildableOntologyResource {
}


text:
CREATE OR REPLACE FUNCTION mtp_get_kpi_year_data2(i_json json)
  RETURNS json AS
$BODY$

v_year = i_json.year

v_sql = "select date_part('year', mkpi.kmonth) as year, date_part('month', mkpi.kmonth) as month,
 eqpt.labname, eqpt.identifier, eqpt.equipid, eqpt.equipname,
 worktime, plantime, downtime,
 mkpi.kpi1, mkpi.kpi2
 from buss_eqpt_kpi  mkpi
 inner join buss_equipinfo eqpt on (mkpi.identifier = eqpt.identifier )
 and to_char(mkpi.kmonth, 'YYYY') = '#{v_year}'
 order by eqpt.seq, mkpi.kmonth
"
try
    rtn = plv8.execute(v_sql)
catch err
    plv8.elog(DEBUG, v_sql)

return {"retuning":rtn}

$BODY$
  LANGUAGE plcoffee VOLATILE
  COST 100;


text:
import { DataTransformerID } from './ids';
import { filterFramesTransformer, FilterOptions } from './filter';
import { DataTransformerInfo } from '../../types/transformations';
import { FrameMatcherID } from '../matchers/ids';

export interface FilterFramesByRefIdTransformerOptions {
  include?: string;
  exclude?: string;
}

export const filterFramesByRefIdTransformer: DataTransformerInfo<FilterFramesByRefIdTransformerOptions> = {
  id: DataTransformerID.filterByRefId,
  name: 'Filter data by query refId',
  description: 'select a subset of results',
  defaultOptions: {},

  /**
   * Return a modified copy of the series.  If the transform is not or should not
   * be applied, just return the input series
   */
  operator: (options) => (source) => {
    const filterOptions: FilterOptions = {};
    if (options.include) {
      filterOptions.include = {
        id: FrameMatcherID.byRefId,
        options: options.include,
      };
    }
    if (options.exclude) {
      filterOptions.exclude = {
        id: FrameMatcherID.byRefId,
        options: options.exclude,
      };
    }

    return source.pipe(filterFramesTransformer.operator(filterOptions));
  },
};


text:
<?php

class Google_Service_AdExchangeBuyer_TargetingValue extends Google_Model
{
  protected $creativeSizeValueType = 'Google_Service_AdExchangeBuyer_TargetingValueCreativeSize';
  protected $creativeSizeValueDataType = '';
  protected $dayPartTargetingValueType = 'Google_Service_AdExchangeBuyer_TargetingValueDayPartTargeting';
  protected $dayPartTargetingValueDataType = '';
  public $longValue;
  public $stringValue;

  public function setCreativeSizeValue(Google_Service_AdExchangeBuyer_TargetingValueCreativeSize $creativeSizeValue)
  {
    $this->creativeSizeValue = $creativeSizeValue;
  }
  public function getCreativeSizeValue()
  {
    return $this->creativeSizeValue;
  }
  public function setDayPartTargetingValue(Google_Service_AdExchangeBuyer_TargetingValueDayPartTargeting $dayPartTargetingValue)
  {
    $this->dayPartTargetingValue = $dayPartTargetingValue;
  }
  public function getDayPartTargetingValue()
  {
    return $this->dayPartTargetingValue;
  }
  public function setLongValue($longValue)
  {
    $this->longValue = $longValue;
  }
  public function getLongValue()
  {
    return $this->longValue;
  }
  public function setStringValue($stringValue)
  {
    $this->stringValue = $stringValue;
  }
  public function getStringValue()
  {
    return $this->stringValue;
  }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require 'pathname'

describe "Pathname#join" do
  it "without separators" do
    Pathname.new('/usr').join(Pathname.new('foo')).should == Pathname.new('/usr/foo')
  end

  it "with separators" do
    Pathname.new('/usr').join(Pathname.new('/foo')).should == Pathname.new('/foo')
  end

  it "with a string" do
    Pathname.new('/usr').join('foo').should == Pathname.new('/usr/foo')
  end

  it "with root" do
    Pathname.new('/usr').join(Pathname.new('/')).should == Pathname.new('/')
  end

  it "with a relative path" do
    Pathname.new('/usr').join(Pathname.new('../foo')).should == Pathname.new('/foo')
  end

  it "a relative path with current" do
    Pathname.new('.').join(Pathname.new('foo')).should == Pathname.new('foo')
  end

  it "an absolute path with current" do
    Pathname.new('.').join(Pathname.new('/foo')).should == Pathname.new('/foo')
  end

  it "a prefixed relative path with current" do
    Pathname.new('.').join(Pathname.new('./foo')).should == Pathname.new('foo')
  end

  it "multiple paths" do
    Pathname.new('.').join(Pathname.new('./foo'), 'bar').should == Pathname.new('foo/bar')
  end
end


text:
class Unidom::Party::Company < Unidom::Party::ApplicationRecord

  self.table_name = 'unidom_companies'

  include Unidom::Common::Concerns::ModelExtension
  include Unidom::Party::Concerns::AsSourceParty
  include Unidom::Party::Concerns::AsTargetParty

  validates :name, presence: true, length: { in: 2..self.columns_hash['name'].limit }

end unless Unidom::Common::Neglection.namespace_neglected? 'Unidom::Party::Company'


text:
package org.caching.context;

import org.jboss.cache.Cache;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.config.EvictionConfig;
import org.jboss.cache.transaction.JBossTransactionManagerLookup;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by iurii.dziuban on 30.09.2016.
 */
@Configuration
@ComponentScan(basePackages = {"org.caching.data.value", "org.caching.data.jboss_dao"})
public class JbossCachingContext {

    @Bean(destroyMethod="stop")
    public <String,Transaction> Cache<String, Transaction> cache() {
        org.jboss.cache.config.Configuration cacheConfiguration = new org.jboss.cache.config.Configuration();
        cacheConfiguration.setCacheMode(org.jboss.cache.config.Configuration.CacheMode.REPL_ASYNC);
        cacheConfiguration.setTransactionManagerLookupClass(JBossTransactionManagerLookup.class.getName());
        cacheConfiguration.setClusterName("cacheClusterName");
        cacheConfiguration.setEvictionConfig(new EvictionConfig());
        return new DefaultCacheFactory<String, Transaction>().createCache(cacheConfiguration, true);
    }

}


text:
const exec = require('./exec');
const path = require('path');
const readline = require('readline');
const semver = require('semver');
const pkg = require('../package.json');
const branchName = exec('git rev-parse --abbrev-ref HEAD', true);
const currentVersion = pkg.version;
const stdin = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
const syncRemote = (branchName, nextVersion) => {

  exec(`git push origin ${branchName}`);

  if (nextVersion) {
    exec(`git push --tags`);
    console.log(`TravisCI will now release to npm on the tagged commit ${nextVersion} for the pearson-ux account.`);
  }
};
const exitFailure = (message) => {
  console.error(message);
  process.exit(1);
};

// *** Releaser provides the target SEMVER-compliant version ***

stdin.question(`Next version (current is ${currentVersion})? `, (nextVersion) => {

  if (!semver.valid(nextVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: requires a semver-compliant version. See http://semver.org/`);
  }

  if (!semver.gt(nextVersion, currentVersion)) {
    exitFailure(`Version '${nextVersion}' is not valid: it must be greater than the current version.`);
  }

  if (nextVersion.startsWith('v')) {
    nextVersion = nextVersion.slice(1);
  }

  // Ensure unit tests pass before continuing!

  // Order of operations:
  // 1. Bump the version update in package.json and npm-shrinkwrap.json
  // 2. The 'version' custom npm script (defined in package.json) executes changelog generation and adding to commit
  // 3. Locally commit and tag
  exec(`npm version ${nextVersion}`);

  // push commit and tag on target release branch
  syncRemote(branchName, nextVersion);

  stdin.close();
});


text:
<?php
/**
 * ------------------------------------------------------------------------------------
 * Created by SAN Business Consultants for RAPTOR phase 2
 * Open Source VA Innovation Project 2011-2014
 * VA Innovator: Dr. Jonathan Medverd
 * SAN Implementation: Andrew Casertano, Frank Font, et al
 * Contacts: acasertano@sanbusinessconsultants.com, ffont@sanbusinessconsultants.com
 * ------------------------------------------------------------------------------------
 *
 */

namespace raptor;

module_load_include('php', 'raptor_datalayer', 'config/Choices');
require_once ('FormHelper.php');
module_load_include('php', 'raptor_datalayer', 'core/data_worklist');

/**
 * Implementes the radation dose add page.
 *
 * @author Frank Font of SAN Business Consultants
 */
class AddRadiationDoseHxEntryPage
{
    private $m_oContext = null;

    function __construct()
    {
        $this->m_oContext = \raptor\Context::getInstance();
    }

    /**
     * Get the values to populate the form.
     * @return type result of the queries as an array
     */
    function getFieldValues()
    {
        //TODO
        $myvalues = array();
        return $myvalues;
    }

    /**
     * Some checks to validate the data before we try to save it.
     */
    function looksValid($form, $myvalues)
    {
        $bGood = TRUE;
        //TODO - special checks here
        return $bGood;
    }

    /**
     * Write the values into the database.
     * Return 0 if there was an error, else 1.
     */
    function updateDatabase($form, $myvalues)
    {
        //TODO
        return 1;
    }

    /**
     * Get all the form contents for rendering
     * @return type renderable array
     */
    public function getForm($form, &$form_state, $disabled, $myvalues)
    {

        $form['data_entry_area1'] = array(
            '#prefix' => "\n
\n",
            '#suffix' => "\n
\n",
            '#disabled' => $disabled,
        );

        //TODO

        $form['data_entry_area1']['toppart']['placeholder'] = array(
            '#markup'         => '
'.t('PLACEHOLDER FOR THE ADD FORM').'
',
        );

        $form['data_entry_area1']['action_buttons'] = array(
            '#prefix' => "\n
\n",
            '#suffix' => "\n
\n",
            '#disabled' => $disabled,
        );
        $form['data_entry_area1']['action_buttons']['remove'] = array('#type' => 'submit'
                , '#attributes' => array('class' => array('admin-action-button'))
                , '#value' => t('Add This Radiation Dose Entry')
                , '#disabled' => $disabled
        );
        $form['data_entry_area1']['action_buttons']['cancel'] = array('#type' => 'item'
                , '#markup' => '<input class="raptor-dialog-cancel" type="button" value="Cancel">');

        return $form;
    }
}


text:
import DSLFilterTypes from "../../constants/DSLFilterTypes";
import DSLExpression from "../../structs/DSLExpression";
import DSLExpressionPart from "../../structs/DSLExpressionPart";
import DSLUtil from "../DSLUtil";

import DSLASTNodes from "../../structs/DSLASTNodes";

let thisParts, thisAst, thisAttribs, thisFuzzy, thisExact;

describe("DSLUtil", () => {
  describe("#reduceAstFilters", () => {
    it("is called for every filter in the tree", () => {
      const ast = new DSLExpression('foo bar (is:attribute "exact")').ast;
      const handler = jest.fn();

      DSLUtil.reduceAstFilters(ast, handler);

      const texts = handler.mock.calls.map((call) => call[1].filterParams.text);

      expect(texts).toEqual(["foo", "bar", "attribute", "exact"]);
    });

    it("returns and process memo", () => {
      const ast = new DSLExpression('foo bar (is:attribute "exact")').ast;
      const texts = DSLUtil.reduceAstFilters(
        ast,
        (memo, filter) => memo.concat(filter.filterParams.text),
        []
      );

      expect(texts).toEqual(["foo", "bar", "attribute", "exact"]);
    });
  });

  describe("#canFormProcessExpression", () => {
    it("returns true if no repeating token and no groups", () => {
      const expr = new DSLExpression('is:foo is:bar foo bar "expr"');

      expect(DSLUtil.canFormProcessExpression(expr)).toBeTruthy();
    });

    it("returns true if repeating token and no group", () => {
      const expr = new DSLExpression('is:foo is:bar foo bar "expr" is:foo');

      expect(DSLUtil.canFormProcessExpression(expr)).toBeTruthy();
    });

    it("returns true if group and no repeating token", () => {
      const expr = new DSLExpression('is:foo is:bar (foo bar "expr")');

      expect(DSLUtil.canFormProcessExpression(expr)).toBeTruthy();
    });

    it("returns false if group and repeating token", () => {
      const expr = new DSLExpression('is:foo is:bar (is:foo bar "expr")');

      expect(DSLUtil.canFormProcessExpression(expr)).toBeFalsy();
    });
  });

  describe("#canProcessParts", () => {
    beforeEach(() => {
      thisParts = {
        attr: DSLExpressionPart.attribute("is", "foo"),
        exact: DSLExpressionPart.exact,
        fuzzy: DSLExpressionPart.fuzzy,
      };
    });

    it("returns true when expression is empty", () => {
      const expression = new DSLExpression();

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeTruthy();
    });

    it("returns true when expression has a single attribute node", () => {
      const expression = new DSLExpression("is:foo");

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeTruthy();
    });

    it("returns false when expression has a repeating attribute node", () => {
      const expression = new DSLExpression("is:foo is:foo");

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeFalsy();
    });

    it("returns true when expression has a single exact node", () => {
      const expression = new DSLExpression('"exact foo"');

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeTruthy();
    });

    it("returns false when expression has a repeating exact node", () => {
      const expression = new DSLExpression('"exact foo" "something else"');

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeFalsy();
    });

    it("returns true when expression has a single fuzzy node", () => {
      const expression = new DSLExpression("foo");

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeTruthy();
    });

    it("returns true when expression has a repeating fuzzy nodes", () => {
      const expression = new DSLExpression("foo foo");

      expect(DSLUtil.canProcessParts(expression, thisParts)).toBeTruthy();
    });
  });

  describe("#findNodesByFilter", () => {
    beforeEach(() => {
      thisAst = new DSLExpression('is:foo bar is:bar is:foo spacebar "foo-bar"')
        .ast;

      // For reference, the parsed AST is visualized like so:
      //
      // AND: [
      //   AND: [
      //     AND: [
      //       AND: [
      //         AND: [
      //           'is:foo',
      //           'bar'
      //         ],
      //         'is:bar'
      //       ],
      //       'is:foo'
      //     ],
      //     'spacebar'
      //   ],
      //   '"foo-bar"'
      // ]

      // console.log(this.ast);

      thisAttribs = [
        thisAst.children[0].children[0].children[0].children[0].children[0],
        thisAst.children[0].children[0].children[0].children[1],
        thisAst.children[0].children[0].children[1],
      ];

      thisFuzzy = [
        thisAst.children[0].children[0].children[0].children[0].children[1],
        thisAst.children[0].children[1],
      ];

      thisExact = [thisAst.children[1]];
    });

    it("returns all occurrences of attribute match", () => {
      const filter = DSLExpressionPart.attribute("is", "foo");

      expect(DSLUtil.findNodesByFilter(thisAst, filter)).toEqual([
        thisAttribs[0],
        thisAttribs[2],
      ]);
    });

    it("returns all occurrences of fuzzy match", () => {
      const filter = DSLExpressionPart.fuzzy;

      expect(DSLUtil.findNodesByFilter(thisAst, filter)).toEqual(thisFuzzy);
    });

    it("returns all occurrences of exact match", () => {
      const filter = DSLExpressionPart.exact;

      expect(DSLUtil.findNodesByFilter(thisAst, filter)).toEqual(thisExact);
    });
  });

  describe("#getPartValues", () => {
    beforeEach(() => {
      thisParts = {
        attr: DSLExpressionPart.attribute("is", "foo"),
        exact: DSLExpressionPart.exact,
        fuzzy: DSLExpressionPart.fuzzy,
      };
    });

    it("sets `true` on existing attributes", () => {
      const expression = new DSLExpression("is:foo");

      expect(DSLUtil.getPartValues(expression, thisParts)).toEqual({
        attr: true,
        exact: null,
        fuzzy: null,
      });
    });

    it("sets the string value of exact matches", () => {
      const expression = new DSLExpression('"this is a test"');

      expect(DSLUtil.getPartValues(expression, thisParts)).toEqual({
        attr: false,
        exact: "this is a test",
        fuzzy: null,
      });
    });

    it("sets the string value of fuzzy matches", () => {
      const expression = new DSLExpression("foo bar token");

      expect(DSLUtil.getPartValues(expression, thisParts)).toEqual({
        attr: false,
        exact: null,
        fuzzy: "foo bar token",
      });
    });

    it("handles more than one property in expression", () => {
      const expression = new DSLExpression('foo "exact" is:foo bar token');

      expect(DSLUtil.getPartValues(expression, thisParts)).toEqual({
        attr: true,
        exact: "exact",
        fuzzy: "foo bar token",
      });
    });
  });

  describe("#getNodeString", () => {
    it("returns the string of attribute nodes", () => {
      const node = new DSLASTNodes.FilterNode(0, 0, DSLFilterTypes.ATTRIB, {
        label: "label",
        text: "text",
      });

      expect(DSLUtil.getNodeString(node)).toEqual("label:text");
    });

    it("returns the string of fuzzy nodes", () => {
      const node = new DSLASTNodes.FilterNode(0, 0, DSLFilterTypes.FUZZY, {
        text: "text",
      });

      expect(DSLUtil.getNodeString(node)).toEqual("text");
    });

    it("returns the string of exact nodes", () => {
      const node = new DSLASTNodes.FilterNode(0, 0, DSLFilterTypes.EXACT, {
        text: "text",
      });

      expect(DSLUtil.getNodeString(node)).toEqual('"text"');
    });
  });
});


text:
/* <DESC>
 * multi socket API usage with libevent 2
 * </DESC>
 */
/* Example application source code using the multi socket interface to
   download many files at once.

Written by Jeff Pohlmeyer

Requires libevent version 2 and a (POSIX?) system that has mkfifo().

This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c"
sample programs.

When running, the program creates the named pipe "hiper.fifo"

Whenever there is input into the fifo, the program reads the input as a list
of URL's and creates some new easy handles to fetch each URL via the
curl_multi "hiper" API.

Thus, you can try a single URL:
  % echo http://www.yahoo.com > hiper.fifo

Or a whole bunch of them:
  % cat my-url-list > hiper.fifo

The fifo buffer is handled almost instantly, so you can even add more URL's
while the previous requests are still being downloaded.

Note:
  For the sake of simplicity, URL length is limited to 1023 char's !

This is purely a demo app, all retrieved data is simply discarded by the write
callback.

*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <sys/poll.h>
#include <curl/curl.h>
#include <event2/event.h>
#include <event2/event_struct.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/cdefs.h>

#ifdef __GNUC__
#define _Unused __attribute__((unused))
#else
#define _Unused
#endif

#define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */

/* Global information, common to all connections */
typedef struct _GlobalInfo
{
  struct event_base *evbase;
  struct event fifo_event;
  struct event timer_event;
  CURLM *multi;
  int still_running;
  FILE *input;
  int stopped;
} GlobalInfo;

/* Information associated with a specific easy handle */
typedef struct _ConnInfo
{
  CURL *easy;
  char *url;
  GlobalInfo *global;
  char error[CURL_ERROR_SIZE];
} ConnInfo;

/* Information associated with a specific socket */
typedef struct _SockInfo
{
  curl_socket_t sockfd;
  CURL *easy;
  int action;
  long timeout;
  struct event ev;
  GlobalInfo *global;
} SockInfo;

#define __case(code) \
  case code: s = __STRING(code)

/* Die if we get a bad CURLMcode somewhere */
static void mcode_or_die(const char *where, CURLMcode code)
{
  if(CURLM_OK != code) {
    const char *s;
    switch(code) {
      __case(CURLM_BAD_HANDLE); break;
      __case(CURLM_BAD_EASY_HANDLE); break;
      __case(CURLM_OUT_OF_MEMORY); break;
      __case(CURLM_INTERNAL_ERROR); break;
      __case(CURLM_UNKNOWN_OPTION); break;
      __case(CURLM_LAST); break;
      default: s = "CURLM_unknown"; break;
      __case(CURLM_BAD_SOCKET);
      fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
      /* ignore this error */
      return;
    }
    fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
    exit(code);
  }
}

/* Update the event timer after curl_multi library calls */
static int multi_timer_cb(CURLM *multi _Unused, long timeout_ms, GlobalInfo *g)
{
  struct timeval timeout;

  timeout.tv_sec = timeout_ms/1000;
  timeout.tv_usec = (timeout_ms%1000)*1000;
  fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);

  /*
   * if timeout_ms is -1, just delete the timer
   *
   * For all other values of timeout_ms, this should set or *update* the timer
   * to the new value
   */
  if(timeout_ms == -1)
    evtimer_del(&g->timer_event);
  else /* includes timeout zero */
    evtimer_add(&g->timer_event, &timeout);
  return 0;
}

/* Check for completed transfers, and remove their easy handles */
static void check_multi_info(GlobalInfo *g)
{
  char *eff_url;
  CURLMsg *msg;
  int msgs_left;
  ConnInfo *conn;
  CURL *easy;
  CURLcode res;

  fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running);
  while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
    if(msg->msg == CURLMSG_DONE) {
      easy = msg->easy_handle;
      res = msg->data.result;
      curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
      curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
      fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error);
      curl_multi_remove_handle(g->multi, easy);
      free(conn->url);
      curl_easy_cleanup(easy);
      free(conn);
    }
  }
  if(g->still_running == 0 && g->stopped)
    event_base_loopbreak(g->evbase);
}

/* Called by libevent when we get action on a multi socket */
static void event_cb(int fd, short kind, void *userp)
{
  GlobalInfo *g = (GlobalInfo*) userp;
  CURLMcode rc;

  int action =
    ((kind & EV_READ) ? CURL_CSELECT_IN : 0) |
    ((kind & EV_WRITE) ? CURL_CSELECT_OUT : 0);

  rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
  mcode_or_die("event_cb: curl_multi_socket_action", rc);

  check_multi_info(g);
  if(g->still_running <= 0) {
    fprintf(MSG_OUT, "last transfer done, kill timeout\n");
    if(evtimer_pending(&g->timer_event, NULL)) {
      evtimer_del(&g->timer_event);
    }
  }
}

/* Called by libevent when our timeout expires */
static void timer_cb(int fd _Unused, short kind _Unused, void *userp)
{
  GlobalInfo *g = (GlobalInfo *)userp;
  CURLMcode rc;

  rc = curl_multi_socket_action(g->multi,
                                  CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  mcode_or_die("timer_cb: curl_multi_socket_action", rc);
  check_multi_info(g);
}

/* Clean up the SockInfo structure */
static void remsock(SockInfo *f)
{
  if(f) {
    event_del(&f->ev);
    free(f);
  }
}

/* Assign information to a SockInfo structure */
static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
                    GlobalInfo *g)
{
  int kind =
     ((act & CURL_POLL_IN) ? EV_READ : 0) |
     ((act & CURL_POLL_OUT) ? EV_WRITE : 0) | EV_PERSIST;

  f->sockfd = s;
  f->action = act;
  f->easy = e;
  event_del(&f->ev);
  event_assign(&f->ev, g->evbase, f->sockfd, kind, event_cb, g);
  event_add(&f->ev, NULL);
}

/* Initialize a new SockInfo structure */
static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
{
  SockInfo *fdp = calloc(sizeof(SockInfo), 1);

  fdp->global = g;
  setsock(fdp, s, easy, action, g);
  curl_multi_assign(g->multi, s, fdp);
}

/* CURLMOPT_SOCKETFUNCTION */
static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
{
  GlobalInfo *g = (GlobalInfo*) cbp;
  SockInfo *fdp = (SockInfo*) sockp;
  const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };

  fprintf(MSG_OUT,
          "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  if(what == CURL_POLL_REMOVE) {
    fprintf(MSG_OUT, "\n");
    remsock(fdp);
  }
  else {
    if(!fdp) {
      fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
      addsock(s, e, what, g);
    }
    else {
      fprintf(MSG_OUT,
              "Changing action from %s to %s\n",
              whatstr[fdp->action], whatstr[what]);
      setsock(fdp, s, e, what, g);
    }
  }
  return 0;
}

/* CURLOPT_WRITEFUNCTION */
static size_t write_cb(void *ptr _Unused, size_t size, size_t nmemb,
                       void *data)
{
  size_t realsize = size * nmemb;
  (void)_Unused;
  (void)data;

  return realsize;
}

/* CURLOPT_PROGRESSFUNCTION */
static int prog_cb(void *p, double dltotal, double dlnow, double ult _Unused,
                   double uln _Unused)
{
  ConnInfo *conn = (ConnInfo *)p;

  fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  return 0;
}

/* Create a new easy handle, and add it to the global curl_multi */
static void new_conn(char *url, GlobalInfo *g)
{
  ConnInfo *conn;
  CURLMcode rc;

  conn = calloc(1, sizeof(ConnInfo));
  conn->error[0]='\0';

  conn->easy = curl_easy_init();
  if(!conn->easy) {
    fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
    exit(2);
  }
  conn->global = g;
  conn->url = strdup(url);
  curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
  curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
  curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  fprintf(MSG_OUT,
          "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  rc = curl_multi_add_handle(g->multi, conn->easy);
  mcode_or_die("new_conn: curl_multi_add_handle", rc);

  /* note that the add_handle() will set a time-out to trigger very soon so
     that the necessary socket_action() call will be called by this app */
}

/* This gets called whenever data is received from the fifo */
static void fifo_cb(int fd _Unused, short event _Unused, void *arg)
{
  char s[1024];
  long int rv = 0;
  int n = 0;
  GlobalInfo *g = (GlobalInfo *)arg;

  do {
    s[0]='\0';
    rv = fscanf(g->input, "%1023s%n", s, &n);
    s[n]='\0';
    if(n && s[0]) {
      if(!strcmp(s, "stop")) {
        g->stopped = 1;
        if(g->still_running == 0)
          event_base_loopbreak(g->evbase);
      }
      else
        new_conn(s, arg);  /* if we read a URL, go get it! */
    }
    else
      break;
  } while(rv != EOF);
}

/* Create a named pipe and tell libevent to monitor it */
static const char *fifo = "hiper.fifo";
static int init_fifo(GlobalInfo *g)
{
  struct stat st;
  curl_socket_t sockfd;

  fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
  if(lstat (fifo, &st) == 0) {
    if((st.st_mode & S_IFMT) == S_IFREG) {
      errno = EEXIST;
      perror("lstat");
      exit(1);
    }
  }
  unlink(fifo);
  if(mkfifo (fifo, 0600) == -1) {
    perror("mkfifo");
    exit(1);
  }
  sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
  if(sockfd == -1) {
    perror("open");
    exit(1);
  }
  g->input = fdopen(sockfd, "r");

  fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
  event_assign(&g->fifo_event, g->evbase, sockfd, EV_READ|EV_PERSIST,
               fifo_cb, g);
  event_add(&g->fifo_event, NULL);
  return (0);
}

static void clean_fifo(GlobalInfo *g)
{
    event_del(&g->fifo_event);
    fclose(g->input);
    unlink(fifo);
}

int main(int argc _Unused, char **argv _Unused)
{
  GlobalInfo g;

  memset(&g, 0, sizeof(GlobalInfo));
  g.evbase = event_base_new();
  init_fifo(&g);
  g.multi = curl_multi_init();
  evtimer_assign(&g.timer_event, g.evbase, timer_cb, &g);

  /* setup the generic multi interface options we want */
  curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
  curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);

  /* we don't call any curl_multi_socket*() function yet as we have no handles
     added! */

  event_base_dispatch(g.evbase);

  /* this, of course, won't get called since only way to stop this program is
     via ctrl-C, but it is here to show how cleanup /would/ be done. */
  clean_fifo(&g);
  event_del(&g.timer_event);
  event_base_free(g.evbase);
  curl_multi_cleanup(g.multi);
  return 0;
}


text:
using OpenQA.Selenium;
using OpenQA.Selenite.Implementation;
using OpenQA.Selenite.Setup;

namespace OpenQA.Selenite.Examples.Nirvana
{
    public class LoggedInPage : WebBlock
    {
        public LoggedInPage(Session session)
            : base(session)
        {
            Wait.Until(driver => driver.FindElement(By.Id("north")));
            Tag = Session.Driver.FindElement(By.TagName("body"));
        }

        public ToolBar ToolBar => new ToolBar(Session);

        public SideBar SideBar => new SideBar(Session);

        public MainArea MainArea => new MainArea(Session);
    }
}


text:
package couchdb

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	"github.com/flimzy/kivik"
	"github.com/flimzy/kivik/driver"
	"github.com/flimzy/kivik/driver/couchdb/chttp"
	"github.com/flimzy/kivik/errors"
)

type bulkResults struct {
	body io.ReadCloser
	dec  *json.Decoder
}

var _ driver.BulkResults = &bulkResults{}

func (r *bulkResults) Next(update *driver.BulkResult) error {
	if !r.dec.More() {
		if err := consumeDelim(r.dec, json.Delim(']')); err != nil {
			return err
		}
		return io.EOF
	}
	var updateResult struct {
		ID     string `json:"id"`
		Rev    string `json:"rev"`
		Error  string `json:"error"`
		Reason string `json:"reason"`
	}
	err := r.dec.Decode(&updateResult)
	if err != nil {
		return err
	}
	update.ID = updateResult.ID
	update.Rev = updateResult.Rev
	update.Error = nil
	if updateResult.Error != "" {
		var status int
		switch updateResult.Error {
		case "conflict":
			status = kivik.StatusConflict
		case "not_implemented":
			status = kivik.StatusNotImplemented
		default:
			fmt.Printf("Unknown error %s / %s \n", updateResult.Error, updateResult.Reason)
		}
		update.Error = errors.Status(status, updateResult.Reason)
	}
	return nil
}

func (r *bulkResults) Close() error {
	return r.body.Close()
}

func (d *db) BulkDocs(ctx context.Context, docs []interface{}) (driver.BulkResults, error) {
	var cancel context.CancelFunc
	ctx, cancel = context.WithCancel(ctx)
	defer cancel()
	body, errFunc := chttp.EncodeBody(map[string]interface{}{"docs": docs}, cancel)
	opts := &chttp.Options{
		Body:        body,
		ForceCommit: d.forceCommit,
	}
	resp, err := d.Client.DoReq(ctx, kivik.MethodPost, d.path("_bulk_docs", nil), opts)
	if jsonErr := errFunc(); jsonErr != nil {
		if resp.Body != nil {
			resp.Body.Close()
		}
		return nil, jsonErr
	}
	if err != nil {
		return nil, err
	}
	switch resp.StatusCode {
	case kivik.StatusCreated:
		// Nothing to do
	case kivik.StatusExpectationFailed:
		err = &chttp.HTTPError{
			Code:   kivik.StatusExpectationFailed,
			Reason: "one or more document was rejected",
		}
	default:
		if resp.StatusCode < 400 {
			fmt.Printf("Unexpected BulkDoc response code: %d", resp.StatusCode)
		}
		// All other errors can consume the response body and return immediately
		return nil, chttp.ResponseError(resp)
	}
	dec := json.NewDecoder(resp.Body)
	// Consume the opening '[' char
	if jsonErr := consumeDelim(dec, json.Delim('[')); jsonErr != nil {
		return nil, jsonErr
	}
	return &bulkResults{
		body: resp.Body,
		dec:  dec,
	}, err
}


text:
import { expect } from 'chai';
import Loki from 'lokijs';
import UserManager from '../src/modules/UserManager';

const db = new Loki('test/mock-users.json');
const users = () => db.getCollection('users');

describe('UserManager', () => {
  beforeEach((done) => {
    db.loadDatabase({}, () => {
      done();
    });
  });

  afterEach(() => {
    users().clear();
  });

  describe('#isUserAuthorized', () => {
    it('should return true for valid user', () => {
      users().insert({ username: 'valid_user', role: 'user' });

      const userMananger = new UserManager(users);
      const result = userMananger.isUserAuthorized({ username: 'valid_user' });
      expect(result).to.eq(true);
    });

    it('should return true for valid user without username', () => {
      users().insert({ id: 1385770801, role: 'user' });

      const userMananger = new UserManager(users);
      const result = userMananger.isUserAuthorized({ userId: 1385770801, username: 'valid_user' });
      expect(result).to.eq(true);
    });

    it('should return false for unregistered users', () => {
      const userManager = new UserManager(users);
      const result = userManager.isUserAuthorized({ username: 'unregistered', role: 'not registered' });
      expect(result).to.eq(false);
    });
  });

  describe('#upsertUser', () => {
    it('should add new user as registree', () => {
      const userManager = new UserManager(users);
      const action = userManager.upsertUser({ username: 'sweezharbot', first_name: 'Swee', last_name: 'Zhar Bo', id: 12345 });
      expect(action).to.eq('insert');
      expect(users().data.length).to.eq(1);
      expect(users().findOne(x => x.username === 'sweezharbot').role).to.eq('registree');
    });

    it('should add IDs for old users with blank userId', () => {
      users().insert({ 'username': 'valid_user', userId: '' });

      const userManager = new UserManager(users);
      const action = userManager.upsertUser({ username: 'valid_user', id: 1234567 });
      expect(action).to.eq('update');
      expect(users().findOne({ 'username': 'valid_user' }).userId).to.eq(1234567);
    });

    it('should add IDs for old users with undefined userId', () => {
      users().insert({ 'username': 'valid_user', userId: '' });

      const userManager = new UserManager(users);
      const action = userManager.upsertUser({ username: 'valid_user', id: 1234567 });
      expect(action).to.eq('update');
      expect(users().findOne({ 'username': 'valid_user' }).userId).to.eq(1234567);
    });

    it('should not insert new users', () => {
      users().insert({ 'username': 'valid_user', userId: 1234567 });

      const userManager = new UserManager(users);
      const action = userManager.upsertUser({ 'username': 'valid_user', id: 12345687 });
      expect(action).to.eq('');
      expect(users().data.length).to.eq(1);
    });

    it('should allow users without usernames', () => {
      users().insert({ userId: 12345698 });

      const userManager = new UserManager(users);
      const action = userManager.upsertUser({ id: 1234567 });
      expect(action).to.eq('insert');
      expect(users().data.length).to.eq(2);
      expect(users().find({ 'userId': 12345698 })).to.have.lengthOf(1);
    });
  });

  describe('#getUser', () => {
    beforeEach(() => {
      users().insert({ username: 'swee_zhar_bo1', userId: 1234561 });
      users().insert({ username: 'swee_zhar_bo2', userId: 1234562 });
      users().insert({ username: 'swee_zhar_bo3', userId: 1234563 });
    });

    it('should return user in database', () => {
      const userManager = new UserManager(users);
      const userInDB = userManager.getUser({ username: 'swee_zhar_bo2' });
      expect(userInDB.userId).to.eq(1234562);
    });

    it('should return empty if not in database', () => {
      const userManager = new UserManager(users);
      const userInDB = userManager.getUser({ username: 'bo_zhar_bor' });
      expect(userInDB).to.be.undefined;
    });
  });
});


text:
<?php declare(strict_types=1);

namespace VfacTmdb\Results;

use VfacTmdb\Abstracts\Results;
use VfacTmdb\Interfaces\Results\CastResultsInterface;
use VfacTmdb\Interfaces\TmdbInterface;

/**
 * Class to manipulate a movie or tv show cast result
 * @package Tmdb
 * @author Vincent Faliès <vincent@vfac.fr>
 * @copyright Copyright (c) 2017-2021
 */
class Cast extends Results implements CastResultsInterface
{
    /**
     * Character name
     * @var string
     */
    protected $character = null;
    /**
     * Gender
     * @var int
     */
    protected $gender = null;
    /**
     * Credit Id
     * @var string
     */
    protected $credit_id = null;

    /**
     * Name
     * @var string
     */
    protected $name = null;
    /**
     * Image profile path
     * @var string
     */
    protected $profile_path = null;
    /**
     * Order in cast
     * @var int
     */
    protected $order = null;
    /**
     * Id
     * @var int
     */
    protected $id = null;

    /**
     * Constructor
     * @param TmdbInterface $tmdb
     * @param \stdClass $result
     */
    public function __construct(TmdbInterface $tmdb, \stdClass $result)
    {
        parent::__construct($tmdb, $result);

        $this->id           = $this->data->id;
        $this->character    = $this->data->character;
        $this->gender       = $this->data->gender;
        $this->credit_id    = $this->data->credit_id;
        $this->name         = $this->data->name;
        $this->profile_path = $this->data->profile_path;
        $this->order        = $this->data->order;
    }

    /**
     * Get Id
     * @return int
     */
    public function getId() : int
    {
        return (int) $this->id;
    }

    /**
     * Get credit Id
     * @return string
     */
    public function getCreditId() : string
    {
        return $this->credit_id;
    }

    /**
     * Get character name
     * @return string
     */
    public function getCharacter() : string
    {
        return $this->character;
    }

    /**
     * Get gender
     * @return int
     */
    public function getGender() : int
    {
        return $this->gender;
    }

    /**
     * Get name
     * @return string
     */
    public function getName() : string
    {
        return $this->name;
    }

    /**
     * Get profile path
     * @return string
     */
    public function getProfilePath() : string
    {
        return $this->profile_path;
    }

    /**
     * Get Order
     * @return int
     */
    public function getOrder() : int
    {
        return $this->order;
    }
}


text:
<?php

namespace PXB\Application\Interfaces;

use Interop\Container\ContainerInterface;
use Zend\Expressive\ConfigManager\PhpFileProvider as ConfigLoader;

interface ModuleConfigInterface
{
    /**
     * Returns a configuration container, that contains configurations
     * applicable to this module (templates, routes, dependencies, etc)
     *
     * @param ContainerInterface $container
     * @return ConfigLoader
     */
    public function __invoke(ContainerInterface $container);
}


text:
package com.gentics.mesh.demo;

import static com.gentics.mesh.core.rest.common.Permission.READ;
import static com.gentics.mesh.core.rest.common.Permission.READ_PUBLISHED;
import static com.gentics.mesh.core.rest.common.Permission.UPDATE;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.apache.commons.io.IOUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.gentics.mesh.FieldUtil;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.core.data.user.MeshAuthUser;
import com.gentics.mesh.core.db.Database;
import com.gentics.mesh.core.rest.group.GroupCreateRequest;
import com.gentics.mesh.core.rest.group.GroupListResponse;
import com.gentics.mesh.core.rest.group.GroupResponse;
import com.gentics.mesh.core.rest.node.NodeCreateRequest;
import com.gentics.mesh.core.rest.node.NodeResponse;
import com.gentics.mesh.core.rest.node.NodeUpdateRequest;
import com.gentics.mesh.core.rest.node.field.BinaryField;
import com.gentics.mesh.core.rest.project.ProjectCreateRequest;
import com.gentics.mesh.core.rest.project.ProjectResponse;
import com.gentics.mesh.core.rest.role.RoleCreateRequest;
import com.gentics.mesh.core.rest.role.RoleListResponse;
import com.gentics.mesh.core.rest.role.RolePermissionRequest;
import com.gentics.mesh.core.rest.role.RoleResponse;
import com.gentics.mesh.core.rest.schema.SchemaListResponse;
import com.gentics.mesh.core.rest.schema.impl.SchemaCreateRequest;
import com.gentics.mesh.core.rest.schema.impl.SchemaReferenceImpl;
import com.gentics.mesh.core.rest.schema.impl.SchemaResponse;
import com.gentics.mesh.core.rest.tag.TagCreateRequest;
import com.gentics.mesh.core.rest.tag.TagFamilyCreateRequest;
import com.gentics.mesh.core.rest.tag.TagFamilyResponse;
import com.gentics.mesh.core.rest.tag.TagResponse;
import com.gentics.mesh.core.rest.user.NodeReference;
import com.gentics.mesh.core.rest.user.UserCreateRequest;
import com.gentics.mesh.core.rest.user.UserListResponse;
import com.gentics.mesh.core.rest.user.UserResponse;
import com.gentics.mesh.error.MeshSchemaException;
import com.gentics.mesh.json.JsonUtil;
import com.gentics.mesh.parameter.impl.PublishParametersImpl;
import com.gentics.mesh.rest.MeshLocalClient;
import com.gentics.mesh.rest.client.MeshRequest;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

/**
 * Central data provider for the Gentics Mesh Demo content.
 *
 * The content is created using the {@link MeshLocalClient}.
 */
@Singleton
public class DemoDataProvider {

	private static final Logger log = LoggerFactory.getLogger(DemoDataProvider.class);

	public static final String PROJECT_NAME = "demo";
	public static final String TAG_CATEGORIES_SCHEMA_NAME = "tagCategories";
	public static final String TAG_DEFAULT_SCHEMA_NAME = "tag";

	private Database db;

	private MeshLocalClient client;

	private Map<String, ProjectResponse> projects = new HashMap<>();
	private Map<String, SchemaResponse> schemas = new HashMap<>();
	private Map<String, TagFamilyResponse> tagFamilies = new HashMap<>();
	private Map<String, NodeResponse> nodes = new HashMap<>();
	private Map<String, TagResponse> tags = new HashMap<>();
	private Map<String, UserResponse> users = new HashMap<>();
	private Map<String, RoleResponse> roles = new HashMap<>();
	private Map<String, GroupResponse> groups = new HashMap<>();

	@Inject
	public DemoDataProvider(Database database, MeshLocalClient client) {
		this.db = database;
		this.client = client;
	}

	/**
	 * Setup the demo content
	 *
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 * @throws MeshSchemaException
	 * @throws InterruptedException
	 */
	public void setup() throws JsonParseException, JsonMappingException, IOException, MeshSchemaException, InterruptedException {
		MeshAuthUser user = db.tx(tx -> {
			return tx.userDao().findMeshAuthUserByUsername("admin");
		});
		client.setUser(user);

		addBootstrappedData();

		addRoles();
		addGroups();
		addUsers();

		addProjects();
		addTagFamilies();
		addTags();

		addSchemaContainers();
		addNodes();
		// updatePermissions();
		publishAllNodes();
		addWebclientPermissions();
		addAnonymousPermissions();

		log.info("Demo data setup completed");
	}

	/**
	 * Publish the basenodes for each project we created.
	 *
	 * @throws InterruptedException
	 */
	private void publishAllNodes() throws InterruptedException {
		for (ProjectResponse project : projects.values()) {
			call(() -> client.publishNode(PROJECT_NAME, project.getRootNode().getUuid(), new PublishParametersImpl().setRecursive(true)));
		}
	}

	/**
	 * Add the anonymous read permissions
	 */
	private void addAnonymousPermissions() {
		RolePermissionRequest request = new RolePermissionRequest();
		request.setRecursive(true);
		request.getPermissions().add(READ);
		request.getPermissions().add(READ_PUBLISHED);
		call(() -> client.updateRolePermissions(getRole("anonymous").getUuid(), "projects/" + getProject("demo").getUuid(), request));
		call(() -> client.updateRolePermissions(getRole("anonymous").getUuid(), "users/" + users.get("anonymous").getUuid(), request));
	}

	/**
	 * Add the webclient role permissions.
	 *
	 * @throws InterruptedException
	 */
	private void addWebclientPermissions() throws InterruptedException {
		RolePermissionRequest request = new RolePermissionRequest();
		request.setRecursive(true);
		request.getPermissions().add(READ);
		request.getPermissions().add(UPDATE);
		call(() -> client.updateRolePermissions(getRole("Client Role").getUuid(), "projects/" + getProject("demo").getUuid(), request));
		call(() -> client.updateRolePermissions(getRole("Client Role").getUuid(), "users/" + users.get("webclient").getUuid(), request));
	}

	/**
	 * Load users JSON file and create users.
	 *
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void addUsers() throws IOException, InterruptedException {
		JsonObject usersJson = loadJson("users");
		JsonArray dataArray = usersJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject userJson = dataArray.getJsonObject(i);
			String uuid = userJson.getString("uuid");
			String email = userJson.getString("email");
			String username = userJson.getString("username");
			String firstname = userJson.getString("firstName");
			String lastname = userJson.getString("lastName");
			String password = userJson.getString("password");

			log.info("Creating user {" + username + "}");

			UserCreateRequest request = new UserCreateRequest();
			request.setUsername(username);
			request.setEmailAddress(email);
			request.setFirstname(firstname);
			request.setLastname(lastname);
			request.setPassword(password);
			UserResponse response = call(() -> client.createUser(uuid, request));
			users.put(username, response);

			JsonArray groupArray = userJson.getJsonArray("groups");
			for (int e = 0; e < groupArray.size(); e++) {
				String groupUuid = groups.get(groupArray.getString(e)).getUuid();
				call(() -> client.addUserToGroup(groupUuid, response.getUuid()));
			}
		}

	}

	/**
	 * Add groups from JSON file to graph.
	 *
	 * @throws InterruptedException
	 * @throws IOException
	 * @throws Throwable
	 */
	private void addGroups() throws InterruptedException, IOException {
		JsonObject groupsJson = loadJson("groups");
		JsonArray dataArray = groupsJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject groupJson = dataArray.getJsonObject(i);
			String name = groupJson.getString("name");
			String uuid = groupJson.getString("uuid");

			log.info("Creating group {" + name + "}");
			GroupCreateRequest groupCreateRequest = new GroupCreateRequest();
			groupCreateRequest.setName(name);
			GroupResponse group = call(() -> client.createGroup(uuid, groupCreateRequest));
			groups.put(name, group);

			JsonArray rolesNode = groupJson.getJsonArray("roles");
			for (int e = 0; e < rolesNode.size(); e++) {
				final int r = e;
				call(() -> client.addRoleToGroup(group.getUuid(), getRole(rolesNode.getString(r)).getUuid()));
			}
		}
	}

	/**
	 * Load roles JSON file and add those roles to the graph.
	 *
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void addRoles() throws IOException, InterruptedException {
		JsonObject rolesJson = loadJson("roles");
		JsonArray dataArray = rolesJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject roleJson = dataArray.getJsonObject(i);
			String name = roleJson.getString("name");
			String uuid = roleJson.getString("uuid");

			log.info("Creating role {" + name + "}");
			RoleCreateRequest request = new RoleCreateRequest();
			request.setName(name);
			RoleResponse role = call(() -> client.createRole(uuid, request));
			roles.put(name, role);
		}
	}

	/**
	 * Add data to the internal maps which was created within the {@link BootstrapInitializer} (e.g.: admin groups, roles, users)
	 *
	 * @throws InterruptedException
	 * @throws IOException
	 */
	private void addBootstrappedData() throws InterruptedException, IOException {
		GroupListResponse groupsResponse = client.findGroups().blockingGet();
		for (GroupResponse group : groupsResponse.getData()) {
			groups.put(group.getName(), group);
		}

		UserListResponse usersResponse = client.findUsers().blockingGet();
		for (UserResponse user : usersResponse.getData()) {
			users.put(user.getUsername(), user);
		}

		RoleListResponse rolesResponse = client.findRoles().blockingGet();
		for (RoleResponse role : rolesResponse.getData()) {
			roles.put(role.getName(), role);
		}

		SchemaListResponse schemasResponse = client.findSchemas().blockingGet();
		for (SchemaResponse schema : schemasResponse.getData()) {
			schemas.put(schema.getName(), schema);
		}
	}

	/**
	 * Load nodes JSON file and add those nodes to the graph.
	 *
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void addNodes() throws IOException, InterruptedException {
		JsonObject nodesJson = loadJson("nodes");
		JsonArray dataArray = nodesJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject nodeJson = dataArray.getJsonObject(i);
			String uuid = nodeJson.getString("uuid");
			ProjectResponse project = getProject(nodeJson.getString("project"));
			String schemaName = nodeJson.getString("schema");
			String parentNodeName = nodeJson.getString("parent");
			String segmentFieldValue = nodeJson.getString("segmentFieldValue");
			String name = nodeJson.getString("name");
			SchemaResponse schema = getSchemaModel(schemaName);
			NodeResponse parentNode = (nodeJson.getString("project") + ".basenode").equals(parentNodeName) ? null : getNode(parentNodeName);

			log.info("Creating node {" + name + "} for schema {" + schemaName + "}");
			NodeCreateRequest nodeCreateRequest = new NodeCreateRequest();
			nodeCreateRequest.setLanguage("en");
			if (parentNode != null) {
				nodeCreateRequest.setParentNode(new NodeReference().setUuid(parentNode.getUuid()));
			} else {
				nodeCreateRequest.setParentNode(project.getRootNode());
			}
			nodeCreateRequest.setSchema(new SchemaReferenceImpl().setUuid(schema.getUuid()));
			nodeCreateRequest.getFields().put("name", FieldUtil.createStringField(name));

			// Add the segment field value
			switch (schemaName) {
			case "category":
			case "folder":
			case "vehicle":
				nodeCreateRequest.getFields().put("slug", FieldUtil.createStringField(segmentFieldValue));
				break;
			}

			JsonObject fieldsObject = nodeJson.getJsonObject("fields");
			if (fieldsObject != null) {
				for (String fieldName : fieldsObject.fieldNames()) {
					Object obj = fieldsObject.getValue(fieldName);
					if ("vehicleImage".equals(fieldName)) {
						nodeCreateRequest.getFields().put(fieldName, FieldUtil.createNodeField(getNode((String) obj).getUuid()));
						continue;
					}
					if ("description".equals(fieldName)) {
						nodeCreateRequest.getFields().put(fieldName, FieldUtil.createHtmlField(String.valueOf(obj)));
						continue;
					}
					if (obj instanceof Integer || obj instanceof Float || obj instanceof Double) {
						nodeCreateRequest.getFields().put(fieldName,
							FieldUtil.createNumberField(com.gentics.mesh.util.NumberUtils.createNumber(obj.toString())));
					} else if (obj instanceof String) {
						nodeCreateRequest.getFields().put(fieldName, FieldUtil.createStringField((String) obj));
					} else {
						throw new RuntimeException("Demo data type {" + obj.getClass().getName() + "} for field {" + fieldName + "} is unknown.");
					}
				}
			}
			NodeResponse createdNode = call(() -> client.createNode(uuid, project.getName(), nodeCreateRequest));
			System.out.println("UUID: " + uuid + " - " + createdNode.getUuid());

			// Upload binary data
			JsonObject binNode = nodeJson.getJsonObject("bin");
			if (binNode != null) {
				String path = binNode.getString("path");
				String filenName = binNode.getString("filename");
				String contentType = binNode.getString("contentType");
				InputStream ins = getClass().getResourceAsStream("/data/" + path);
				if (ins == null) {
					throw new NullPointerException("Could not find binary file within path {" + path + "}");
				}
				byte[] bytes = IOUtils.toByteArray(ins);
				Buffer fileData = Buffer.buffer(bytes);

				NodeResponse resp = call(
					() -> client.updateNodeBinaryField(PROJECT_NAME, createdNode.getUuid(), "en", createdNode.getVersion().toString(), "image",
						fileData.getBytes(), filenName, contentType));

				Float fpx = binNode.getFloat("fpx");
				Float fpy = binNode.getFloat("fpy");
				if (fpx != null && fpy != null) {
					NodeUpdateRequest update = resp.toRequest();
					BinaryField image = update.getFields().getBinaryField("image");
					image.setFocalPoint(fpx, fpy);
					update.getFields().put("image", image);
					call(() -> client.updateNode(PROJECT_NAME, createdNode.getUuid(), update));
				}
			}

			// Add tags to node
			JsonArray tagArray = nodeJson.getJsonArray("tags");
			for (int e = 0; e < tagArray.size(); e++) {
				String tagName = tagArray.getString(e);
				call(() -> client.addTagToNode(PROJECT_NAME, createdNode.getUuid(), getTag(tagName).getUuid()));
			}

			nodes.put(name, createdNode);
		}

	}

	/**
	 * Load tags JSON and add those tags to the graph.
	 *
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void addTags() throws IOException, InterruptedException {
		JsonObject tagsJson = loadJson("tags");
		JsonArray dataArray = tagsJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject tagJson = dataArray.getJsonObject(i);
			String name = tagJson.getString("name");
			String uuid = tagJson.getString("uuid");
			String tagFamilyName = tagJson.getString("tagFamily");

			log.info("Creating tag {" + name + "} to family {" + tagFamilyName + "}");
			TagFamilyResponse tagFamily = getTagFamily(tagFamilyName);
			// TODO determine project of tag family automatically or use json field to assign it
			TagCreateRequest createRequest = new TagCreateRequest();
			createRequest.setName(name);
			TagResponse result = call(() -> client.createTag(PROJECT_NAME, tagFamily.getUuid(), uuid, createRequest));
			tags.put(name, result);
		}
	}

	/**
	 * Load project JSON file and add those projects to the graph.
	 *
	 * @throws IOException
	 * @throws InterruptedException
	 */
	private void addProjects() throws IOException, InterruptedException {
		JsonObject projectsJson = loadJson("projects");
		JsonArray dataArray = projectsJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject projectJson = dataArray.getJsonObject(i);
			String name = projectJson.getString("name");
			String uuid = projectJson.getString("uuid");

			log.info("Creating project {" + name + "}");
			ProjectCreateRequest request = new ProjectCreateRequest();
			request.setSchema(new SchemaReferenceImpl().setName("folder"));
			request.setName(name);
			ProjectResponse project = call(() -> client.createProject(uuid, request));
			projects.put(name, project);
		}
	}

	private void addTagFamilies() throws IOException, InterruptedException {
		JsonObject tagfamilyJson = loadJson("tagfamilies");
		JsonArray dataArray = tagfamilyJson.getJsonArray("data");
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject tagFamilyJson = dataArray.getJsonObject(i);
			String uuid = tagFamilyJson.getString("uuid");
			String name = tagFamilyJson.getString("name");
			String projectName = tagFamilyJson.getString("project");

			log.info("Creating tagfamily {" + name + "} for project {" + projectName + "}");
			TagFamilyCreateRequest request = new TagFamilyCreateRequest();
			request.setName(name);
			TagFamilyResponse result = call(() -> client.createTagFamily(PROJECT_NAME, uuid, request));
			tagFamilies.put(name, result);
		}
	}

	private void addSchemaContainers() throws MeshSchemaException, IOException, InterruptedException {

		JsonObject schemasJson = loadJson("schemas");
		JsonArray dataArray = schemasJson.getJsonArray("data");
		// Create new schemas
		for (int i = 0; i < dataArray.size(); i++) {
			JsonObject schemaJson = dataArray.getJsonObject(i);
			String schemaName = schemaJson.getString("name");
			String uuid = schemaJson.getString("uuid");
			StringWriter writer = new StringWriter();
			InputStream ins = getClass().getResourceAsStream("/data/schemas/" + schemaName + ".json");
			if (ins != null) {
				IOUtils.copy(ins, writer, StandardCharsets.UTF_8.name());
				SchemaCreateRequest schema = JsonUtil.readValue(writer.toString(), SchemaCreateRequest.class);
				SchemaResponse schemaResponse = call(() -> client.createSchema(uuid, schema));
				schemas.put(schemaName, schemaResponse);
			}

			// Assign all schemas to all projects
			JsonArray projectsArray = schemaJson.getJsonArray("projects");
			for (int e = 0; e < projectsArray.size(); e++) {
				String projectName = projectsArray.getString(e);
				ProjectResponse project = getProject(projectName);
				for (SchemaResponse schema : schemas.values()) {
					call(() -> client.assignSchemaToProject(project.getName(), schema.getUuid()));
				}
			}

		}
	}

	protected <T> T call(ClientHandler<T> handler) {
		try {
			return handler.handle().blockingGet();
		} catch (Exception e) {
			throw new RuntimeException("Error while handling request.", e);
		}
	}

	private JsonObject loadJson(String name) throws IOException {
		StringWriter writer = new StringWriter();
		IOUtils.copy(getClass().getResourceAsStream("/data/" + name + ".json"), writer, StandardCharsets.UTF_8.name());
		return new JsonObject(writer.toString());
	}

	private TagFamilyResponse getTagFamily(String name) {
		TagFamilyResponse tagfamily = tagFamilies.get(name);
		Objects.requireNonNull(tagfamily, "Tagfamily with name {" + name + "} could not be found.");
		return tagfamily;
	}

	private TagResponse getTag(String name) {
		TagResponse tag = tags.get(name);
		Objects.requireNonNull(tag, "Tag with name {" + name + "} could not be found.");
		return tag;
	}

	private SchemaResponse getSchemaModel(String name) {
		SchemaResponse model = schemas.get(name);
		Objects.requireNonNull(model, "Schema container with name {" + name + "} could not be found.");
		return model;
	}

	private ProjectResponse getProject(String name) {
		ProjectResponse project = projects.get(name);
		Objects.requireNonNull(project, "Project {" + name + "} could not be found.");
		return project;
	}

	private RoleResponse getRole(String name) {
		RoleResponse role = roles.get(name);
		Objects.requireNonNull(role, "Role with name {" + name + "} could not be found.");
		return role;
	}

	private NodeResponse getNode(String name) {
		NodeResponse node = nodes.get(name);
		Objects.requireNonNull(node, "Node with name {" + name + "} could not be found.");
		return node;
	}

	@FunctionalInterface
	protected static interface ClientHandler<T> {
		MeshRequest<T> handle() throws Exception;
	}

}


text:
package com.deswaef.spring.examples.reactor.model;

/**
 * User: Quinten
 * Date: 6-9-2014
 * Time: 01:39
 *
 * @author Quinten De Swaef
 */
public enum LogCategory {
    DEBUG, ERROR, INFO
}


text:
> Create various text style inputs such as: `text`, `password`, `number`, `url`,
`search`, and more. Also supports creating `textarea` controls.

**Example:**
```html
<template>
  <div>
    <h5>Text input with formatter</h5>
    <b-form-input v-model="text1"
                  type="text"
                  placeholder="Enter your name"
                  :formatter="format"
    ></b-form-input>
    <small class="text-muted">We will convert your name to lowercase instantly</small>
    <p>Value: {{ text1 }}</p>

    <h5>Text input with lazy formatter (on blur)</h5>
    <b-form-input v-model="text2"
                  type="text"
                  placeholder="Enter your name"
                  :formatter="format"
                  lazy-formatter
    ></b-form-input>
    <small class="text-muted">This one is a little lazy!</small>
    <p>Value: {{ text2 }}</p>

    <h5>Textarea with auto row height</h5>
    <b-form-input textarea v-model="text3" placeholder="Text area mode"></b-form-input>
    <p>Value: </p>
    <pre>{{ text3 }}</pre>
  </div>
</template>

<script>
export default {
  data: {
    text1: '',
    text2: '',
    text3: ''
  },
  methods: {
    format(value, el) {
      return value.toLowerCase();
    }
  }
}
</script>

<!-- form-input-1.vue -->
```

### Input type
`<b-form-input>` defaults to a `text` input, but you can set it to any other text-like
type, such as `password`, `number`, `url`, etc, by setting the `type` prop to the
appropriate value.

#### Textarea mode
Render a `<textarea>` element by setting the `textarea` prop to `true` or by
setting the `type` prop to `textarea`.

By default the `<textarea>` will automatically size its height based on on the number
lines of text (separated by newlines) it contains. You can override this behaviour
by supplying a numeric value to the `rows` prop. The `rows` prop has no effect
on other input types.

### Formatter
`<b-form-input>` optionally supports formatting by passing a function reference to
the `formatter` prop.

By default, formatting occurs when the control's native `input` event fires. You can
use the boolean prop `lazy-formatter` to restrict the formatter function to being
called on the control's native `change` event (which usually occurs on blur).

The `formatter` function receives two arguments (the raw value of the input, and
a reference to the input element) and should return the formatted value (as a string).

No formatting occurs if a `formatter` is not provided.

### Static Control
Easily convert a `<b-form-input>` control to a Bootstrap static form
control by setting the prop `static` to true.

You can also use the `<b-form-input-static>` component to create static form controls.

### Control sizing
Set heights using the `size` prop to `sm` or `lg` for small or large respectively.

To control width, place the input inside standard Bootstrap grid column.

### Contextual States
Bootstrap includes validation styles for danger, warning, and success states
on most form controls.

**Note that these states will not appear unless the `<b-form-input>` is
wrapped in a `<b-form fieldset>` which also has the same `state` value.**

On `<b-form-input>`, these states will add the corresponding **validtion state icon**
at the right of the input. Validation icons are url()s configured via Bootstrap V4's
SaSS variables that are applied to background-image declarations for each state.

Generally speaking, you'll want to use a particular state for specific types of feedback:
- `danger` is great for when there's a blocking or required field. A user must fill in
this field properly to submit the form.
- `warning` works well for input values that are in progress, like password strength, or
soft validation before a user attempts to submit a form.
- `success` is ideal for situations when you have per-field validation throughout a form
and want to encourage a user through the rest of the fields.

To apply one of the contextual state icons on `<b-form-input>`, set the `state` prop
to `danger`, `warning`, or `success`. Remember that you will not see the validation
state icon unless the input is wrapped in a `<b-form-fieldset>` which also
has the **same** `state` applied!

#### Conveying contextual validation state to assistive technologies and colorblind users:
Using these contextual states to denote the state of a form control only provides
a visual, color-based indication, which will not be conveyed to users of assistive
technologies - such as screen readers - or to colorblind users.

Ensure that an alternative indication of state is also provided. For instance, you
could include a hint about state in the form control's `<label>` text itself, or by
providing an additional help text block. Specifically for assistive technologies,
invalid form controls can also be assigned an `aria-invalid="true"` attribute.

### ARIA `aria-invalid` attribute
When `<form-input>` has an invalid contextual state (i.e. `danger`) you may also
want to set the `<b-form-input>` prop `invalid` to `true`, or a string value.

Supported `invalid` values are:
- `false` (default) No errors detected
- `true` The value has failed validation.
- `grammar` A grammatical error has been detected.
- `spelling` A spelling error has been detected.


text:
package github.cesarferreira.jsonify;

import android.util.Log;

import com.google.gson.Gson;

public class JSONify {

    private static final int BUMP = 4;

    public static String from(Object o) {
        return from(o, false, false);
    }

    public static String from(Object o, boolean printFormated) {
        return from(o, printFormated, false);
    }

    public static void print(Object o) {
        from(o, true, true);
    }

    private static String from(Object o, boolean printFormatted, boolean isPrintable) {
        Gson g = new Gson();
        String json = g.toJson(o);

        if (!printFormatted) {
            return json;
        }

        String reconstruction = "";

        int level = 0;

        for (int i = 0; i < json.length(); i++) {
            String current = String.valueOf(json.charAt(i));

            if (current.equals("{") || current.equals("[")) {
                level += BUMP;
                current = current + "\n" + getSpaces(level);
            }

            if (current.equals("}") || current.equals("]")) {
                level -= BUMP;
                current = "\n" + getSpaces(level) + current;
            }

            if (current.equals(",")) {
                current = current + "\n" + getSpaces(level);
            }

            reconstruction += current;
        }

        reconstruction = reconstruction.replace("\":", "\" : ");

        if (isPrintable) {
            String[] a = reconstruction.split("\n");
            for (int i = 0; i < a.length; i++) {
                System.out.println(a[i]);
            }
        }

        return reconstruction;
    }

    private static String getSpaces(int level) {
        String spaces = "";
        for (int i = 1; i < level; i++) {
            spaces += " ";
        }
        return spaces;
    }

}