text:
using System.Collections.Generic;
using NUnit.Framework;
using Vertica.AnalyticsTracker.Messages;

namespace AnalyticsTracker.Tests.Messages
{
	[TestFixture]
	public class VariableTester
	{
		[Test]
		public void RenderMessage_ValueIsString_QuotedValueRendered()
		{
			var subj = new Variable("myvar", "myvalue");
			var renderedMessage = subj.RenderMessage();
			Assert.That(renderedMessage, Is.StringContaining("{'myvar': 'myvalue'}"));
		}

		[Test]
		public void RenderMessage_ValueIsDecimal_ValueRendered()
		{
			var subj = new Variable("myvar", 12.34M);
			var renderedMessage = subj.RenderMessage();
			Assert.That(renderedMessage, Is.StringContaining("{'myvar': 12.34}"));
		}

		[Test]
		public void RenderMessage_ValueIsArray_ArrayRendered()
		{
			var subj = new Variable("myvar", new[] { "val1", "val2" });
			var renderedMessage = subj.RenderMessage();
			Assert.That(renderedMessage, Is.StringContaining("{'myvar': ['val1','val2']}"));
		}

		[Test]
		public void RenderMessage_ValueIsDictionary_ObjectRendered()
		{
			var subj = new Variable("myvar", new Dictionary<string, object> {{"key1", "val1"}});
			var renderedMessage = subj.RenderMessage();
			Assert.That(renderedMessage, Is.StringContaining("{'myvar': {'key1': 'val1'}}"));
		}
	}
}


text:
package br.com.restful.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import br.com.restful.factory.ConnectionFactory;
import br.com.restful.model.Cliente;

/**
 *
 * Classe responsável por conter os metodos do CRUD
 *
 * @author Douglas Costa <douglas.cst90@gmail.com>
 * @since 17/02/2013 01:55:13
 * @version 1.0
 */
public class ClienteDAO extends ConnectionFactory {

	private static ClienteDAO instance;

	/**
	 *
	 * Método responsável por criar uma instancia da classe ClienteDAO (Singleton)
	 *
	 * @return
	 * @author Douglas Costa <douglas.cst90@gmail.com.br>
	 * @since 17/02/2013 02:03:47
	 * @version 1.0
	 */
	public static ClienteDAO getInstance(){
		if(instance == null)
			instance = new ClienteDAO();
		return instance;
	}

	/**
	 *
	 * Método responsável por listar todos os clientes do banco
	 *
	 * @return ArrayList<CLiente> clientes
	 * @author Douglas Costa <douglas.cst90@gmail.com.br>
	 * @since 17/02/2013 02:01:35
	 * @version 1.0
	 */
	public ArrayList<Cliente> listarTodos(){
		Connection conexao = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<Cliente> clientes = null;

		conexao = criarConexao();
		clientes = new ArrayList<Cliente>();
		try {
			pstmt = conexao.prepareStatement("select * from cliente order by nome");
			rs = pstmt.executeQuery();

			while(rs.next()){
				Cliente cliente = new Cliente();

				cliente.setId(rs.getInt("id"));
				cliente.setNome(rs.getString("nome"));
				cliente.setCpf(rs.getString("cpf"));
				cliente.setEndereco(rs.getString("endereco"));

				clientes.add(cliente);
			}

		} catch (Exception e) {
			System.out.println("Erro ao listar todos os clientes: " + e);
			e.printStackTrace();
		} finally {
			fecharConexao(conexao, pstmt, rs);
		}
		return clientes;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home_model extends CI_Model{

  public function __construct()
  {
    parent::__construct();
    //Codeigniter : Write Less Do More
  }

  public function get_query_post($whereIntIdPost = '')
  {
    $query = "";

    if ($whereIntIdPost == '') {
      $query = "SELECT lol_post.*,
      dislikes.`dislike`,
      lol_user.`username`,
      lol_user.`image_profile`,
      comments.`total_comment`,
      SUM(lol_like_post.`response`) as `likes`
      FROM lol_post
      JOIN lol_user
      ON lol_user.`intIdUser` = lol_post.`intIdUser`
      LEFT JOIN lol_like_post
      ON lol_like_post.`intIdPost` = lol_post.`intIdPost`
      LEFT JOIN (
        SELECT
        intIdPost,
        COUNT(response) AS `dislike`
        FROM lol_like_post
        WHERE response = '0'
        GROUP BY intIdPost
      ) dislikes
      ON dislikes.`intIdPost` = lol_post.`intIdPost`
      LEFT JOIN (
        SELECT intIdPost,
        COUNT(intIdPost) AS `total_comment`
        FROM lol_comments
        GROUP BY intIdPost
      ) comments
      ON comments.`intIdPost` = lol_post.`intIdPost`
      GROUP BY lol_post.`intIdPost`
      ORDER BY lol_post.`dtmDate`";

    } else {
      $query = "SELECT
      dislikes.`dislike`,
      SUM(lol_like_post.`response`) as `likes`
      FROM lol_post
      LEFT JOIN lol_like_post
      ON lol_like_post.`intIdPost` = lol_post.`intIdPost`
      LEFT JOIN (
        SELECT
        intIdPost,
        COUNT(response) AS `dislike`
        FROM lol_like_post
        WHERE response = '0'
        GROUP BY intIdPost
      ) dislikes
      ON dislikes.`intIdPost` = lol_post.`intIdPost`
      WHERE lol_post.`intIdPost` = '$whereIntIdPost'
      GROUP BY lol_post.`intIdPost`
      ORDER BY lol_post.`dtmDate` desc";

    }

    return $query;
  }

  public function get_my_post_query()
  {
    $intIdUser = $this->session->userdata['user']['intIdUser'];

    $query = "SELECT lol_post.*,
    dislikes.`dislike`,
    lol_user.`username`,
    lol_user.`image_profile`,
    comments.`total_comment`,
    SUM(lol_like_post.`response`) as `likes`
    FROM lol_post
    JOIN lol_user
    ON lol_user.`intIdUser` = lol_post.`intIdUser`
    LEFT JOIN lol_like_post
    ON lol_like_post.`intIdPost` = lol_post.`intIdPost`
    LEFT JOIN (
      SELECT
      intIdPost,
      COUNT(response) AS `dislike`
      FROM lol_like_post
      WHERE response = '0'
      GROUP BY intIdPost
    ) dislikes
    ON dislikes.`intIdPost` = lol_post.`intIdPost`
    LEFT JOIN (
      SELECT intIdPost,
      COUNT(intIdPost) AS `total_comment`
      FROM lol_comments
      GROUP BY intIdPost
    ) comments
    ON comments.`intIdPost` = lol_post.`intIdPost`
    WHERE lol_post.`intIdUser` = '$intIdUser'
    GROUP BY lol_post.`intIdPost`
    ORDER BY lol_post.`dtmDate` desc";

    return $query;
  }

  public function get_limit_post($my ,$offset , $limit)
  {
    $intIdUser = $this->session->userdata['user']['intIdUser'];
    $where = ($my != '') ? "WHERE lol_post.`intIdUser` = '$intIdUser'" : "" ;
    $query = "SELECT lol_post.*,
    dislikes.`dislike`,
    lol_user.`username`,
    lol_user.`image_profile`,
    comments.`total_comment`,
    SUM(lol_like_post.`response`) as `likes`
    FROM lol_post
    JOIN lol_user
    ON lol_user.`intIdUser` = lol_post.`intIdUser`
    LEFT JOIN lol_like_post
    ON lol_like_post.`intIdPost` = lol_post.`intIdPost`
    LEFT JOIN (
      SELECT
      intIdPost,
      COUNT(response) AS `dislike`
      FROM lol_like_post
      WHERE response = '0'
      GROUP BY intIdPost
    ) dislikes
    ON dislikes.`intIdPost` = lol_post.`intIdPost`
    LEFT JOIN (
      SELECT intIdPost,
      COUNT(intIdPost) AS `total_comment`
      FROM lol_comments
      GROUP BY intIdPost
    ) comments
    ON comments.`intIdPost` = lol_post.`intIdPost`
    $where
    GROUP BY lol_post.`intIdPost`
    ORDER BY lol_post.`dtmDate` desc
    LIMIT $offset, $limit";
    return $query;
  }

}


text:
from vumi.tests.helpers import VumiTestCase

from go.vumitools.tests.helpers import djangotest_imports

with djangotest_imports(globals()):
    from django import forms

    from go.apps.rapidsms.view_definition import (
        EndpointsField, RapidSmsForm, AuthTokensForm, EditRapidSmsView,
        ConversationViewDefinition)

class TestEndpointsField(VumiTestCase):
    def test_clean_none(self):
        f = EndpointsField()
        self.assertEqual(f.clean(None), [])

    def test_clean_empty_string(self):
        f = EndpointsField()
        self.assertEqual(f.clean(""), [])

    def test_clean_invalid_type(self):
        f = EndpointsField()
        self.assertRaises(forms.ValidationError, f.clean, 5)

    def test_clean_one_endpoint(self):
        f = EndpointsField()
        self.assertEqual(f.clean(u"foo"), [u"foo"])

    def test_clean_two_endpoints(self):
        f = EndpointsField()
        self.assertEqual(f.clean(u"foo, bar"), [u"foo", u"bar"])

    def test_clean_invalid_endpoint(self):
        f = EndpointsField()
        self.assertRaises(forms.ValidationError, f.clean, u"foo:bar")

    def test_from_endpoints(self):
        f1 = EndpointsField()
        self.assertEqual(f1.from_endpoints([u"foo", u"bar"]), u"foo,bar")
        self.assertEqual(f1.from_endpoints([]), u"")
        f2 = EndpointsField(separator=u"+")
        self.assertEqual(f2.from_endpoints([u"foo", u"bar"]), u"foo+bar")

class TestRapidSmsForm(VumiTestCase):
    def test_initial_from_config(self):
        initial = RapidSmsForm.initial_from_config({
            "rapidsms_url": "http://www.example.com/",
            "rapidsms_username": "rapid-user",
            "rapidsms_password": "rapid-pass",
            "rapidsms_auth_method": "basic",
            "rapidsms_http_method": "POST",
        })
        self.assertEqual(initial, {
            'rapidsms_url': 'http://www.example.com/',
            'rapidsms_username': 'rapid-user',
            'rapidsms_password': 'rapid-pass',
            'rapidsms_auth_method': 'basic',
            'rapidsms_http_method': 'POST',
            'allowed_endpoints': u'default',
        })

    def test_initial_from_config_with_endpoints(self):
        initial = RapidSmsForm.initial_from_config({
            'allowed_endpoints': ['default', 'extra']
        })
        self.assertEqual(initial, {
            'allowed_endpoints': u'default,extra',
        })

    def test_to_config(self):
        form = RapidSmsForm({
            'rapidsms_url': 'http://www.example.com/',
            'rapidsms_username': 'rapid-user',
            'rapidsms_password': 'rapid-pass',
            'rapidsms_auth_method': 'basic',
            'rapidsms_http_method': 'POST',
            'allowed_endpoints': 'default, extra',
        })
        form.is_valid()
        self.assertEqual(form.errors, {})
        self.assertEqual(form.to_config(), {
            'rapidsms_url': u'http://www.example.com/',
            'rapidsms_username': u'rapid-user',
            'rapidsms_password': u'rapid-pass',
            'rapidsms_auth_method': u'basic',
            'rapidsms_http_method': u'POST',
            'allowed_endpoints': ['default', 'extra'],
        })

class TestAuthTokensForm(VumiTestCase):
    def test_initial_from_config_with_auth_token(self):
        initial = AuthTokensForm.initial_from_config({
            'api_tokens': ["token-1"]
        })
        self.assertEqual(initial, {
            'auth_token': "token-1",
        })

    def test_to_config(self):
        form = AuthTokensForm({
            'auth_token': "token-1",
        })
        form.is_valid()
        self.assertEqual(form.errors, {})
        self.assertEqual(form.to_config(), {
            'api_tokens': ["token-1"]
        })

class TestEditRapidSmsView(VumiTestCase):
    def test_edit_forms(self):
        view = EditRapidSmsView()
        self.assertEqual(view.edit_forms, (
            ('rapidsms', RapidSmsForm),
            ('auth_tokens', AuthTokensForm),
        ))

class TestConversationViewDefinition(VumiTestCase):
    def test_edit_view(self):
        view_def = ConversationViewDefinition(None)
        self.assertEqual(view_def.edit_view, EditRapidSmsView)


text:
require_relative '../support/helpers/test_env'

FactoryBot.define do
  # Project without repository
  #
  # Project does not have bare repository.
  # Use this factory if you don't need repository in tests
  factory :project, class: 'Project' do
    sequence(:name) { |n| "project#{n}" }
    path { name.downcase.gsub(/\s/, '_') }
    # Behaves differently to nil due to cache_has_external_issue_tracker
    has_external_issue_tracker { false }

    # Associations
    namespace
    creator { group ? create(:user) : namespace&.owner }

    transient do
      # Nest Project Feature attributes
      wiki_access_level { ProjectFeature::ENABLED }
      builds_access_level { ProjectFeature::ENABLED }
      snippets_access_level { ProjectFeature::ENABLED }
      issues_access_level { ProjectFeature::ENABLED }
      forking_access_level { ProjectFeature::ENABLED }
      merge_requests_access_level { ProjectFeature::ENABLED }
      repository_access_level { ProjectFeature::ENABLED }
      pages_access_level do
        visibility_level == Gitlab::VisibilityLevel::PUBLIC ? ProjectFeature::ENABLED : ProjectFeature::PRIVATE
      end

      # we can't assign the delegated `#ci_cd_settings` attributes directly, as the
      # `#ci_cd_settings` relation needs to be created first
      group_runners_enabled { nil }
      import_status { nil }
      import_jid { nil }
      import_correlation_id { nil }
      import_last_error { nil }
      forward_deployment_enabled { nil }
    end

    after(:create) do |project, evaluator|
      # Builds and MRs can't have higher visibility level than repository access level.
      builds_access_level = [evaluator.builds_access_level, evaluator.repository_access_level].min
      merge_requests_access_level = [evaluator.merge_requests_access_level, evaluator.repository_access_level].min

      hash = {
        wiki_access_level: evaluator.wiki_access_level,
        builds_access_level: builds_access_level,
        snippets_access_level: evaluator.snippets_access_level,
        issues_access_level: evaluator.issues_access_level,
        forking_access_level: evaluator.forking_access_level,
        merge_requests_access_level: merge_requests_access_level,
        repository_access_level: evaluator.repository_access_level,
        pages_access_level: evaluator.pages_access_level
      }

      project.project_feature.update!(hash)

      # Normally the class Projects::CreateService is used for creating
      # projects, and this class takes care of making sure the owner and current
      # user have access to the project. Our specs don't use said service class,
      # thus we must manually refresh things here.
      unless project.group || project.pending_delete
        project.add_maintainer(project.owner)
      end

      project.group&.refresh_members_authorized_projects

      # assign the delegated `#ci_cd_settings` attributes after create
      project.reload.group_runners_enabled = evaluator.group_runners_enabled unless evaluator.group_runners_enabled.nil?

      if evaluator.import_status
        import_state = project.import_state || project.build_import_state
        import_state.status = evaluator.import_status
        import_state.jid = evaluator.import_jid
        import_state.correlation_id_value = evaluator.import_correlation_id
        import_state.last_error = evaluator.import_last_error
        import_state.save!
      end
    end

    trait :public do
      visibility_level { Gitlab::VisibilityLevel::PUBLIC }
    end

    trait :internal do
      visibility_level { Gitlab::VisibilityLevel::INTERNAL }
    end

    trait :private do
      visibility_level { Gitlab::VisibilityLevel::PRIVATE }
    end

    trait :import_scheduled do
      import_status { :scheduled }
    end

    trait :import_started do
      import_status { :started }
    end

    trait :import_finished do
      import_status { :finished }
    end

    trait :import_failed do
      import_status { :failed }
    end

    trait :archived do
      archived { true }
    end

    trait :last_repository_check_failed do
      last_repository_check_failed { true }
    end

    storage_version { Project::LATEST_STORAGE_VERSION }

    trait :legacy_storage do
      storage_version { nil }
    end

    trait :request_access_disabled do
      request_access_enabled { false }
    end

    trait :with_avatar do
      avatar { fixture_file_upload('spec/fixtures/dk.png') }
    end

    trait :with_export do
      after(:create) do |project, _evaluator|
        ProjectExportWorker.new.perform(project.creator.id, project.id)
      end
    end

    trait :broken_storage do
      after(:create) do |project|
        project.update_column(:repository_storage, 'broken')
      end
    end

    # Build a custom repository by specifying a hash of `filename => content` in
    # the transient `files` attribute. Each file will be created in its own
    # commit, operating against the master branch. So, the following call:
    #
    #     create(:project, :custom_repo, files: { 'foo/a.txt' => 'foo', 'b.txt' => bar' })
    #
    # will create a repository containing two files, and two commits, in master
    trait :custom_repo do
      transient do
        files { {} }
      end

      after :create do |project, evaluator|
        raise "Failed to create repository!" unless project.create_repository

        evaluator.files.each do |filename, content|
          project.repository.create_file(
            project.creator,
            filename,
            content,
            message: "Automatically created file #{filename}",
            branch_name: 'master'
          )
        end
      end
    end

    # Test repository - https://gitlab.com/gitlab-org/gitlab-test
    trait :repository do
      test_repo

      transient do
        create_templates { nil }
        create_branch { nil }
      end

      after :create do |project, evaluator|
        if evaluator.create_templates
          templates_path = "#{evaluator.create_templates}_templates"

          project.repository.create_file(
            project.creator,
            ".gitlab/#{templates_path}/bug.md",
            'something valid',
            message: 'test 3',
            branch_name: 'master')
          project.repository.create_file(
            project.creator,
            ".gitlab/#{templates_path}/template_test.md",
            'template_test',
            message: 'test 1',
            branch_name: 'master')
          project.repository.create_file(
            project.creator,
            ".gitlab/#{templates_path}/feature_proposal.md",
            'feature_proposal',
            message: 'test 2',
            branch_name: 'master')
        end

        if evaluator.create_branch
          project.repository.create_file(
            project.creator,
            'README.md',
            "README on branch #{evaluator.create_branch}",
            message: 'Add README.md',
            branch_name: evaluator.create_branch)

        end
      end
    end

    trait :empty_repo do
      after(:create) do |project|
        raise "Failed to create repository!" unless project.create_repository
      end
    end

    trait :design_repo do
      after(:create) do |project|
        raise 'Failed to create design repository!' unless project.design_repository.create_if_not_exists
      end
    end

    trait :remote_mirror do
      transient do
        remote_name { "remote_mirror_#{SecureRandom.hex}" }
        url { "http://foo.com" }
        enabled { true }
      end
      after(:create) do |project, evaluator|
        project.remote_mirrors.create!(url: evaluator.url, enabled: evaluator.enabled)
      end
    end

    trait :stubbed_repository do
      after(:build) do |project|
        allow(project).to receive(:empty_repo?).and_return(false)
        allow(project.repository).to receive(:empty?).and_return(false)
      end
    end

    trait :wiki_repo do
      after(:create) do |project|
        raise 'Failed to create wiki repository!' unless project.create_wiki
      end
    end

    trait :read_only do
      repository_read_only { true }
    end

    trait :broken_repo do
      after(:create) do |project|
        TestEnv.rm_storage_dir(project.repository_storage, "#{project.disk_path}.git/refs")
      end
    end

    trait :test_repo do
      after :create do |project|
        TestEnv.copy_repo(project,
          bare_repo: TestEnv.factory_repo_path_bare,
          refs: TestEnv::BRANCH_SHA)
      end
    end

    trait(:wiki_enabled)            { wiki_access_level { ProjectFeature::ENABLED } }
    trait(:wiki_disabled)           { wiki_access_level { ProjectFeature::DISABLED } }
    trait(:wiki_private)            { wiki_access_level { ProjectFeature::PRIVATE } }
    trait(:builds_enabled)          { builds_access_level { ProjectFeature::ENABLED } }
    trait(:builds_disabled)         { builds_access_level { ProjectFeature::DISABLED } }
    trait(:builds_private)          { builds_access_level { ProjectFeature::PRIVATE } }
    trait(:snippets_enabled)        { snippets_access_level { ProjectFeature::ENABLED } }
    trait(:snippets_disabled)       { snippets_access_level { ProjectFeature::DISABLED } }
    trait(:snippets_private)        { snippets_access_level { ProjectFeature::PRIVATE } }
    trait(:issues_disabled)         { issues_access_level { ProjectFeature::DISABLED } }
    trait(:issues_enabled)          { issues_access_level { ProjectFeature::ENABLED } }
    trait(:issues_private)          { issues_access_level { ProjectFeature::PRIVATE } }
    trait(:forking_disabled)         { forking_access_level { ProjectFeature::DISABLED } }
    trait(:forking_enabled)          { forking_access_level { ProjectFeature::ENABLED } }
    trait(:forking_private)          { forking_access_level { ProjectFeature::PRIVATE } }
    trait(:merge_requests_enabled)  { merge_requests_access_level { ProjectFeature::ENABLED } }
    trait(:merge_requests_disabled) { merge_requests_access_level { ProjectFeature::DISABLED } }
    trait(:merge_requests_private)  { merge_requests_access_level { ProjectFeature::PRIVATE } }
    trait(:merge_requests_public)   { merge_requests_access_level { ProjectFeature::PUBLIC } }
    trait(:repository_enabled)      { repository_access_level { ProjectFeature::ENABLED } }
    trait(:repository_disabled)     { repository_access_level { ProjectFeature::DISABLED } }
    trait(:repository_private)      { repository_access_level { ProjectFeature::PRIVATE } }
    trait(:pages_public)            { pages_access_level { ProjectFeature::PUBLIC } }
    trait(:pages_enabled)           { pages_access_level { ProjectFeature::ENABLED } }
    trait(:pages_disabled)          { pages_access_level { ProjectFeature::DISABLED } }
    trait(:pages_private)           { pages_access_level { ProjectFeature::PRIVATE } }

    trait :auto_devops do
      association :auto_devops, factory: :project_auto_devops
    end

    trait :auto_devops_disabled do
      association :auto_devops, factory: [:project_auto_devops, :disabled]
    end

    trait :without_container_expiration_policy do
      after :create do |project|
        project.container_expiration_policy.destroy!
      end
    end
  end

  trait :service_desk_disabled do
    service_desk_enabled { nil }
  end

  trait(:service_desk_enabled) do
    service_desk_enabled { true }
  end

  # Project with empty repository
  #
  # This is a case when you just created a project
  # but not pushed any code there yet
  factory :project_empty_repo, parent: :project do
    empty_repo
  end

  # Project with broken repository
  #
  # Project with an invalid repository state
  factory :project_broken_repo, parent: :project do
    broken_repo
  end

  factory :forked_project_with_submodules, parent: :project do
    path { 'forked-gitlabhq' }

    after :create do |project|
      TestEnv.copy_repo(project,
        bare_repo: TestEnv.forked_repo_path_bare,
        refs: TestEnv::FORKED_BRANCH_SHA)
    end
  end

  factory :redmine_project, parent: :project do
    has_external_issue_tracker { true }

    redmine_service
  end

  factory :youtrack_project, parent: :project do
    has_external_issue_tracker { true }

    youtrack_service
  end

  factory :jira_project, parent: :project do
    has_external_issue_tracker { true }

    jira_service
  end

  factory :mock_deployment_project, parent: :project do
    mock_deployment_service
  end

  factory :prometheus_project, parent: :project do
    after :create do |project|
      project.create_prometheus_service(
        active: true,
        properties: {
          api_url: 'https://prometheus.example.com/',
          manual_configuration: true
        }
      )
    end
  end

  factory :project_with_design, parent: :project do
    after(:create) do |project|
      issue = create(:issue, project: project)
      create(:design, project: project, issue: issue)
    end
  end

  trait :in_subgroup do
    namespace factory: [:group, :nested]
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<draft href="WEBGL_draw_instanced_base_vertex_base_instance/">

  <name>WEBGL_draw_instanced_base_vertex_base_instance</name>

  <contact> WebGL
  working group (public_webgl 'at' khronos.org) </contact>

  <contributors>
    <contributor>Contributors to the ANGLE_base_vertex_base_instance specification</contributor>
    <contributor>Members of the WebGL working group</contributor>
  </contributors>

  <number>46</number>

  <depends>
    <api version="2.0"/>
  </depends>

  <overview>
      <addendum>
        This extension exposes the DrawArraysInstancedBaseInstanceANGLE and
        DrawElementsInstancedBaseVertexBaseInstanceANGLE entrypoints as
        drawArraysInstancedBaseInstanceWEBGL and
        drawElementsInstancedBaseVertexBaseInstanceWEBGL. In addition the vertex
        shader builtin gl_BaseVertex and gl_BaseInstance are added.
      </addendum>
      <addendum>
        The implementation must validate the arrays and indices referenced by
        drawArraysInstancedBaseInstanceWEBGL and
        drawElementsInstancedBaseVertexBaseInstanceWEBGL, similarly to how indices
        referenced by drawArrays and drawElements are validated according
        to section

          Enabled Vertex Attributes and Range Checking
         and

          Range Checking
         of the WebGL specification.
      </addendum>
      <addendum>
        Although the extension name is named WEBGL_draw_instanced_base_vertex_base_instance, the
        extension must be enabled with the
        #extension GL_ANGLE_base_vertex_base_instance directive, as shown in the
        sample code, to use the extension in a shader.

        Likewise the shading language preprocessor
        #define GL_ANGLE_base_vertex_base_instance will be defined to 1 if the
        extension is supported.
      </addendum>

        The baseVertex functionality could effectly help reduce CPU overhead with static batching
        and text rendering in game engine implementations.

        The baseInstance functionality could make instanced arrays more useful as they could start
        instancing from a particular point in the buffer.

    <features>
      <feature>
        The drawArraysInstancedBaseInstanceWEBGL
        and drawElementsInstancedBaseVertexBaseInstanceWEBGL entry points are added.
        These provide a counterpoint to instanced rendering and are more flexible for certain
        scenarios. drawArraysInstancedBaseInstanceWEBGL behaves identically to
        drawArraysInstanced except that the first element within those instanced
        vertex attributes is specified in baseInstance.
        drawElementsInstancedBaseVertexBaseInstanceWEBGL is equivalent to
        drawElementsInstanced except that the value of the base vertex passed into
        driver is baseVertex instead of zero, and that the first element within those
        instanced vertex attributes is specified in baseInstance.
      </feature>

      <feature>
        The gl_BaseVertex and gl_BaseInstance builtins are added to the
        shading language. For any *BaseVertex* draw call variant, the baseVertex of
        the draw may be read by the vertex shader as gl_BaseVertex. For non
        *BaseVertex* calls, the value of gl_BaseVertex is 0. For any *BaseInstance
        draw call variant, the baseInstance of the draw may be read by the vertex
        shader as gl_BaseInstance. For non *BaseInstance calls, the value of
        gl_BaseInstance is 0.
      </feature>

      <feature>
        Notice that the value of gl_BaseVertex is added into gl_VertexID,
        while the value of gl_BaseInstance is not added into
        gl_InstanceID.
      </feature>

      <glsl extname="GL_ANGLE_base_vertex_base_instance">
        <stage type="vertex"/>
        <input name="gl_BaseVertex" type="int" />
        <input name="gl_BaseInstance" type="int" />
      </glsl>
    </features>
  </overview>

  <idl xml:space="preserve">

[NoInterfaceObject]
interface WEBGL_draw_instanced_base_vertex_base_instance {
  void drawArraysInstancedBaseInstanceWEBGL(
      GLenum mode, GLint first, GLsizei count,
      GLsizei instanceCount, GLuint baseInstance
  );
  void drawElementsInstancedBaseVertexBaseInstanceWEBGL(
      GLenum mode, GLsizei count, GLenum type, GLintptr offset,
      GLsizei instanceCount, GLint baseVertex, GLuint baseinstance
  );
};
  </idl>

  <newfun>
    <function name="drawArraysInstancedBaseInstanceWEBGL" type="void">
      <param name="mode" type="GLenum"/>
      <param name="first" type="GLint"/>
      <param name="count" type="GLsizei"/>
      <param name="instanceCount" type="GLsizei"/>
      <param name="baseInstance" type="GLuint"/>
    </function>
    <function name="drawElementsInstancedBaseVertexBaseInstanceWEBGL" type="void">
      <param name="mode" type="GLenum"/>
      <param name="count" type="GLsizei"/>
      <param name="type" type="GLenum"/>
      <param name="offset" type="GLintptr"/>
      <param name="instanceCount" type="GLsizei"/>
      <param name="baseVertex" type="GLint"/>
      <param name="baseInstance" type="GLuint"/>
    </function>
  </newfun>

  <security>
    The base-vertex-base-instance-draw APIs are subject to all of the same rules regarding
    out-of-range array
    accesses as the core WebGL APIs.
  </security>

  <samplecode xml:space="preserve">

var ext = gl.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");

{
  // drawArraysInstancedBaseInstance variant.
  let first = 0;
  let count = 3;
  let instanceCount = 2;
  let baseInstance = 1;
  ext.drawArraysInstancedBaseInstanceWEBGL(
      gl.TRIANGLES, first, count, instanceCount, baseInstance);
}

{
  // drawElementsInstancedBaseVertexBaseInstance variant.
  // Assumes that the indices which have been previously uploaded to the
  // ELEMENT_ARRAY_BUFFER are to be treated as UNSIGNED_SHORT.
  let count = 3;
  let offset = 0;
  let instanceCount = 2;
  let baseVertice = 3;
  let baseInstance = 1;
  ext.drawElementsInstancedBaseVertexBaseInstanceWEBGL(
      gl.TRIANGLES, count, gl.UNSIGHNED_SHORT, offset, instanceCount, baseVertex, baseInstance);
}

#version 300 es
#extension GL_ANGLE_base_vertex_base_instance : require
void main() {
    gl_Position = vec4(gl_BaseVertex, gl_InstanceID + gl_BaseInstance, 0, 1);
}

  </samplecode>

  <tests/>

  <issues/>

  <history>
    <revision date="2019/08/28">
      <change>Initial version.</change>
    </revision>
    <revision date="2019/09/25">
      <change>Move to draft.</change>
    </revision>
  </history>
</draft>


text:
package es.ujaen.rlc00008.gnbwallet;

/**
 * Created by Ricardo on 2/3/16.
 */
public class SysConstants {

	/**
	 * Public Xml Base URL
	 */
	public static final String HOST_BASE_URL = "http://aws01-preproduction01.taksee.com";

}


text:
package com.monszdev.anydumper;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "AnyDumper";
    }
}


text:
import boto

class AvailabilityZone(object):
    """Helper class that represents an availability zone

    We often only want 2 things from an AZ - a slug and name.
    This class keeps those in one location.
    """

    def __init__(self, availability_zone):
        """Creates an AvailabilityZoneHelper object

        Args:
        availability_zone (AvailabilityZone): boto object
        """

        self.availability_zone = availability_zone

    @property
    def cfn_name(self):
        """
        Utility method to return a string appropriate for CloudFormation
        name of a resource (e.g. UsEast1a)
        """
        return self.availability_zone.name.title().replace('-', '')

    @property
    def name(self):
        """Utility function to return the name of an availability zone"""
        return self.availability_zone.name

def get_availability_zones(aws_profile):
    """Helper function that returns availability zones for a region

    Returns:
      (list of AvailabilityZone): List of availability zones for a given
                                  EC2 region
    """
    conn = boto.connect_ec2(profile_name=aws_profile)
    return [AvailabilityZone(az) for az in conn.get_all_zones()]

def get_subnet_cidr_block():
    """Generator to generate unique CIDR block subnets"""
    current = 0
    high = 255
    while current <= high:
        yield '10.0.%s.0/24' % current
        current += 1

def get_recent_ami(aws_profile, ami_name, owner="self"):
    conn = boto.connect_ec2(profile_name=aws_profile)
    images = conn.get_all_images(owners=owner, filters={
        'name': ami_name
    })

    return sorted(filter(lambda i: True if 'beta' not in i.name else False,
                         images),
                  key=lambda i: i.name, reverse=True)[0].id

def read_file(file_name):
    """Reads an entire file and returns it as a string

    Arguments
    :param file_name: A path to a file
    """
    with open(file_name, 'r') as f:
        return f.read()


text:
shared_examples_for "an InnerHash instance" do |object, hash|
  describe ".has_key?" do
    context "when specifing the existing key names" do
      it "returns true" do
        hash.keys.each do |key|
          expect(object).to have_key(key)
        end
      end
    end

    context "when specifing the non-existing key names" do
      it "returns false" do
        hash.keys.each do |key|
          expect(object).not_to have_key(key.reverse)
        end
      end
    end

    context "when specifing the existing key names in symbol" do
      it "returns true" do
        hash.keys.each do |key|
          expect(object).to have_key(key.to_sym)
        end
      end
    end

    context "when specifing the non-existing key names in symbol" do
      it "returns false" do
        hash.keys.each do |key|
          expect(object).not_to have_key(key.reverse.to_sym)
        end
      end
    end
  end

  describe ".[]" do
    context "when specifing the existing key names" do
      it "returns a Hash value" do
        hash.each do |key, value|
          expect(object[key]).to be_a(Configue::Node) if value
        end
      end

      describe "the Hash value" do
        it "has keys described in the setting(s)" do
          hash.each do |key, value|
            expect(object[key].keys).to match_array(value) if value
          end
        end
      end
    end

    context "when specifing the existing key names in symbol" do
      it "returns a Hash value" do
        hash.each do |key, value|
          expect(object[key.to_sym]).to be_a(Configue::Node) if value
        end
      end

      describe "the Hash value" do
        it "has keys described in the setting(s)" do
          hash.each do |key, value|
            expect(object[key.to_sym].keys).to match_array(value) if value
          end
        end
      end
    end
  end

  describe ".(key_name)" do
    context "when call methods which names are existing in the setting(s)" do
      it "returns a Hash value" do
        hash.each do |key, value|
          expect(object.__send__(key)).to be_a(Configue::Node) if value
        end
      end

      describe "the Hash value" do
        it "has keys described in the setting(s)" do
          hash.each do |key, value|
            next unless value
            actual = object.__send__(key)
            expect(actual.keys).to match_array(value)
          end
        end
      end
    end
  end
end


text:
package com.seiche.strike;

import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

public class Player {

	//Player Parameters

	//Movement and position
	private int x = 100;
	private int y = 100;
	private int dx = 0;
	private int dy = 0;
	private boolean firstRun = true;

	//Animation
	private Bitmap myShip[] = new Bitmap[3];
	private int cell = 0;

	//Shooting variables
	private boolean shoot = false;
	private int canShoot = 50;
	private Bitmap bulletImg;
	private ArrayList<PlayerBullet> bulletArray;

	//Constructor takes in the view as a condition to allocate resources
	public Player(Surface v){
		myShip[0] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane01);
		myShip[1] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane02);
		myShip[2] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane03);

		bulletImg = BitmapFactory.decodeResource(v.getResources(), R.drawable.bullet);
		bulletArray = new ArrayList<PlayerBullet>();
	}

	//Moves and draws the player bitmap
	public void draw(Canvas c, int w, int h){
		if(firstRun){
			x = w/2;
			y = h/2;
			firstRun = false;
		}

		x += dx;
		y += dy;

		if(y < 0)
			y = 0;

		cell++;
		if(cell > 2)
			cell = 0;
		c.drawBitmap(myShip[cell], x-32, y-32, null);

		shoot(c);
	}

	public void shoot(Canvas c){
		canShoot++;
		if(shoot && canShoot > 5){
			canShoot = 0;

			bulletArray.add(new PlayerBullet(x, y-20));
		}

		for(int i = 0; i < bulletArray.size(); i++){
			bulletArray.get(i).move();
			int yTemp = bulletArray.get(i).getY();
			c.drawBitmap(bulletImg, bulletArray.get(i).getX()-16, yTemp, null);

			if(yTemp < -16)
				bulletArray.remove(i);
		}
	}

	//Sets the movement variables depending on the input of the touch screen x and y
	//values by dividing the displacement by the hypotenuse of the resulting triangle
	public void setDisplace(int xInput, int yInput){
		int hypo = (int)Math.sqrt(xInput*xInput + yInput*yInput);
		hypo = hypo/50;

		dx = (int)(xInput - x)/hypo;
		dy = (int)(yInput - y)/hypo;
	}

	//Sets the plane to shooting state or not depending on ACTION_DOWN or ACTION_UP state
	public void setShoot(boolean set){
		shoot = set;
	}

	//Returns the movement vector to zero on ACTION_UP
	public void setImobile(){
		dx = 0;
		dy = 0;
	}

	public ArrayList<PlayerBullet> getArray(){
		return bulletArray;
	}

	public void removeBullet(int index){
		bulletArray.get(index).remove();
	}
}


text:
<?php
declare(strict_types=1);
namespace BarkaneArts\Website\Handlers;

use BarkaneArts\Website\HandlerCommon;
use BarkaneArts\Website\HandlerInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class CustomUserHomepage implements HandlerInterface
{
    use HandlerCommon;

    public function __construct()
    {
        $this->beforeInvoke();
    }

    /**
     * Invoke the HTTP request
     *
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @param array $args
     * @return ResponseInterface
     */
    public function __invoke(RequestInterface $request, ResponseInterface $response, array $args = []): ResponseInterface
    {
        if (!($args['user'])) {
            \header('Location: /');
            exit;
        }

        $user = \preg_replace('/[^A-Za-z0-9\-\_]/', '', $args['user']);
        if (!\file_exists(BARKANE_ROOT . '/templates/user/' . $user . '.twig')) {
            \header('Location: /');
            exit;
        }

        // Render index view
        $response->getBody()->write(
            $this->twig->render('user/' . $user .'.twig', $args)
        );
        return $response;
    }

}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/policy/enrollment/private_membership/psm_rlwe_dmserver_client_impl.h"

#include <memory>
#include <string>
#include <vector>

#include "base/check.h"
#include "base/guid.h"
#include "base/metrics/histogram_functions.h"
#include "base/sequence_checker.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chrome/browser/ash/policy/enrollment/private_membership/private_membership_rlwe_client.h"
#include "chrome/browser/ash/policy/enrollment/private_membership/psm_rlwe_dmserver_client.h"
#include "chrome/browser/ash/policy/enrollment/private_membership/psm_rlwe_id_provider.h"
#include "chrome/common/pref_names.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/core/common/cloud/dmserver_job_configurations.h"
#include "components/policy/core/common/cloud/enterprise_metrics.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/prefs/pref_service.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/private_membership/src/private_membership_rlwe.pb.h"

namespace psm_rlwe = private_membership::rlwe;
namespace em = enterprise_management;

namespace policy {

PsmRlweDmserverClientImpl::PsmRlweDmserverClientImpl(
    DeviceManagementService* device_management_service,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    PrivateMembershipRlweClient::Factory* psm_rlwe_client_factory,
    PsmRlweIdProvider* psm_rlwe_id_provider)
    : random_device_id_(base::GenerateGUID()),
      url_loader_factory_(url_loader_factory),
      device_management_service_(device_management_service) {
  CHECK(device_management_service);
  CHECK(psm_rlwe_client_factory);
  CHECK(psm_rlwe_id_provider);

  psm_rlwe_id_ = psm_rlwe_id_provider->ConstructRlweId();

  // Create PSM client for |psm_rlwe_id_| with use case as CROS_DEVICE_STATE.
  std::vector<psm_rlwe::RlwePlaintextId> psm_ids = {psm_rlwe_id_};
  auto status_or_client = psm_rlwe_client_factory->Create(
      psm_rlwe::RlweUseCase::CROS_DEVICE_STATE, psm_ids);
  if (!status_or_client.ok()) {
    // If the PSM RLWE client hasn't been created successfully, then report
    // the error and don't run the protocol.
    LOG(ERROR) << "PSM error: unexpected internal logic error during creating "
                  "PSM RLWE client";
    last_psm_execution_result_ =
        ResultHolder(PsmResult::kCreateRlweClientLibraryError);
    base::UmaHistogramEnumeration(kUMAPsmResult + uma_suffix_,
                                  PsmResult::kCreateRlweClientLibraryError);
    return;
  }

  psm_rlwe_client_ = std::move(status_or_client).value();
}

PsmRlweDmserverClientImpl::~PsmRlweDmserverClientImpl() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void PsmRlweDmserverClientImpl::CheckMembership(CompletionCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(callback);

  // Ignore new calls and execute `callback` with
  // |last_psm_execution_result_|, in case any error occurred while running
  // PSM previously.
  if (last_psm_execution_result_ &&
      last_psm_execution_result_.value().IsError()) {
    std::move(callback).Run(last_psm_execution_result_.value());
    return;
  }

  // There should not be any pending PSM requests.
  CHECK(!psm_request_job_);

  time_start_ = base::TimeTicks::Now();

  on_completion_callback_ = std::move(callback);

  SendPsmRlweOprfRequest();
}

bool PsmRlweDmserverClientImpl::IsCheckMembershipInProgress() const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return psm_request_job_ != nullptr;
}

void PsmRlweDmserverClientImpl::StoreErrorAndStop(PsmResult psm_result) {
  // Note that kUMAPsmResult histogram is only using initial enrollment as a
  // suffix until PSM support FRE.
  base::UmaHistogramEnumeration(kUMAPsmResult + uma_suffix_, psm_result);

  // Stop the current |psm_request_job_|.
  psm_request_job_.reset();

  last_psm_execution_result_ = ResultHolder(psm_result);
  std::move(on_completion_callback_).Run(last_psm_execution_result_.value());
}

void PsmRlweDmserverClientImpl::SendPsmRlweOprfRequest() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Create RLWE OPRF request.
  const auto status_or_oprf_request = psm_rlwe_client_->CreateOprfRequest();
  if (!status_or_oprf_request.ok()) {
    // If the RLWE OPRF request hasn't been created successfully, then report
    // the error and stop the protocol.
    LOG(ERROR) << "PSM error: unexpected internal logic error during creating "
                  "RLWE OPRF request";
    StoreErrorAndStop(PsmResult::kCreateOprfRequestLibraryError);
    return;
  }

  LOG(WARNING) << "PSM: prepare and send out the RLWE OPRF request";

  // Prepare the RLWE OPRF request job.
  // The passed callback will not be called if |psm_request_job_| is
  // destroyed, so it's safe to use base::Unretained.
  std::unique_ptr<DMServerJobConfiguration> config =
      CreatePsmRequestJobConfiguration(base::BindOnce(
          &PsmRlweDmserverClientImpl::OnRlweOprfRequestCompletion,
          base::Unretained(this)));

  em::DeviceManagementRequest* request = config->request();
  em::PrivateSetMembershipRlweRequest* psm_rlwe_request =
      request->mutable_private_set_membership_request()->mutable_rlwe_request();

  *psm_rlwe_request->mutable_oprf_request() = status_or_oprf_request.value();
  psm_request_job_ = device_management_service_->CreateJob(std::move(config));
}

void PsmRlweDmserverClientImpl::OnRlweOprfRequestCompletion(
    DeviceManagementService::Job* job,
    DeviceManagementStatus status,
    int net_error,
    const em::DeviceManagementResponse& response) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  base::UmaHistogramSparse(kUMAPsmDmServerRequestStatus + uma_suffix_, status);

  switch (status) {
    case DM_STATUS_SUCCESS: {
      // Check if the RLWE OPRF response is empty.
      if (!response.private_set_membership_response().has_rlwe_response() ||
          !response.private_set_membership_response()
               .rlwe_response()
               .has_oprf_response()) {
        LOG(ERROR) << "PSM error: empty OPRF RLWE response";
        StoreErrorAndStop(PsmResult::kEmptyOprfResponseError);
        return;
      }

      LOG(WARNING) << "PSM RLWE OPRF request completed successfully";
      SendPsmRlweQueryRequest(response.private_set_membership_response());
      return;
    }
    case DM_STATUS_REQUEST_FAILED: {
      LOG(ERROR)
          << "PSM error: RLWE OPRF request failed due to connection error";
      base::UmaHistogramSparse(kUMAPsmNetworkErrorCode + uma_suffix_,
                               -net_error);
      StoreErrorAndStop(PsmResult::kConnectionError);
      return;
    }
    default: {
      LOG(ERROR) << "PSM error: RLWE OPRF request failed due to server error";
      StoreErrorAndStop(PsmResult::kServerError);
      return;
    }
  }
}

void PsmRlweDmserverClientImpl::SendPsmRlweQueryRequest(
    const em::PrivateSetMembershipResponse& psm_response) {
  // Extract the oprf_response from |psm_response|.
  const psm_rlwe::PrivateMembershipRlweOprfResponse oprf_response =
      psm_response.rlwe_response().oprf_response();

  const auto status_or_query_request =
      psm_rlwe_client_->CreateQueryRequest(oprf_response);

  // Create RLWE query request.
  if (!status_or_query_request.ok()) {
    // If the RLWE query request hasn't been created successfully, then report
    // the error and stop the protocol.
    LOG(ERROR) << "PSM error: unexpected internal logic error during creating "
                  "RLWE query request";
    StoreErrorAndStop(PsmResult::kCreateQueryRequestLibraryError);
    return;
  }

  LOG(WARNING) << "PSM: prepare and send out the RLWE query request";

  // Prepare the RLWE query request job.
  std::unique_ptr<DMServerJobConfiguration> config =
      CreatePsmRequestJobConfiguration(base::BindOnce(
          &PsmRlweDmserverClientImpl::OnRlweQueryRequestCompletion,
          base::Unretained(this), oprf_response));

  em::DeviceManagementRequest* request = config->request();
  em::PrivateSetMembershipRlweRequest* psm_rlwe_request =
      request->mutable_private_set_membership_request()->mutable_rlwe_request();

  *psm_rlwe_request->mutable_query_request() = status_or_query_request.value();
  psm_request_job_ = device_management_service_->CreateJob(std::move(config));
}

void PsmRlweDmserverClientImpl::OnRlweQueryRequestCompletion(
    const psm_rlwe::PrivateMembershipRlweOprfResponse& oprf_response,
    DeviceManagementService::Job* job,
    DeviceManagementStatus status,
    int net_error,
    const em::DeviceManagementResponse& response) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  base::UmaHistogramSparse(kUMAPsmDmServerRequestStatus + uma_suffix_, status);

  switch (status) {
    case DM_STATUS_SUCCESS: {
      // Check if the RLWE query response is empty.
      if (!response.private_set_membership_response().has_rlwe_response() ||
          !response.private_set_membership_response()
               .rlwe_response()
               .has_query_response()) {
        LOG(ERROR) << "PSM error: empty query RLWE response";
        StoreErrorAndStop(PsmResult::kEmptyQueryResponseError);
        return;
      }

      const psm_rlwe::PrivateMembershipRlweQueryResponse query_response =
          response.private_set_membership_response()
              .rlwe_response()
              .query_response();

      auto status_or_responses =
          psm_rlwe_client_->ProcessQueryResponse(query_response);

      if (!status_or_responses.ok()) {
        // If the RLWE query response hasn't processed successfully, then
        // report the error and stop the protocol.
        LOG(ERROR) << "PSM error: unexpected internal logic error during "
                      "processing the "
                      "RLWE query response";
        StoreErrorAndStop(PsmResult::kProcessingQueryResponseLibraryError);
        return;
      }

      LOG(WARNING) << "PSM query request completed successfully";

      base::UmaHistogramEnumeration(kUMAPsmResult + uma_suffix_,
                                    PsmResult::kSuccessfulDetermination);
      RecordPsmSuccessTimeHistogram();

      // The RLWE query response has been processed successfully. Extract
      // the membership response, and report the result.

      psm_rlwe::RlweMembershipResponses rlwe_membership_responses =
          std::move(status_or_responses).value();

      // Ensure the existence of one membership response. Then, verify that it
      // is regarding the current PSM ID.
      if (rlwe_membership_responses.membership_responses_size() != 1 ||
          rlwe_membership_responses.membership_responses(0)
                  .plaintext_id()
                  .sensitive_id() != psm_rlwe_id_.sensitive_id()) {
        LOG(ERROR)
            << "PSM error: RLWE membership responses are either empty or its "
               "first response's ID is not the same as the current PSM ID.";
        // TODO(crbug.com/1302982): Record that error separately and merge it
        // with PsmResult.
        StoreErrorAndStop(PsmResult::kEmptyQueryResponseError);
        return;
      }

      const bool membership_result =
          rlwe_membership_responses.membership_responses(0)
              .membership_response()
              .is_member();

      LOG(WARNING) << "PSM determination successful. Identifier "
                   << (membership_result ? "" : "not ")
                   << "present on the server";

      // Reset the |psm_request_job_| to allow another call to
      // CheckMembership.
      psm_request_job_.reset();

      // Store the last PSM execution result.
      last_psm_execution_result_ =
          ResultHolder(PsmResult::kSuccessfulDetermination, membership_result,
                       /*membership_determination_time=*/base::Time::Now());

      std::move(on_completion_callback_)
          .Run(last_psm_execution_result_.value());
      return;
    }
    case DM_STATUS_REQUEST_FAILED: {
      LOG(ERROR)
          << "PSM error: RLWE query request failed due to connection error";
      base::UmaHistogramSparse(kUMAPsmNetworkErrorCode + uma_suffix_,
                               -net_error);
      StoreErrorAndStop(PsmResult::kConnectionError);
      return;
    }
    default: {
      LOG(ERROR) << "PSM error: RLWE query request failed due to server error";
      StoreErrorAndStop(PsmResult::kServerError);
      return;
    }
  }
}

std::unique_ptr<DMServerJobConfiguration>
PsmRlweDmserverClientImpl::CreatePsmRequestJobConfiguration(
    DMServerJobConfiguration::Callback callback) {
  return std::make_unique<DMServerJobConfiguration>(
      device_management_service_,
      DeviceManagementService::JobConfiguration::
          TYPE_PSM_HAS_DEVICE_STATE_REQUEST,
      random_device_id_,
      /*critical=*/true, DMAuth::NoAuth(),
      /*oauth_token=*/absl::nullopt, url_loader_factory_, std::move(callback));
}

void PsmRlweDmserverClientImpl::RecordPsmSuccessTimeHistogram() {
  // These values determine bucketing of the histogram, they should not be
  // changed.
  static const base::TimeDelta kMin = base::Milliseconds(1);
  static const base::TimeDelta kMax = base::Seconds(25);
  static const int kBuckets = 50;

  base::TimeTicks now = base::TimeTicks::Now();
  if (!time_start_.is_null()) {
    base::TimeDelta delta = now - time_start_;
    base::UmaHistogramCustomTimes(kUMAPsmSuccessTime, delta, kMin, kMax,
                                  kBuckets);
  }
}

}  // namespace policy


text:
package org.apache.flink.streaming.api.operators.source;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.eventtime.TimestampAssigner;
import org.apache.flink.api.common.eventtime.Watermark;
import org.apache.flink.api.common.eventtime.WatermarkGenerator;
import org.apache.flink.api.common.eventtime.WatermarkOutput;
import org.apache.flink.api.connector.source.SourceOutput;
import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.tasks.ExceptionInChainedOperatorException;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Implementation of the SourceOutput. The records emitted to this output are pushed into a given
 * {@link PushingAsyncDataInput.DataOutput}. The watermarks are pushed into the same output, or into
 * a separate {@link WatermarkOutput}, if one is provided.
 *
 *
Periodic Watermarks

 *
 *
This output does not implement automatic periodic watermark emission. The method {@link
 * SourceOutputWithWatermarks#emitPeriodicWatermark()} needs to be called periodically.
 *
 *
Note on Performance Considerations

 *
 *
The methods {@link SourceOutput#collect(Object)} and {@link SourceOutput#collect(Object,
 * long)} are highly performance-critical (part of the hot loop). To make the code as JIT friendly
 * as possible, we want to have only a single implementation of these two methods, across all
 * classes. That way, the JIT compiler can de-virtualize (and inline) them better.
 *
 *
Currently, we have one implementation of these methods for the case where we don't need
 * watermarks (see class {@link NoOpTimestampsAndWatermarks}) and one for the case where we do (this
 * class). When the JVM is dedicated to a single job (or type of job) only one of these classes will
 * be loaded. In mixed job setups, we still have a bimorphic method (rather than a
 * poly/-/mega-morphic method).
 *
 * @param <T> The type of emitted records.
 */
@Internal
public class SourceOutputWithWatermarks<T> implements SourceOutput<T> {

    private final PushingAsyncDataInput.DataOutput<T> recordsOutput;

    private final TimestampAssigner<T> timestampAssigner;

    private final WatermarkGenerator<T> watermarkGenerator;

    private final WatermarkOutput onEventWatermarkOutput;

    private final WatermarkOutput periodicWatermarkOutput;

    private final StreamRecord<T> reusingRecord;

    /**
     * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput and
     * watermarks to the (possibly different) WatermarkOutput.
     */
    protected SourceOutputWithWatermarks(
            PushingAsyncDataInput.DataOutput<T> recordsOutput,
            WatermarkOutput onEventWatermarkOutput,
            WatermarkOutput periodicWatermarkOutput,
            TimestampAssigner<T> timestampAssigner,
            WatermarkGenerator<T> watermarkGenerator) {

        this.recordsOutput = checkNotNull(recordsOutput);
        this.onEventWatermarkOutput = checkNotNull(onEventWatermarkOutput);
        this.periodicWatermarkOutput = checkNotNull(periodicWatermarkOutput);
        this.timestampAssigner = checkNotNull(timestampAssigner);
        this.watermarkGenerator = checkNotNull(watermarkGenerator);
        this.reusingRecord = new StreamRecord<>(null);
    }

    // ------------------------------------------------------------------------
    // SourceOutput Methods
    //
    // Note that the two methods below are final, as a partial enforcement
    // of the performance design goal mentioned in the class-level comment.
    // ------------------------------------------------------------------------

    @Override
    public final void collect(T record) {
        collect(record, TimestampAssigner.NO_TIMESTAMP);
    }

    @Override
    public final void collect(T record, long timestamp) {
        try {
            final long assignedTimestamp = timestampAssigner.extractTimestamp(record, timestamp);

            // IMPORTANT: The event must be emitted before the watermark generator is called.
            recordsOutput.emitRecord(reusingRecord.replace(record, assignedTimestamp));
            watermarkGenerator.onEvent(record, assignedTimestamp, onEventWatermarkOutput);
        } catch (ExceptionInChainedOperatorException e) {
            throw e;
        } catch (Exception e) {
            throw new ExceptionInChainedOperatorException(e);
        }
    }

    // ------------------------------------------------------------------------
    // WatermarkOutput Methods
    //
    // These two methods are final as well, to enforce the contract that the
    // watermarks from emitWatermark(Watermark) go to the same output as the
    // watermarks from the watermarkGenerator.onEvent(...) calls in the collect(...)
    // methods.
    // ------------------------------------------------------------------------

    @Override
    public final void emitWatermark(Watermark watermark) {
        onEventWatermarkOutput.emitWatermark(watermark);
    }

    @Override
    public final void markIdle() {
        onEventWatermarkOutput.markIdle();
    }

    @Override
    public void markActive() {
        onEventWatermarkOutput.markActive();
    }

    public final void emitPeriodicWatermark() {
        watermarkGenerator.onPeriodicEmit(periodicWatermarkOutput);
    }

    // ------------------------------------------------------------------------
    // Factories
    // ------------------------------------------------------------------------

    /**
     * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput and
     * watermarks to the (possibly different) WatermarkOutput.
     */
    public static <E> SourceOutputWithWatermarks<E> createWithSameOutputs(
            PushingAsyncDataInput.DataOutput<E> recordsAndWatermarksOutput,
            TimestampAssigner<E> timestampAssigner,
            WatermarkGenerator<E> watermarkGenerator) {

        final WatermarkOutput watermarkOutput =
                new WatermarkToDataOutput(recordsAndWatermarksOutput);

        return new SourceOutputWithWatermarks<>(
                recordsAndWatermarksOutput,
                watermarkOutput,
                watermarkOutput,
                timestampAssigner,
                watermarkGenerator);
    }

    /**
     * Creates a new SourceOutputWithWatermarks that emits records to the given DataOutput and
     * watermarks to the different WatermarkOutputs.
     */
    public static <E> SourceOutputWithWatermarks<E> createWithSeparateOutputs(
            PushingAsyncDataInput.DataOutput<E> recordsOutput,
            WatermarkOutput onEventWatermarkOutput,
            WatermarkOutput periodicWatermarkOutput,
            TimestampAssigner<E> timestampAssigner,
            WatermarkGenerator<E> watermarkGenerator) {

        return new SourceOutputWithWatermarks<>(
                recordsOutput,
                onEventWatermarkOutput,
                periodicWatermarkOutput,
                timestampAssigner,
                watermarkGenerator);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBitcoin
{
	public abstract class ChainBase
	{
		public virtual ChainedBlock Genesis
		{
			get
			{
				return GetBlock(0);
			}
		}
		public abstract ChainedBlock GetBlock(uint256 id);
		public abstract ChainedBlock GetBlock(int height);
		public abstract ChainedBlock Tip
		{
			get;
		}
		public abstract int Height
		{
			get;
		}

		public bool Contains(uint256 hash)
		{
			ChainedBlock pindex = GetBlock(hash);
			return pindex != null;
		}

		public IEnumerable<ChainedBlock> ToEnumerable(bool fromTip)
		{
			if(fromTip)
			{
				ChainedBlock b = Tip;
				while(b != null)
				{
					yield return b;
					b = b.Previous;
				}
			}
			else
			{
				foreach(var b in EnumerateFromStart())
					yield return b;
			}
		}

		public ChainedBlock SetTip(ChainBase otherChain)
		{
			if (otherChain == null) throw new ArgumentNullException("otherChain");
			return SetTip(otherChain.Tip);
		}

		public bool SetTip(BlockHeader header)
		{
			ChainedBlock chainedHeader;
			return TrySetTip(header, out chainedHeader);
		}

		public bool TrySetTip(BlockHeader header, out ChainedBlock chainedHeader)
		{
			if (header == null) throw new ArgumentNullException("header");
			chainedHeader = null;
			var prev = GetBlock(header.HashPrevBlock);
			if(prev == null)
				return false;
			chainedHeader = new ChainedBlock(header, header.GetHash(), GetBlock(header.HashPrevBlock));
			SetTip(chainedHeader);
			return true;
		}

		protected abstract IEnumerable<ChainedBlock> EnumerateFromStart();

		public bool Contains(ChainedBlock blockIndex)
		{
			if (blockIndex == null) throw new ArgumentNullException("blockIndex");
			return GetBlock(blockIndex.Height) != null;
		}

		public bool SameTip(ChainBase chain)
		{
			if (chain == null) throw new ArgumentNullException("chain");
			return Tip.HashBlock == chain.Tip.HashBlock;
		}

		public Target GetWorkRequired(Network network, int height)
		{
			return GetBlock(height).GetWorkRequired(network);
		}

		public bool Validate(Network network, bool fullChain = true)
		{
			var tip = Tip;
			if(tip == null)
				return false;
			if(!fullChain)
				return tip.Validate(network);
			else
			{
				foreach(var block in tip.EnumerateToGenesis())
				{
					if(!block.Validate(network))
						return false;
				}
				return true;
			}
		}

		public ChainedBlock FindFork(ChainBase chain)
		{
			if (chain == null) throw new ArgumentNullException("chain");
			return FindFork(chain.ToEnumerable(true).Select(o => o.HashBlock));
		}

		public ChainedBlock FindFork(IEnumerable<uint256> hashes)
		{
			if (hashes == null) throw new ArgumentNullException("hashes");
			// Find the first block the caller has in the main chain
			foreach(uint256 hash in hashes)
			{
				ChainedBlock mi = GetBlock(hash);
				if(mi != null)
				{
					return mi;
				}
			}
			return Genesis;
		}
#if !PORTABLE
		public ChainedBlock FindFork(BlockLocator locator)
		{
			if (locator == null) throw new ArgumentNullException("locator");
			return FindFork(locator.Blocks);
		}
#endif

		public IEnumerable<ChainedBlock> EnumerateAfter(uint256 blockHash)
		{
			var block = GetBlock(blockHash);
			if(block == null)
				return new ChainedBlock[0];
			return EnumerateAfter(block);
		}

		public IEnumerable<ChainedBlock> EnumerateToTip(ChainedBlock block)
		{
			if (block == null) throw new ArgumentNullException("block");
			return EnumerateToTip(block.HashBlock);
		}

		public IEnumerable<ChainedBlock> EnumerateToTip(uint256 blockHash)
		{
			var block = GetBlock(blockHash);
			if(block == null)
				yield break;
			yield return block;
			foreach(var r in EnumerateAfter(blockHash))
				yield return r;
		}

		public virtual IEnumerable<ChainedBlock> EnumerateAfter(ChainedBlock block)
		{
			int i = block.Height + 1;
			var prev = block;
			while(true)
			{
				var b = GetBlock(i);
				if(b == null || b.Previous != prev)
					yield break;
				yield return b;
				i++;
				prev = b;
			}
		}

		/// <summary>
		/// Force a new tip for the chain
		/// </summary>
		/// <param name="pindex"></param>
		/// <returns>forking point</returns>
		public abstract ChainedBlock SetTip(ChainedBlock pindex);
	}
}


text:
package org.jboss.weld.tests.specialization.weld1651;

import javax.inject.Inject;

import org.junit.Assert;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.weld.test.util.Utils;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Tomas Remes
 */

@RunWith(Arquillian.class)
public class GenericBeanSpecializationTest {

    @Inject
    MetalFan<Music> fan;

    @Deployment
    public static WebArchive createWebArchive() {
        WebArchive war = ShrinkWrap.create(WebArchive.class, Utils.getDeploymentNameAsHash(GenericBeanSpecializationTest.class, Utils.ARCHIVE_TYPE.WAR));
        war.addClasses(GenericBeanSpecializationTest.class, Fan.class, MetalFan.class, Music.class);
        war.addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
        return war;
    }

    @Test
    public void testGenericBeanSpecialization(){
        Assert.assertNotNull(fan);
    }

}


text: Rails.application.config.session_store :cookie_store, key: '_TestNgGrid_session'


text:
package task

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"time"
)

func ReadFile(path string) (Task, error) {
	task := Task{Path: path}

	f, err := os.Open(path)
	if err != nil {
		return task, err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	line := 0
	for scanner.Scan() {
		text := scanner.Text()
		switch line {
		case 0:
			// Created
			task.Created, err = time.ParseInLocation(time.RFC3339, text, time.Local)
			if err != nil {
				return task, err
			}

		case 1:
			// Due date
			task.Due, err = time.ParseInLocation(time.RFC3339, text, time.Local)
			if err != nil {
				return task, err
			}

		case 2:
			// Priority
			task.Priority, err = parsePriority(text)
			if err != nil {
				return task, err
			}

		case 3:
			// State
			var state int
			state, err = strconv.Atoi(text)
			if err != nil {
				return task, err
			}
			task.State = State(state)

		case 4:
			// Started
			task.Started, err = time.ParseInLocation(time.RFC3339, text, time.Local)
			if err != nil {
				return task, err
			}

		case 5:
			// Worked
			task.Worked, err = time.ParseDuration(text)
			if err != nil {
				return task, err
			}

		case 6:
			// Description
			task.Description = text

		default:
			task.Notes += text + "\n"
		}

		line++
	}

	task.UpdateID()
	return task, nil
}

func (t *Task) Write() error {
	file, err := os.Create(t.Path)
	if err != nil {
		return err
	}
	defer file.Close()

	// Write the fields in the following order
	file.WriteString(t.Created.Format(time.RFC3339))
	file.WriteString("\n")
	file.WriteString(t.Due.Format(time.RFC3339))
	file.WriteString("\n")
	file.WriteString(fmt.Sprintln(t.Priority))
	file.WriteString(fmt.Sprintf("%d\n", t.State))
	file.WriteString(t.Started.Format(time.RFC3339))
	file.WriteString("\n")
	file.WriteString(t.Worked.String())
	file.WriteString("\n")
	file.WriteString(t.Description)
	file.WriteString("\n")
	file.WriteString(t.Notes)

	return nil
}


text:
require 'config'
require 'logger'

ActiveRecord::Base.configurations = {
  'test' => {
    :adapter  => 'mysql',
    :database => DB_NAME,
    :username => DB_USER
  }
}

ActiveRecord::Base.establish_connection 'test'

require 'schema'

class Article < ActiveRecord::Base; end


text:
namespace Atlas.Internal
{
    internal static class Version
    {
        public static int Major
        {
            get { return 0; }
        }

        public static int Minor
        {
            get { return 9; }
        }

        public static int Revision
        {
            get { return 7; }
        }

        public static string Full
        {
            get
            {
                return string.Format( "{0}.{1}.{2}", Major, Minor, Revision );
            }
        }
    }
}


text:
/* parser.h -- Everything you wanted to know about the parser, but were
   afraid to ask. */

/* Copyright (C) 1995 Free Software Foundation, Inc.

   This file is part of GNU Bash, the Bourne Again SHell.

   Bash is free software; you can redistribute it and/or modify it under
   the terms of the GNU General Public License as published by the Free
   Software Foundation; either version 2, or (at your option) any later
   version.

   Bash is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   for more details.

   You should have received a copy of the GNU General Public License along
   with Bash; see the file COPYING.  If not, write to the Free Software
   Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */

#if !defined (_PARSER_H_)
#  define _PARSER_H_

#  include "command.h"
#  include "input.h"

/* Definition of the delimiter stack.  Needed by parse.y and bashhist.c. */
struct dstack {
/* DELIMITERS is a stack of the nested delimiters that we have
   encountered so far. */
  char *delimiters;

/* Offset into the stack of delimiters. */
  int delimiter_depth;

/* How many slots are allocated to DELIMITERS. */
  int delimiter_space;
};

#endif /* _PARSER_H_ */


text:
- UPCOMING EVENTS -

 0">

Loading events.. This may take a few seconds..

{{event.name}}

              {{event.description}}

              Participating: {{event.participating}}

              My Status:     {{event.currentPlayerStatus}}

              Event is locked - Please join other events!

              <button ng-disabled="event.rankinglocked" class="btn btn-primary" data-toggle="modal" data-target="#participateModal" ng-click="register_for_event(event.id, 'participate')"> I'd like to participate</button>
              <button class="btn btn-primary" data-toggle="modal" data-target="#watchModal"ng-click="register_for_event(event.id, 'watch')"> I'd like to come watch</button>
              <button class="btn btn-primary" data-toggle="modal" data-target="#postModal"ng-click="register_for_event(event.id, 'follow')"> Keep me posted</button>
              <button class="btn btn-primary" ng-click="go_to_eventsRanking(event.id)"> I'd like to view the rankings</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Thanks for participating!

        <button type="button" class="btn btn-success" data-dismiss="modal">You are welcome!</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Thanks for coming to watch!

        <button type="button" class="btn btn-success" data-dismiss="modal">You are welcome!</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Thanks for your interest!

        <button type="button" class="btn btn-success" data-dismiss="modal">You are welcome!</button>


text:
package org.springframework.security.oauth2.config.xml;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.BeanMetadataElement;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.http.MatcherType;
import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

/**
 * Common place for OAuth namespace configuration utils.
 *
 * @author Ryan Heaton
 */
public class ConfigUtils {
  private static final Method createMatcherMethod3x = ReflectionUtils.findMethod(
          MatcherType.class, "createMatcher", String.class, String.class);
  private static final Method createMatcherMethod4x = ReflectionUtils.findMethod(
          MatcherType.class, "createMatcher", ParserContext.class, String.class, String.class);

  private ConfigUtils() {
  }

  public static BeanDefinition createSecurityMetadataSource(Element element, ParserContext pc) {
    List<Element> filterPatterns = DomUtils.getChildElementsByTagName(element, "url");

    if (filterPatterns.isEmpty()) {
      return null;
    }

    // TODO : add support for lowercase-comparisons
    String patternType = element.getAttribute("path-type");
    if (!StringUtils.hasText(patternType)) {
      patternType = "ant";
    }

    MatcherType matcherType = MatcherType.valueOf(patternType);

    ManagedMap<BeanDefinition, BeanDefinition> invocationDefinitionMap = new ManagedMap<BeanDefinition, BeanDefinition>();

    for (Element filterPattern : filterPatterns) {
      String path = filterPattern.getAttribute("pattern");
      if (!StringUtils.hasText(path)) {
        pc.getReaderContext().error("pattern attribute cannot be empty or null", filterPattern);
      }

      String method = filterPattern.getAttribute("httpMethod");
      if (!StringUtils.hasText(method)) {
        method = null;
      }

      String access = filterPattern.getAttribute("resources");

      if (StringUtils.hasText(access)) {
        BeanDefinition matcher;
        if (createMatcherMethod4x != null) {
          matcher  = (BeanDefinition)ReflectionUtils.invokeMethod(createMatcherMethod4x, matcherType, pc, path, method);
        } else {
          matcher  = (BeanDefinition)ReflectionUtils.invokeMethod(createMatcherMethod3x, matcherType, path, method);
        }

        if (access.equals("none")) {
          invocationDefinitionMap.put(matcher, BeanDefinitionBuilder.rootBeanDefinition(Collections.class).setFactoryMethod("emptyList").getBeanDefinition());
        }
        else {
          BeanDefinitionBuilder attributeBuilder = BeanDefinitionBuilder.rootBeanDefinition(SecurityConfig.class);
          attributeBuilder.addConstructorArgValue(access);
          attributeBuilder.setFactoryMethod("createListFromCommaDelimitedString");

          if (invocationDefinitionMap.containsKey(matcher)) {
            pc.getReaderContext().warning("Duplicate URL defined: " + path
                                            + ". The original attribute values will be overwritten", pc.extractSource(filterPattern));
          }

          invocationDefinitionMap.put(matcher, attributeBuilder.getBeanDefinition());
        }
      }
    }

    BeanDefinitionBuilder fidsBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultFilterInvocationSecurityMetadataSource.class);
    fidsBuilder.addConstructorArgValue(invocationDefinitionMap);
    fidsBuilder.getRawBeanDefinition().setSource(pc.extractSource(element));

    return fidsBuilder.getBeanDefinition();
  }

  @SuppressWarnings({"unchecked"})
  public static List<BeanMetadataElement> findFilterChain(ParserContext parserContext, String explicitRef) {
    String filterChainRef = explicitRef;
    if (!StringUtils.hasText(filterChainRef)) {
      filterChainRef = findDefaultFilterChainBeanId(parserContext);
    }
    return (List<BeanMetadataElement>)
            parserContext.getRegistry().getBeanDefinition(filterChainRef).getConstructorArgumentValues().getArgumentValue(1,List.class).getValue();
  }

  @SuppressWarnings({"unchecked"})
  protected static String findDefaultFilterChainBeanId(ParserContext parserContext) {
    BeanDefinition filterChainList = parserContext.getRegistry().getBeanDefinition(BeanIds.FILTER_CHAINS);
    // Get the list of SecurityFilterChain beans
    List<BeanReference> filterChains = (List<BeanReference>)
              filterChainList.getPropertyValues().getPropertyValue("sourceList").getValue();

    return filterChains.get(filterChains.size() - 1).getBeanName();
  }

}


text:
<?php
use chilimatic\lib\transformer\string\AnnotationValidatorClassName;

/**
 *
 * @author j
 * Date: 9/27/15
 * Time: 7:55 PM
 *
 * File: AnnotationValidatorClassNameTest.php
 */
class AnnotationValidatorClassNameTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function checkIfTheFirstLetterIsUpperCase() {
        $transformer = new AnnotationValidatorClassName();
        $className = $transformer->transform('class');
        $this->assertEquals('Class', $className);
    }

    /**
     * @test
     */
    public function checkIfFirstLetterAfterADelimiterIsUpperCase() {
        $transformer = new AnnotationValidatorClassName();
        $className = $transformer('\class');
        $this->assertEquals('\Class', $className);
    }

    /**
     * @test
     */
    public function checkIfTheBeginningLetterOfTheClassNameIsUpperCaseAfterTheLastBackslash() {
        $transformer = new AnnotationValidatorClassName();
        $className = $transformer('\my\test\class');
        $this->assertEquals('\my\test\Class', $className);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SassyStudio.Compiler.Parsing.Selectors
{
    public class ClassSelector : SimpleSelector
    {
        public ClassName Name { get; protected set; }
        protected override bool ParseSelectorToken(IItemFactory itemFactory, ITextProvider text, ITokenStream stream)
        {
            var name = itemFactory.CreateSpecific<ClassName>(this, text, stream);
            if (name.Parse(itemFactory, text, stream))
            {
                Name = name;
                Children.Add(name);
            }

            return Children.Count > 0;
        }
    }
}


text:
<title>GETLOG - The GNU Fortran Compiler</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="The GNU Fortran Compiler">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Intrinsic-Procedures.html#Intrinsic-Procedures" title="Intrinsic Procedures">
<link rel="prev" href="GETGID.html#GETGID" title="GETGID">
<link rel="next" href="GETPID.html#GETPID" title="GETPID">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: GETPID,
Previous: GETGID,
Up: Intrinsic Procedures

8.105 GETLOG — Get login name

Description:
Gets the username under which the program is running.

Standard:
GNU extension

Class:
Subroutine

Syntax:
CALL GETLOG(C)

Arguments:

<var>C</var> 	Shall be of type CHARACTER and of default kind.

Return value:
Stores the current user name in <var>LOGIN</var>.  (On systems where POSIX
functions geteuid and getpwuid are not available, and
the getlogin function is not implemented either, this will
return a blank string.)

Example:

          PROGRAM TEST_GETLOG
            CHARACTER(32) :: login
            CALL GETLOG(login)
            WRITE(*,*) login
          END PROGRAM

See also:
GETUID


text:
package openutil

import (
	"log"
	"net"
	"net/http"
	"strings"
	"time"

	"github.com/shurcooL/github_flavored_markdown/gfmstyle"
	"github.com/shurcooL/go/gfmutil"
	"github.com/shurcooL/go/open"
)

// DisplayMarkdownInBrowser displays given Markdown in a new browser window/tab.
func DisplayMarkdownInBrowser(markdown []byte) {
	stopServerChan := make(chan struct{})

	handler := func(w http.ResponseWriter, req *http.Request) {
		gfmutil.WriteGitHubFlavoredMarkdownViaLocal(w, markdown)

		// TODO: A better way to fix: /assets/gfm/gfm.css Failed to load resource: net::ERR_CONNECTION_REFUSED.
		// HACK: Give some time for other assets to finish loading.
		go func() {
			time.Sleep(1 * time.Second)
			stopServerChan <- struct{}{}
		}()
	}

	http.HandleFunc("/index", handler)
	http.Handle("/assets/gfm/", http.StripPrefix("/assets/gfm", http.FileServer(gfmstyle.Assets))) // Serve the "/assets/gfm/gfm.css" file.
	http.Handle("/favicon.ico", http.NotFoundHandler())

	// TODO: Aquire a free port similarly to using ioutil.TempFile() for files.
	// TODO: Consider using httptest.NewServer.
	open.Open("http://localhost:7044/index")

	err := httpstoppable۰ListenAndServe("localhost:7044", nil, stopServerChan)
	if err != nil {
		panic(err)
	}
}

// DisplayHTMLInBrowser displays given html page in a new browser window/tab.
// query can be empty, otherwise it should begin with "?" like "?key=value".
func DisplayHTMLInBrowser(mux *http.ServeMux, stopServerChan <-chan struct{}, query string) {
	// TODO: Aquire a free port similarly to using ioutil.TempFile() for files.
	open.Open("http://localhost:7044/index" + query)

	err := httpstoppable۰ListenAndServe("localhost:7044", mux, stopServerChan)
	if err != nil {
		panic(err)
	}
}

// ListenAndServe listens on the TCP network address addr
// and then calls Serve with handler to handle requests
// on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// Handler is typically nil, in which case the http.DefaultServeMux is
// used.
//
// When receiving from stop unblocks (because it's closed or a value is sent),
// listener is closed and ListenAndServe returns with nil error.
// Otherise, it always returns a non-nil error.
//
// Deprecated: Go 1.8 added native support for stopping a server in net/http.
// net/http should be used instead. This copied function will be removed soon.
func httpstoppable۰ListenAndServe(addr string, handler http.Handler, stop <-chan struct{}) error {
	srv := &http.Server{Addr: addr, Handler: handler}
	if addr == "" {
		addr = ":http"
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	go func() {
		<-stop
		err := ln.Close()
		if err != nil {
			log.Println("httpstoppable.ListenAndServe: error closing listener:", err)
		}
	}()
	err = srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
	switch { // Serve always returns a non-nil error.
	case strings.Contains(err.Error(), "use of closed network connection"):
		return nil
	default:
		return err
	}
}

// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe so dead TCP connections
// (e.g. closing laptop mid-download) eventually go away.
type tcpKeepAliveListener struct {
	*net.TCPListener
}

func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
	tc, err := ln.AcceptTCP()
	if err != nil {
		return
	}
	tc.SetKeepAlive(true)
	tc.SetKeepAlivePeriod(3 * time.Minute)
	return tc, nil
}


text: yarn run test-update


text:
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

class Base {

  interface Seq<E> extends Iterable<E> {
    static <E> Seq<E> of(Iterable<? extends E> source) {
      return null;
    }

    <R> Seq<R> map(Function<? super E, ? extends R> mapper);
  }

}

class Test3 extends Base {

  static void test3(Seq<String[]> many) {
    Seq<Seq<String>> mapped = many.map(Arrays::asList).map(Seq::of);
    Seq<Seq<String>> mappedL = many.map(Arrays::asList).map(list -> Seq.of(list));
  }

  public static <T> List<T> asList(T[] a) {
    return null;
  }
}


text:
'''
A script to plot files with data in [x, y, z, v1, v2, ..., vn] format.

Author: Mikko Auvinen, Department of Applied Mechanics, Aalto University

Example usage: (1) Place in your $HOME/bin directory (with plotTools.py) and make it an executable.
  (2) Run the script in the directory where you have the data files with an optional file search string:
   cuniplot.py [optional str, default="."]
'''

import sys
import matplotlib.pyplot as plt
import argparse
from utilities import filesFromList
from plotTools import plotDY, userLabels

# = = = MAIN PROGRAM = = = = =

parser = argparse.ArgumentParser()
parser.add_argument("strKey", help="Search string for collecting files.",\
    default=None)
parser.add_argument("-d","--dim", nargs=1, help="No. of spatial dimensions.", type=int,\
    action="store", default=3)
parser.add_argument("--labels", help="User specified labels.", action="store_true",\
    default=False)
parser.add_argument("--yx", help="Transpose x and y axes.", action="store_true",\
    default=False)

try:
  args = parser.parse_args()
except:
  args = parser.parse_args([0])   # Send strKey=0
  args.strKey = raw_input(" Enter search string: ")
  if( not args.strKey ): sys.exit(1)

plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=16)

while 1:

  fileNos, fileList = filesFromList( args.strKey )

  pfig = plt.figure(num=1, figsize=(8.,8.));
  for fn in fileNos:
    pfig = plotDY( pfig, fileList[fn], args.dim, args.yx )

  if( args.labels):
    pfig = userLabels( pfig )
  plt.grid(True)
  plt.legend(loc=0)

  plt.show()


text:
package vtools.dataModel.expression;

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

import org.apache.log4j.Logger;
import org.vagabond.benchmark.model.IdGen;

import vtools.visitor.Visitable;
import vtools.visitor.Visitor;

public class SPJQuery extends Query implements Visitable, Cloneable, Trampable
{
	static Logger log = Logger.getLogger(SPJQuery.class);

    private int _top;

    private boolean _distinct;

    private SelectClauseList _select;

    private FromClauseList _from;

    private BooleanExpression _where;

    private Vector<Projection> _groupby;

    private Path _into;

    // determines whether the from clause will have joins or commas
    private boolean _withJOINS;

    private ArrayList<String> _targets = new ArrayList<String>();

    private ArrayList<String> _sources = new ArrayList<String>();

    public SPJQuery()
    {
        _select = new SelectClauseList();
        _from = new FromClauseList();
        _where = null;
        _groupby = new Vector<Projection>();
        _top = -1;
        _distinct = false;
        _withJOINS = true;
        _into = null;
    }

    public SPJQuery(String stringExpr)
    {
        // SOS TO BE CHECKED BY YANNIS
        // SQLQueryParser parser = new SQLQueryParser();
        // SPJQuery spjquery = (SPJQuery) parser.parse(stringExpr);
        // _select = spjquery._select;
        // _from = spjquery._from;
        // _where = spjquery._where;
        // _top = spjquery._top;
        // _distinct = spjquery._distinct;
        // _withJOINS = spjquery._withJOINS;
        // _into = spjquery._into;
    }

    public void setSelect(SelectClauseList sel)
    {
        _select = sel;
    }

    public SelectClauseList getSelect()
    {
        return _select;
    }

    public boolean isDistinct()
    {
        return _distinct;
    }

    public void setDistinct(boolean distinct)
    {
        _distinct = distinct;
    }

    public int getTop()
    {
        return _top;
    }

    public void setTop(int top)
    {
        _top = top;
    }

    public Path getIntoSpec()
    {
        return _into;
    }

    public void setIntoTable(Path into)
    {
        _into = into;
    }

    public FromClauseList getFrom()
    {
        return _from;
    }

    public void setFrom(FromClauseList from)
    {
        _from = from;
    }

    public BooleanExpression getWhere()
    {
        return _where;
    }

    public void setWhere(BooleanExpression where)
    {
        _where = where;
    }

    public void addAndInWhere(BooleanExpression cond)
    {
        if (cond == null)
            return;
        else if (_where == null)
            _where = cond;
        else if (_where instanceof AND)
            ((AND) _where).add(cond);
        else
        {
            AND and;
            if (cond instanceof AND)
            {
                and = (AND) cond;
                and.add(_where);
            }
            else
            {
                and = new AND();
                and.add(_where);
                and.add(cond);
            }
            _where = and;
        }
    }

    public void addGroupByTerm(Projection term)
    {
        _groupby.add(term);
    }

    public Projection getGroupByTerm(int position)
    {
        return _groupby.elementAt(position);
    }

    public int getGroupBySize()
    {
        return _groupby.size();
    }

    public Vector<Projection> getGroupBys () {
    	return _groupby;
    }

    public SPJQuery clone()
    {
        SPJQuery spj = (SPJQuery) super.clone();
        spj._from = new FromClauseList();
        for (int i = 0, imax = _from.size(); i < imax; i++)
        {
            Variable key = ((Variable) _from.getKey(i)).clone();
            Expression val = ((Expression) _from.getValue(i)).clone();
            spj._from.add(key, val);
        }
        spj._select = new SelectClauseList();
        for (int i = 0, imax = _select.size(); i < imax; i++)
        {
            String key = new String((String) _select.getKey(i));
            Expression val = ((Expression) _select.getValue(i)).clone();
            spj._select.add(key, val);
        }
        spj._where = (_where == null) ? null : (BooleanExpression) _where.clone();
        spj._top = _top;
        spj._distinct = _distinct;
        spj._withJOINS = _withJOINS;
        spj._into = (_into == null) ? null : _into.clone();
        int size_grpby = _groupby.size();
        spj._groupby = new Vector<Projection>(size_grpby);
        for (int i = 0; i < size_grpby; i++)
            spj._groupby.add((Projection) _groupby.elementAt(i).clone());
        return spj;
    }

    public boolean equals(Object o)
    {
        if (!(o instanceof SPJQuery))
            return false;
        if (!super.equals(o))
            return false;
        SPJQuery spj = (SPJQuery) o;
        if (_from.size() != spj._from.size())
            return false;
        for (int i = 0, imax = _from.size(); i < imax; i++)
        {
            Variable key = spj._from.getExprVar(i);
            Expression val = spj._from.getExpression(i);
            if (!(_from.getKey(i).equals(key)))
                return false;
            if (!(_from.getValue(i).equals(val)))
                return false;
        }
        if (_select.size() != spj._select.size())
            return false;
        for (int i = 0, imax = _select.size(); i < imax; i++)
        {
            String key = spj._select.getTermName(i);
            Expression val = spj._select.getTerm(i);
            if (!(_select.getKey(i).equals(key)))
                return false;
            if (!(_select.getValue(i).equals(val)))
                return false;
        }
        if (!(_where.equals(spj._where)))
            return false;
        if (_top != spj._top)
            return false;
        if (_distinct != spj._distinct)
            return false;
        if (_withJOINS != spj._withJOINS)
            return false;
        if (_into.equals(spj._into))
            return false;
        if (_groupby.size() != spj._groupby.size())
            return false;
        for (int i = 0, imax = _groupby.size(); i < imax; i++)
        {
            Projection p = (Projection) spj._groupby.elementAt(i);
            if (!(_groupby.get(i).equals(p)))
                return false;
        }
        return true;
    }

    public Visitor getPrintVisitor()
    {
        return StringPrinter.StringPrinter;
    }

    public void addTarget(String t) {
    	_targets.add(t);
    }

    public String getTarget(int i) {
    	return _targets.get(i);
    }

    public ArrayList<String> getTargets() {
    	return _targets;
    }

    public void addSource(String t) {
    	_sources.add(t);
    }

    public String getSource(int i) {
    	return _sources.get(i);
    }

    public ArrayList<String> getSources() {
    	return _sources;
    }

//	@Override
//	public String toTrampString(IdGen idGen) throws Exception {
//		StringBuffer result = new StringBuffer();
//		List<String> attrs, rels;
//		attrs = new ArrayList<String> ();
//		rels = new ArrayList<String> ();
//
//		result.append("SELECT ");
//
//		if (isDistinct())
//			result.append(" DISTINCT ");
//
//		for (int i = 0; i < _select.size(); i++) {
//			String expr = _select.getValue(i).toString().toLowerCase();
//			expr = expr.replace("/", ".").replace("$", "");
//			String name = _select.getKey(i).toString().toLowerCase();
//			String attrString = expr + " AS " + name;
//			attrs.add(name);
//
//			result.append(attrString);
//			if (i != _select.size() - 1)
//				result.append(", ");
//			if (log.isDebugEnabled()) {log.debug("Add attr " + attrString);};
//		}
//
//		if (_from.size() > 0) {
//			result.append("\nFROM ");
//			for (int i = 0; i < _from.size(); i++) {
//				// check whether we have a subquery or a relation
//				Object fromItem = _from.getValue(i);
//
//				if (fromItem instanceof Query) {
//					String subQuery = ""; // keep compiler quiet
//
//					if (fromItem instanceof SPJQuery) {
//						SPJQuery spj = (SPJQuery) fromItem;
//						subQuery = spj.toTrampString(idGen);
//					}
//					else if (fromItem instanceof SetOperation) {
//						SetOperation setOp = (SetOperation) fromItem;
//						subQuery = setOp.toTrampString(idGen);
//					}
//					else
//						throw new Exception("Unkown subquery type " + fromItem.getClass());
//
//					subQuery = "(" + subQuery + ")";
//
//					String key = _from.getKey(i).toString();
//					key = key.substring(1).toLowerCase();
//					String relCode;
//
//
//					relCode = subQuery + " AS " + key;
//					result.append(relCode);
//				}
//				else if (fromItem instanceof Projection) {
//					String key = _from.getKey(i).toString();
//					key = key.substring(1).toLowerCase();
//					String relName = _from.getValue(i).toString().toLowerCase();
//					relName = "source." + relName.substring(1); // remove the first "/"
//					String relCode = relName + " ANNOT('${" + idGen.getNextId() + "}') AS " + key;
//					rels.add(relName);
//
//					result.append(relCode);
//					if (i != _from.size() - 1)
//						result.append(", ");
//				}
//				else {
//					throw new Exception("unkown from clause element " + fromItem.getClass());
//				}
//			}
//		}
//
//		if (_where != null) {
//			result.append("\nWHERE ");
//
//			String where = _where.toString();
//
//			// find R.A patterns in where clause and lowercase them
//			where = where.replaceAll("\\$(\\w*)/", "$1.");
//			where = where.toLowerCase();
//			where = where.replace("and", "AND");
//			//TODO check if ok with string consts
//
//			result.append(where);
//		}
//
//		if (_groupby.size() != 0) {
//			result.append("\nGROUP BY ");
//
//			String group = "";
//
//			for(int i = 0; i < _groupby.size(); i++) {
//				Projection p = _groupby.get(i);
//				String grExpr = p.toString().toLowerCase();
//
//				if (i != _groupby.size() - 1)
//					grExpr += ", ";
//				group += grExpr;
//			}
//			group = group.replaceAll("\\$(\\w*)/", "$1.");
//			group = group.toLowerCase();
//
//			result.append(group);
//		}
//
//		if (log.isDebugEnabled()) {log.debug(result);};
//		return result.toString();
//    }
//
//	@Override
//	public String toTrampStringOneMap(String mapping) throws Exception {
//		String result = toTrampString();
//		for(int i = 0; i < getNumberOfLeafs(); i++) {
//			result = result.replace("${" + i + "}", mapping);
//		}
//		return result;
//	}

	public int getNumberOfLeafs () {
		int numLeafs = 0;
		for(int i = 0; i < _from.size(); i++) {
			Object fromItem = _from.getValue(i);

			if (fromItem instanceof Query)
				numLeafs += ((Query) fromItem).getNumberOfLeafs();
			if (fromItem instanceof Projection)
				numLeafs++;
		}

		return numLeafs;
	}

}


text:
// Copyright 2018 Restify. All rights reserved.

'use strict';

var assert = require('assert-plus');

///--- API

/**
 * This plugin creates `req.set(key, val)` and `req.get(key)` methods for
 * setting and retrieving request specific data.
 *
 * @public
 * @function context
 * @returns {Function} Handler
 * @example
 * server.pre(restify.plugins.pre.context());
 * server.get('/', [
 *     function(req, res, next) {
 *         req.set(myMessage, 'hello world');
 *         return next();
 *     },
 *     function two(req, res, next) {
 *         res.send(req.get(myMessage)); // => sends 'hello world'
 *         return next();
 *     }
 * ]);
 */
function ctx() {
    return function context(req, res, next) {
        var data = {};

        /**
         * Set context value by key
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.set
         * @param    {String} key - key
         * @param    {*} value - value
         * @returns  {undefined} no return value
         */
        req.set = function set(key, value) {
            assert.string(key, 'key must be string');

            if (key === '') {
                assert.fail('key must not be empty string');
            }
            data[key] = value;
        };

        /**
         * Get context value by key.
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.get
         * @param    {String} key - key
         * @returns  {*} value stored in context
         */
        req.get = function get(key) {
            assert.string(key, 'key must be string');

            if (key === '') {
                assert.fail('key must not be empty string');
            }
            return data[key];
        };

        /**
         * Get all context
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.getAll
         * @returns  {*} value stored in context
         */
        req.getAll = function getAll() {
            return data;
        };

        return next();
    };
}

///--- Exports

module.exports = ctx;


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:id="@+id/action_environment_local" android:title="Local"/>
	<item android:id="@+id/action_environment_development" android:title="Development"/>
	<item android:id="@+id/action_environment_uat" android:title="UAT"/>
</menu>


text:
<!doctype html>

{% include head.html %}

{% include navigation.html %}

    {% if page.image.feature %}
{% if page.image.title %}
{{ page.image.title }}
{% endif %}
{% endif %}

        {{ content }}

    {% include footer.html %}

{% include scripts.html %}