text:
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBClientError
from decouple import config
import random
import datetime

random.seed(100)

class InfluxDBPayload(object):

    HOST = config('INFLUXDB_HOST', default='localhost')
    PORT = config('INFLUXDB_PORT', default=8086, cast=int)

    ADMIN_USER = config('INFLUXDB_ADMIN_USER', default='root')
    ADMIN_PASSWORD = config('INFLUXDB_ADMIN_PASSWORD', default='root')

    DB_USER = config('INFLUXDB_DB_USER', default='influxdb_user')
    DB_PASSWORD = config('INFLUXDB_DB_PASSWORD', default='influxdb_password')
    DB_NAME = config('INFLUXDB_DB_NAME', default='exemplo')

    @property
    def client(self):
        if not hasattr(self, '_client'):
            self._client = InfluxDBClient(
                self.HOST, self.PORT, self.ADMIN_USER, self.ADMIN_PASSWORD,
                self.DB_NAME)
        return self._client

    def demo(self):
        npoints = 10000

        for point in xrange(npoints):
            measure = random.randint(1, 10)
            host = random.randint(1, 10)
            json_body = [
                {
                    "measurement": "mea-{0}".format(str(measure)),
                    "tags": {
                        "host": "server-{0}".format(str(host)),
                        "region": "us-west"
                    },
                    "time": datetime.datetime.isoformat(
                        datetime.datetime.utcnow()),
                    "fields": {
                        "value": random.random()
                    }
                }
            ]

            self.client.write_points(json_body)

if __name__ == '__main__':
    ifdb = InfluxDBPayload()

    query = 'SELECT value FROM mea;'

    json_body = [
        {
            "measurement": "mea",
            "tags": {
                "host": "server01",
                "region": "us-west"
            },
            "time": "2009-11-10T23:00:00Z",
            "fields": {
                "value": 0.64
            }
        }
    ]

    try:
        print("Create database: " + ifdb.DB_NAME)
        ifdb.client.create_database(ifdb.DB_NAME)
    except InfluxDBClientError:
        pass

    try:
        print("Create a retention policy")
        ifdb.client.create_retention_policy('awesome_policy', '3d', 3,
                                            default=True)
    except InfluxDBClientError:
        pass

    print("Switch user: " + ifdb.DB_USER)
    ifdb.client.switch_user(ifdb.DB_USER, ifdb.DB_PASSWORD)

    print("Write points: {0}".format(json_body))
    ifdb.client.write_points(json_body)

    ifdb.demo()

    print("Queying data: " + query)
    result = ifdb.client.query(query)

    print("Result: {0}".format(result))

    print("Switch user: " + ifdb.ADMIN_USER)
    ifdb.client.switch_user(ifdb.ADMIN_USER, ifdb.ADMIN_PASSWORD)

    if config('DROP_DATABASE', default=False, cast=bool):
        print("Drop database: " + ifdb.DB_NAME)
        ifdb.client.drop_database(ifdb.DB_NAME)


text:
require 'spec_helper'

# Shared examples for a resource inside a Project
#
# By default it tests all the default REST actions: index, create, new, edit,
# show, update, and destroy. You can remove actions by customizing the
# `actions` variable.
#
# It also expects a `controller` variable to be available which defines both
# the path to the resource as well as the controller name.
#
# Examples
#
#   # Default behavior
#   it_behaves_like 'RESTful project resources' do
#     let(:controller) { 'issues' }
#   end
#
#   # Customizing actions
#   it_behaves_like 'RESTful project resources' do
#     let(:actions)    { [:index] }
#     let(:controller) { 'issues' }
#   end
shared_examples 'RESTful project resources' do
  let(:actions) { [:index, :create, :new, :edit, :show, :update, :destroy] }

  it 'to #index' do
    get("/gitlab/gitlabhq/#{controller}").should route_to("projects/#{controller}#index", project_id: 'gitlab/gitlabhq') if actions.include?(:index)
  end

  it 'to #create' do
    post("/gitlab/gitlabhq/#{controller}").should route_to("projects/#{controller}#create", project_id: 'gitlab/gitlabhq') if actions.include?(:create)
  end

  it 'to #new' do
    get("/gitlab/gitlabhq/#{controller}/new").should route_to("projects/#{controller}#new", project_id: 'gitlab/gitlabhq') if actions.include?(:new)
  end

  it 'to #edit' do
    get("/gitlab/gitlabhq/#{controller}/1/edit").should route_to("projects/#{controller}#edit", project_id: 'gitlab/gitlabhq', id: '1') if actions.include?(:edit)
  end

  it 'to #show' do
    get("/gitlab/gitlabhq/#{controller}/1").should route_to("projects/#{controller}#show", project_id: 'gitlab/gitlabhq', id: '1') if actions.include?(:show)
  end

  it 'to #update' do
    put("/gitlab/gitlabhq/#{controller}/1").should route_to("projects/#{controller}#update", project_id: 'gitlab/gitlabhq', id: '1') if actions.include?(:update)
  end

  it 'to #destroy' do
    delete("/gitlab/gitlabhq/#{controller}/1").should route_to("projects/#{controller}#destroy", project_id: 'gitlab/gitlabhq', id: '1') if actions.include?(:destroy)
  end
end

#                 projects POST   /projects(.:format)     projects#create
#              new_project GET    /projects/new(.:format) projects#new
#            files_project GET    /:id/files(.:format)    projects#files
#             edit_project GET    /:id/edit(.:format)     projects#edit
#                  project GET    /:id(.:format)          projects#show
#                          PUT    /:id(.:format)          projects#update
#                          DELETE /:id(.:format)          projects#destroy
# markdown_preview_project POST   /:id/markdown_preview(.:format) projects#markdown_preview
describe ProjectsController, 'routing' do
  it 'to #create' do
    post('/projects').should route_to('projects#create')
  end

  it 'to #new' do
    get('/projects/new').should route_to('projects#new')
  end

  it 'to #edit' do
    get('/gitlab/gitlabhq/edit').should route_to('projects#edit', id: 'gitlab/gitlabhq')
  end

  it 'to #autocomplete_sources' do
    get('/gitlab/gitlabhq/autocomplete_sources').should route_to('projects#autocomplete_sources', id: 'gitlab/gitlabhq')
  end

  it 'to #show' do
    get('/gitlab/gitlabhq').should route_to('projects#show', id: 'gitlab/gitlabhq')
  end

  it 'to #update' do
    put('/gitlab/gitlabhq').should route_to('projects#update', id: 'gitlab/gitlabhq')
  end

  it 'to #destroy' do
    delete('/gitlab/gitlabhq').should route_to('projects#destroy', id: 'gitlab/gitlabhq')
  end

  it 'to #markdown_preview' do
    post('/gitlab/gitlabhq/markdown_preview').should(
      route_to('projects#markdown_preview', id: 'gitlab/gitlabhq')
    )
  end
end

#  pages_project_wikis GET    /:project_id/wikis/pages(.:format)       projects/wikis#pages
# history_project_wiki GET    /:project_id/wikis/:id/history(.:format) projects/wikis#history
#        project_wikis POST   /:project_id/wikis(.:format)             projects/wikis#create
#    edit_project_wiki GET    /:project_id/wikis/:id/edit(.:format)    projects/wikis#edit
#         project_wiki GET    /:project_id/wikis/:id(.:format)         projects/wikis#show
#                      DELETE /:project_id/wikis/:id(.:format)         projects/wikis#destroy
describe Projects::WikisController, 'routing' do
  it 'to #pages' do
    get('/gitlab/gitlabhq/wikis/pages').should route_to('projects/wikis#pages', project_id: 'gitlab/gitlabhq')
  end

  it 'to #history' do
    get('/gitlab/gitlabhq/wikis/1/history').should route_to('projects/wikis#history', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:create, :edit, :show, :destroy] }
    let(:controller) { 'wikis' }
  end
end

# branches_project_repository GET    /:project_id/repository/branches(.:format) projects/repositories#branches
#     tags_project_repository GET    /:project_id/repository/tags(.:format)     projects/repositories#tags
#  archive_project_repository GET    /:project_id/repository/archive(.:format)  projects/repositories#archive
#     edit_project_repository GET    /:project_id/repository/edit(.:format)     projects/repositories#edit
describe Projects::RepositoriesController, 'routing' do
  it 'to #archive' do
    get('/gitlab/gitlabhq/repository/archive').should route_to('projects/repositories#archive', project_id: 'gitlab/gitlabhq')
  end

  it 'to #archive format:zip' do
    get('/gitlab/gitlabhq/repository/archive.zip').should route_to('projects/repositories#archive', project_id: 'gitlab/gitlabhq', format: 'zip')
  end

  it 'to #archive format:tar.bz2' do
    get('/gitlab/gitlabhq/repository/archive.tar.bz2').should route_to('projects/repositories#archive', project_id: 'gitlab/gitlabhq', format: 'tar.bz2')
  end

  it 'to #show' do
    get('/gitlab/gitlabhq/repository').should route_to('projects/repositories#show', project_id: 'gitlab/gitlabhq')
  end
end

describe Projects::BranchesController, 'routing' do
  it 'to #branches' do
    get('/gitlab/gitlabhq/branches').should route_to('projects/branches#index', project_id: 'gitlab/gitlabhq')
    delete('/gitlab/gitlabhq/branches/feature%2345').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature#45')
    delete('/gitlab/gitlabhq/branches/feature%2B45').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature+45')
    delete('/gitlab/gitlabhq/branches/feature@45').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature@45')
    delete('/gitlab/gitlabhq/branches/feature%2345/foo/bar/baz').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature#45/foo/bar/baz')
    delete('/gitlab/gitlabhq/branches/feature%2B45/foo/bar/baz').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature+45/foo/bar/baz')
    delete('/gitlab/gitlabhq/branches/feature@45/foo/bar/baz').should route_to('projects/branches#destroy', project_id: 'gitlab/gitlabhq', id: 'feature@45/foo/bar/baz')
  end
end

describe Projects::TagsController, 'routing' do
  it 'to #tags' do
    get('/gitlab/gitlabhq/tags').should route_to('projects/tags#index', project_id: 'gitlab/gitlabhq')
    delete('/gitlab/gitlabhq/tags/feature%2345').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature#45')
    delete('/gitlab/gitlabhq/tags/feature%2B45').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature+45')
    delete('/gitlab/gitlabhq/tags/feature@45').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature@45')
    delete('/gitlab/gitlabhq/tags/feature%2345/foo/bar/baz').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature#45/foo/bar/baz')
    delete('/gitlab/gitlabhq/tags/feature%2B45/foo/bar/baz').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature+45/foo/bar/baz')
    delete('/gitlab/gitlabhq/tags/feature@45/foo/bar/baz').should route_to('projects/tags#destroy', project_id: 'gitlab/gitlabhq', id: 'feature@45/foo/bar/baz')
  end
end

#     project_deploy_keys GET    /:project_id/deploy_keys(.:format)          deploy_keys#index
#                         POST   /:project_id/deploy_keys(.:format)          deploy_keys#create
#  new_project_deploy_key GET    /:project_id/deploy_keys/new(.:format)      deploy_keys#new
# edit_project_deploy_key GET    /:project_id/deploy_keys/:id/edit(.:format) deploy_keys#edit
#      project_deploy_key GET    /:project_id/deploy_keys/:id(.:format)      deploy_keys#show
#                         PUT    /:project_id/deploy_keys/:id(.:format)      deploy_keys#update
#                         DELETE /:project_id/deploy_keys/:id(.:format)      deploy_keys#destroy
describe Projects::DeployKeysController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:controller) { 'deploy_keys' }
  end
end

# project_protected_branches GET    /:project_id/protected_branches(.:format)     protected_branches#index
#                            POST   /:project_id/protected_branches(.:format)     protected_branches#create
#   project_protected_branch DELETE /:project_id/protected_branches/:id(.:format) protected_branches#destroy
describe Projects::ProtectedBranchesController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:index, :create, :destroy] }
    let(:controller) { 'protected_branches' }
  end
end

#    switch_project_refs GET    /:project_id/refs/switch(.:format)              refs#switch
#  logs_tree_project_ref GET    /:project_id/refs/:id/logs_tree(.:format)       refs#logs_tree
#  logs_file_project_ref GET    /:project_id/refs/:id/logs_tree/:path(.:format) refs#logs_tree
describe Projects::RefsController, 'routing' do
  it 'to #switch' do
    get('/gitlab/gitlabhq/refs/switch').should route_to('projects/refs#switch', project_id: 'gitlab/gitlabhq')
  end

  it 'to #logs_tree' do
    get('/gitlab/gitlabhq/refs/stable/logs_tree').should             route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'stable')
    get('/gitlab/gitlabhq/refs/feature%2345/logs_tree').should             route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature#45')
    get('/gitlab/gitlabhq/refs/feature%2B45/logs_tree').should             route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature+45')
    get('/gitlab/gitlabhq/refs/feature@45/logs_tree').should             route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature@45')
    get('/gitlab/gitlabhq/refs/stable/logs_tree/foo/bar/baz').should route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'stable', path: 'foo/bar/baz')
    get('/gitlab/gitlabhq/refs/feature%2345/logs_tree/foo/bar/baz').should route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature#45', path: 'foo/bar/baz')
    get('/gitlab/gitlabhq/refs/feature%2B45/logs_tree/foo/bar/baz').should route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature+45', path: 'foo/bar/baz')
    get('/gitlab/gitlabhq/refs/feature@45/logs_tree/foo/bar/baz').should route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'feature@45', path: 'foo/bar/baz')
    get('/gitlab/gitlabhq/refs/stable/logs_tree/files.scss').should route_to('projects/refs#logs_tree', project_id: 'gitlab/gitlabhq', id: 'stable', path: 'files.scss')
  end
end

#           diffs_project_merge_request GET    /:project_id/merge_requests/:id/diffs(.:format)           projects/merge_requests#diffs
#       automerge_project_merge_request POST   /:project_id/merge_requests/:id/automerge(.:format)       projects/merge_requests#automerge
# automerge_check_project_merge_request GET    /:project_id/merge_requests/:id/automerge_check(.:format) projects/merge_requests#automerge_check
#    branch_from_project_merge_requests GET    /:project_id/merge_requests/branch_from(.:format)         projects/merge_requests#branch_from
#      branch_to_project_merge_requests GET    /:project_id/merge_requests/branch_to(.:format)           projects/merge_requests#branch_to
#                project_merge_requests GET    /:project_id/merge_requests(.:format)                     projects/merge_requests#index
#                                       POST   /:project_id/merge_requests(.:format)                     projects/merge_requests#create
#             new_project_merge_request GET    /:project_id/merge_requests/new(.:format)                 projects/merge_requests#new
#            edit_project_merge_request GET    /:project_id/merge_requests/:id/edit(.:format)            projects/merge_requests#edit
#                 project_merge_request GET    /:project_id/merge_requests/:id(.:format)                 projects/merge_requests#show
#                                       PUT    /:project_id/merge_requests/:id(.:format)                 projects/merge_requests#update
#                                       DELETE /:project_id/merge_requests/:id(.:format)                 projects/merge_requests#destroy
describe Projects::MergeRequestsController, 'routing' do
  it 'to #diffs' do
    get('/gitlab/gitlabhq/merge_requests/1/diffs').should route_to('projects/merge_requests#diffs', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #automerge' do
    post('/gitlab/gitlabhq/merge_requests/1/automerge').should route_to(
      'projects/merge_requests#automerge',
      project_id: 'gitlab/gitlabhq', id: '1'
    )
  end

  it 'to #automerge_check' do
    get('/gitlab/gitlabhq/merge_requests/1/automerge_check').should route_to('projects/merge_requests#automerge_check', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #branch_from' do
    get('/gitlab/gitlabhq/merge_requests/branch_from').should route_to('projects/merge_requests#branch_from', project_id: 'gitlab/gitlabhq')
  end

  it 'to #branch_to' do
    get('/gitlab/gitlabhq/merge_requests/branch_to').should route_to('projects/merge_requests#branch_to', project_id: 'gitlab/gitlabhq')
  end

  it 'to #show' do
    get('/gitlab/gitlabhq/merge_requests/1.diff').should route_to('projects/merge_requests#show', project_id: 'gitlab/gitlabhq', id: '1', format: 'diff')
    get('/gitlab/gitlabhq/merge_requests/1.patch').should route_to('projects/merge_requests#show', project_id: 'gitlab/gitlabhq', id: '1', format: 'patch')
  end

  it_behaves_like 'RESTful project resources' do
    let(:controller) { 'merge_requests' }
    let(:actions) { [:index, :create, :new, :edit, :show, :update] }
  end
end

#  raw_project_snippet GET    /:project_id/snippets/:id/raw(.:format)  snippets#raw
#     project_snippets GET    /:project_id/snippets(.:format)          snippets#index
#                      POST   /:project_id/snippets(.:format)          snippets#create
#  new_project_snippet GET    /:project_id/snippets/new(.:format)      snippets#new
# edit_project_snippet GET    /:project_id/snippets/:id/edit(.:format) snippets#edit
#      project_snippet GET    /:project_id/snippets/:id(.:format)      snippets#show
#                      PUT    /:project_id/snippets/:id(.:format)      snippets#update
#                      DELETE /:project_id/snippets/:id(.:format)      snippets#destroy
describe SnippetsController, 'routing' do
  it 'to #raw' do
    get('/gitlab/gitlabhq/snippets/1/raw').should route_to('projects/snippets#raw', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #index' do
    get('/gitlab/gitlabhq/snippets').should route_to('projects/snippets#index', project_id: 'gitlab/gitlabhq')
  end

  it 'to #create' do
    post('/gitlab/gitlabhq/snippets').should route_to('projects/snippets#create', project_id: 'gitlab/gitlabhq')
  end

  it 'to #new' do
    get('/gitlab/gitlabhq/snippets/new').should route_to('projects/snippets#new', project_id: 'gitlab/gitlabhq')
  end

  it 'to #edit' do
    get('/gitlab/gitlabhq/snippets/1/edit').should route_to('projects/snippets#edit', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #show' do
    get('/gitlab/gitlabhq/snippets/1').should route_to('projects/snippets#show', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #update' do
    put('/gitlab/gitlabhq/snippets/1').should route_to('projects/snippets#update', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it 'to #destroy' do
    delete('/gitlab/gitlabhq/snippets/1').should route_to('projects/snippets#destroy', project_id: 'gitlab/gitlabhq', id: '1')
  end
end

# test_project_hook GET    /:project_id/hooks/:id/test(.:format) hooks#test
#     project_hooks GET    /:project_id/hooks(.:format)          hooks#index
#                   POST   /:project_id/hooks(.:format)          hooks#create
#      project_hook DELETE /:project_id/hooks/:id(.:format)      hooks#destroy
describe Projects::HooksController, 'routing' do
  it 'to #test' do
    get('/gitlab/gitlabhq/hooks/1/test').should route_to('projects/hooks#test', project_id: 'gitlab/gitlabhq', id: '1')
  end

  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:index, :create, :destroy] }
    let(:controller) { 'hooks' }
  end
end

# project_commit GET    /:project_id/commit/:id(.:format) commit#show {id: /[[:alnum:]]{6,40}/, project_id: /[^\/]+/}
describe Projects::CommitController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/commit/4246fb').should route_to('projects/commit#show', project_id: 'gitlab/gitlabhq', id: '4246fb')
    get('/gitlab/gitlabhq/commit/4246fb.diff').should route_to('projects/commit#show', project_id: 'gitlab/gitlabhq', id: '4246fb', format: 'diff')
    get('/gitlab/gitlabhq/commit/4246fb.patch').should route_to('projects/commit#show', project_id: 'gitlab/gitlabhq', id: '4246fb', format: 'patch')
    get('/gitlab/gitlabhq/commit/4246fbd13872934f72a8fd0d6fb1317b47b59cb5').should route_to('projects/commit#show', project_id: 'gitlab/gitlabhq', id: '4246fbd13872934f72a8fd0d6fb1317b47b59cb5')
  end
end

#    patch_project_commit GET    /:project_id/commits/:id/patch(.:format) commits#patch
#         project_commits GET    /:project_id/commits(.:format)           commits#index
#                         POST   /:project_id/commits(.:format)           commits#create
#          project_commit GET    /:project_id/commits/:id(.:format)       commits#show
describe Projects::CommitsController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:show] }
    let(:controller) { 'commits' }
  end

  it 'to #show' do
    get('/gitlab/gitlabhq/commits/master.atom').should route_to('projects/commits#show', project_id: 'gitlab/gitlabhq', id: 'master', format: 'atom')
  end
end

#     project_team_members GET    /:project_id/team_members(.:format)          team_members#index
#                          POST   /:project_id/team_members(.:format)          team_members#create
#  new_project_team_member GET    /:project_id/team_members/new(.:format)      team_members#new
# edit_project_team_member GET    /:project_id/team_members/:id/edit(.:format) team_members#edit
#      project_team_member GET    /:project_id/team_members/:id(.:format)      team_members#show
#                          PUT    /:project_id/team_members/:id(.:format)      team_members#update
#                          DELETE /:project_id/team_members/:id(.:format)      team_members#destroy
describe Projects::TeamMembersController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:new, :create, :update, :destroy] }
    let(:controller) { 'team_members' }
  end
end

#     project_milestones GET    /:project_id/milestones(.:format)          milestones#index
#                        POST   /:project_id/milestones(.:format)          milestones#create
#  new_project_milestone GET    /:project_id/milestones/new(.:format)      milestones#new
# edit_project_milestone GET    /:project_id/milestones/:id/edit(.:format) milestones#edit
#      project_milestone GET    /:project_id/milestones/:id(.:format)      milestones#show
#                        PUT    /:project_id/milestones/:id(.:format)      milestones#update
#                        DELETE /:project_id/milestones/:id(.:format)      milestones#destroy
describe Projects::MilestonesController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:controller) { 'milestones' }
    let(:actions) { [:index, :create, :new, :edit, :show, :update] }
  end
end

# project_labels GET    /:project_id/labels(.:format) labels#index
describe Projects::LabelsController, 'routing' do
  it 'to #index' do
    get('/gitlab/gitlabhq/labels').should route_to('projects/labels#index', project_id: 'gitlab/gitlabhq')
  end
end

#        sort_project_issues POST   /:project_id/issues/sort(.:format)        issues#sort
# bulk_update_project_issues POST   /:project_id/issues/bulk_update(.:format) issues#bulk_update
#      search_project_issues GET    /:project_id/issues/search(.:format)      issues#search
#             project_issues GET    /:project_id/issues(.:format)             issues#index
#                            POST   /:project_id/issues(.:format)             issues#create
#          new_project_issue GET    /:project_id/issues/new(.:format)         issues#new
#         edit_project_issue GET    /:project_id/issues/:id/edit(.:format)    issues#edit
#              project_issue GET    /:project_id/issues/:id(.:format)         issues#show
#                            PUT    /:project_id/issues/:id(.:format)         issues#update
#                            DELETE /:project_id/issues/:id(.:format)         issues#destroy
describe Projects::IssuesController, 'routing' do
  it 'to #bulk_update' do
    post('/gitlab/gitlabhq/issues/bulk_update').should route_to('projects/issues#bulk_update', project_id: 'gitlab/gitlabhq')
  end

  it_behaves_like 'RESTful project resources' do
    let(:controller) { 'issues' }
    let(:actions) { [:index, :create, :new, :edit, :show, :update] }
  end
end

#         project_notes GET    /:project_id/notes(.:format)         notes#index
#                       POST   /:project_id/notes(.:format)         notes#create
#          project_note DELETE /:project_id/notes/:id(.:format)     notes#destroy
describe Projects::NotesController, 'routing' do
  it_behaves_like 'RESTful project resources' do
    let(:actions)    { [:index, :create, :destroy] }
    let(:controller) { 'notes' }
  end
end

# project_blame GET    /:project_id/blame/:id(.:format) blame#show {id: /.+/, project_id: /[^\/]+/}
describe Projects::BlameController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/blame/master/app/models/project.rb').should route_to('projects/blame#show', project_id: 'gitlab/gitlabhq', id: 'master/app/models/project.rb')
    get('/gitlab/gitlabhq/blame/master/files.scss').should route_to('projects/blame#show', project_id: 'gitlab/gitlabhq', id: 'master/files.scss')
  end
end

# project_blob GET    /:project_id/blob/:id(.:format) blob#show {id: /.+/, project_id: /[^\/]+/}
describe Projects::BlobController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/blob/master/app/models/project.rb').should route_to('projects/blob#show', project_id: 'gitlab/gitlabhq', id: 'master/app/models/project.rb')
    get('/gitlab/gitlabhq/blob/master/app/models/compare.rb').should route_to('projects/blob#show', project_id: 'gitlab/gitlabhq', id: 'master/app/models/compare.rb')
    get('/gitlab/gitlabhq/blob/master/app/models/diff.js').should route_to('projects/blob#show', project_id: 'gitlab/gitlabhq', id: 'master/app/models/diff.js')
    get('/gitlab/gitlabhq/blob/master/files.scss').should route_to('projects/blob#show', project_id: 'gitlab/gitlabhq', id: 'master/files.scss')
  end
end

# project_tree GET    /:project_id/tree/:id(.:format) tree#show {id: /.+/, project_id: /[^\/]+/}
describe Projects::TreeController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/tree/master/app/models/project.rb').should route_to('projects/tree#show', project_id: 'gitlab/gitlabhq', id: 'master/app/models/project.rb')
    get('/gitlab/gitlabhq/tree/master/files.scss').should route_to('projects/tree#show', project_id: 'gitlab/gitlabhq', id: 'master/files.scss')
  end
end

describe Projects::BlobController, 'routing' do
  it 'to #edit' do
    get('/gitlab/gitlabhq/edit/master/app/models/project.rb').should(
      route_to('projects/blob#edit',
               project_id: 'gitlab/gitlabhq',
               id: 'master/app/models/project.rb'))
  end

  it 'to #preview' do
    post('/gitlab/gitlabhq/preview/master/app/models/project.rb').should(
      route_to('projects/blob#preview',
               project_id: 'gitlab/gitlabhq',
               id: 'master/app/models/project.rb'))
  end
end

# project_compare_index GET    /:project_id/compare(.:format)             compare#index {id: /[^\/]+/, project_id: /[^\/]+/}
#                       POST   /:project_id/compare(.:format)             compare#create {id: /[^\/]+/, project_id: /[^\/]+/}
#       project_compare        /:project_id/compare/:from...:to(.:format) compare#show {from: /.+/, to: /.+/, id: /[^\/]+/, project_id: /[^\/]+/}
describe Projects::CompareController, 'routing' do
  it 'to #index' do
    get('/gitlab/gitlabhq/compare').should route_to('projects/compare#index', project_id: 'gitlab/gitlabhq')
  end

  it 'to #compare' do
    post('/gitlab/gitlabhq/compare').should route_to('projects/compare#create', project_id: 'gitlab/gitlabhq')
  end

  it 'to #show' do
    get('/gitlab/gitlabhq/compare/master...stable').should     route_to('projects/compare#show', project_id: 'gitlab/gitlabhq', from: 'master', to: 'stable')
    get('/gitlab/gitlabhq/compare/issue/1234...stable').should route_to('projects/compare#show', project_id: 'gitlab/gitlabhq', from: 'issue/1234', to: 'stable')
  end
end

describe Projects::NetworkController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/network/master').should route_to('projects/network#show', project_id: 'gitlab/gitlabhq', id: 'master')
    get('/gitlab/gitlabhq/network/master.json').should route_to('projects/network#show', project_id: 'gitlab/gitlabhq', id: 'master', format: 'json')
  end
end

describe Projects::GraphsController, 'routing' do
  it 'to #show' do
    get('/gitlab/gitlabhq/graphs/master').should route_to('projects/graphs#show', project_id: 'gitlab/gitlabhq', id: 'master')
  end
end

describe Projects::ForksController, 'routing' do
  it 'to #new' do
    get('/gitlab/gitlabhq/fork/new').should route_to('projects/forks#new', project_id: 'gitlab/gitlabhq')
  end

  it 'to #create' do
    post('/gitlab/gitlabhq/fork').should route_to('projects/forks#create', project_id: 'gitlab/gitlabhq')
  end
end

# project_avatar DELETE /project/avatar(.:format) projects/avatars#destroy
describe Projects::AvatarsController, 'routing' do
  it 'to #destroy' do
    delete('/gitlab/gitlabhq/avatar').should route_to(
      'projects/avatars#destroy', project_id: 'gitlab/gitlabhq')
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.PermissionsPolicy
{
    ///
    /// Controls access to autoplay of media requested through the
    /// HTMLMediaElement interface. If disabled in a document,
    /// then calls to play() without a user gesture will
    /// reject the promise with a NotAllowedError DOMException
    /// object as its parameter. The autoplay attribute will be ignored.
    ///
    public class AutoplayPermissionsPolicyDirectiveBuilder : PermissionsPolicyDirectiveBuilder
    {
        ///
        /// Initializes a new instance of the <see cref="AutoplayPermissionsPolicyDirectiveBuilder"/> class.
        ///
        public AutoplayPermissionsPolicyDirectiveBuilder() : base("autoplay")
        {
        }
    }
}


text:
package com.orientechnologies.orient.distributed.impl.log;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

public interface OLogRequest {
  void serialize(DataOutput output) throws IOException;

  int getRequestType();

  void deserialize(DataInput input) throws IOException;
}


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

namespace Carrotware.Web.UI.Components {

	public class PagedData<T> : PagedDataBase {

		public PagedData()
			: base() {
		}

		public void InitOrderByDescending(Expression<Func<T, Object>> field) {
			InitOrderBy(field, false);
		}

		public void InitOrderBy(Expression<Func<T, Object>> field) {
			InitOrderBy(field, true);
		}

		public void InitOrderBy(Expression<Func<T, Object>> field, bool ascending) {
			MemberExpression memberExpression = field.Body as MemberExpression ??
												((UnaryExpression)field.Body).Operand as MemberExpression;

			string columnName = memberExpression.Member.Name;

			if (ascending) {
				this.OrderBy = String.Format("{0}  ASC", columnName);
			} else {
				this.OrderBy = String.Format("{0}  DESC", columnName);
			}
		}

		public void SetData(List<T> data) {
			this.DataSource = data;
		}

		public List<T> DataSource { get; set; }

		public override bool HasData {
			get {
				return this.DataSource != null && this.DataSource.Any();
			}
		}
	}
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>tinkerpop</artifactId>
        <version>3.4.0-SNAPSHOT</version>
    </parent>
    <artifactId>gremlin-javascript</artifactId>
    <name>Apache TinkerPop :: Gremlin Javascript</name>
    <dependencies>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>gremlin-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>tinkergraph-gremlin</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>gremlin-test</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>gremlin-server</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.test.skip>false</maven.test.skip>
        <skipTests>${maven.test.skip}</skipTests>
        <gremlin.server.dir>${project.parent.basedir}/gremlin-server</gremlin.server.dir>
    </properties>
    <build>
        <directory>${basedir}/target</directory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <!--
                Use gmavenplus-plugin to:
                    - Generate js sources
                    - Start and stop gremlin server for integration tests
                -->
                <groupId>org.codehaus.gmavenplus</groupId>
                <artifactId>gmavenplus-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>log4j</groupId>
                        <artifactId>log4j</artifactId>
                        <version>1.2.17</version>
                        <scope>runtime</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.tinkerpop</groupId>
                        <artifactId>gremlin-server</artifactId>
                        <version>${project.version}</version>
                        <scope>runtime</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-ant</artifactId>
                        <version>${groovy.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>generate-javascript</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <properties>
                                <property>
                                    <name>projectBaseDir</name>
                                    <value>${project.basedir}</value>
                                </property>
                                <property>
                                    <name>projectVersion</name>
                                    <value>${project.version}</value>
                                </property>
                            </properties>
                            <scripts>
                                <script>${project.basedir}/glv/generate.groovy</script>
                            </scripts>
                        </configuration>
                    </execution>
                    <execution>
                        <id>gremlin-server-start</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <properties>
                                <property>
                                    <name>skipTests</name>
                                    <value>${skipTests}</value>
                                </property>
                                <property>
                                    <name>python</name>
                                    <value>false</value>
                                </property>
                                <property>
                                    <name>gremlinServerDir</name>
                                    <value>${gremlin.server.dir}</value>
                                </property>
                                <property>
                                    <name>settingsFile</name>
                                    <value>${gremlin.server.dir}/src/test/resources/org/apache/tinkerpop/gremlin/driver/remote/gremlin-server-integration.yaml</value>
                                </property>
                                <property>
                                    <name>executionName</name>
                                    <value>${project.name}</value>
                                </property>
                                <property>
                                    <name>projectBaseDir</name>
                                    <value>${project.basedir}</value>
                                </property>
                            </properties>
                            <scripts>
                                <script>${gremlin.server.dir}/src/test/scripts/test-server-start.groovy</script>
                            </scripts>
                        </configuration>
                    </execution>
                    <execution>
                        <id>gremlin-server-stop</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>execute</goal>
                        </goals>
                        <configuration>
                            <properties>
                                <property>
                                    <name>skipTests</name>
                                    <value>${skipTests}</value>
                                </property>
                                <property>
                                    <name>executionName</name>
                                    <value>${project.name}</value>
                                </property>
                            </properties>
                            <scripts>
                                <script>${gremlin.server.dir}/src/test/scripts/test-server-stop.groovy</script>
                            </scripts>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>clean</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <id>install node and npm</id>
                        <phase>generate-test-resources</phase>
                        <goals>
                            <goal>install-node-and-npm</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>npm install</id>
                        <phase>generate-test-resources</phase>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>
                    <execution>
                        <id>npm test</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>test</arguments>
                            <failOnError>true</failOnError>
                        </configuration>
                    </execution>
                    <execution>
                        <id>npm test gherkin features</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>run-script features</arguments>
                            <failOnError>true</failOnError>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <skip>${skipIntegrationTests}</skip>
                    <workingDirectory>src/main/javascript/gremlin-javascript</workingDirectory>
                    <nodeVersion>v6.12.3</nodeVersion>
                </configuration>
            </plugin>
            <!--
            there is no point to deploying the jvm stuff - there is no java source really - just poms
            -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <!--
        Provides a way to deploy the gremlin-javascript GLV to npm. This cannot be part of the standard maven execution
        because npm does not have a staging environment like sonatype for releases. As soon as the release is
        published it is public. In our release workflow, deploy occurs prior to vote on the release and we can't
        make this stuff public until the vote is over.
        -->
        <profile>
            <id>glv-javascript-deploy</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>1.4</version>
                        <executions>
                            <execution>
                                <id>npm publish</id>
                                <phase>deploy</phase>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <configuration>
                                    <arguments>publish</arguments>
                                </configuration>
                            </execution>
                        </executions>
                        <configuration>
                            <skip>${skipIntegrationTests}</skip>
                            <workingDirectory>src/main/javascript/gremlin-javascript</workingDirectory>
                            <nodeVersion>v6.12.3</nodeVersion>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package org.onosproject.cluster.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.google.common.io.Files;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;

import org.onosproject.cluster.ClusterMetadata;
import org.onosproject.cluster.ClusterMetadataProvider;
import org.onosproject.cluster.ClusterMetadataProviderRegistry;
import org.onosproject.cluster.ClusterMetadataProviderService;
import org.onosproject.cluster.DefaultControllerNode;
import org.onosproject.cluster.Node;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.PartitionId;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.store.service.Versioned;
import org.slf4j.Logger;

import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.onlab.util.Tools.groupedThreads;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Provider of {@link ClusterMetadata cluster metadata} sourced from a local config file.
 */
@Component(immediate = true)
public class ConfigFileBasedClusterMetadataProvider implements ClusterMetadataProvider {

    private final Logger log = getLogger(getClass());

    private static final String CONFIG_DIR = "../config";
    private static final String CONFIG_FILE_NAME = "cluster.json";
    private static final File CONFIG_FILE = new File(CONFIG_DIR, CONFIG_FILE_NAME);

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected ClusterMetadataProviderRegistry providerRegistry;

    private static final ProviderId PROVIDER_ID = new ProviderId("file", "none");
    private final AtomicReference<Versioned<ClusterMetadata>> cachedMetadata = new AtomicReference<>();
    private final ScheduledExecutorService configFileChangeDetector =
            newSingleThreadScheduledExecutor(groupedThreads("onos/cluster/metadata/config-watcher", "", log));

    private String metadataUrl;
    private ObjectMapper mapper;
    private ClusterMetadataProviderService providerService;

    @Activate
    public void activate() {
        mapper = new ObjectMapper();
        providerService = providerRegistry.register(this);
        metadataUrl = System.getProperty("onos.cluster.metadata.uri", "file://" + CONFIG_DIR + "/" + CONFIG_FILE);
        configFileChangeDetector.scheduleWithFixedDelay(() -> watchUrl(metadataUrl), 100, 500, TimeUnit.MILLISECONDS);
        log.info("Started");
    }

    @Deactivate
    public void deactivate() {
        configFileChangeDetector.shutdown();
        providerRegistry.unregister(this);
        log.info("Stopped");
    }

    @Override
    public ProviderId id() {
        return PROVIDER_ID;
    }

    @Override
    public Versioned<ClusterMetadata> getClusterMetadata() {
        checkState(isAvailable());
        synchronized (this) {
            if (cachedMetadata.get() == null) {
                cachedMetadata.set(blockForMetadata(metadataUrl));
            }
            return cachedMetadata.get();
        }
    }

    private ClusterMetadataPrototype toPrototype(ClusterMetadata metadata) {
        ClusterMetadataPrototype prototype = new ClusterMetadataPrototype();
        prototype.setName(metadata.getName());
        prototype.setController(metadata.getNodes()
                .stream()
                .map(this::toPrototype)
                .collect(Collectors.toSet()));
        prototype.setStorageDnsService(metadata.getStorageDnsService());
        prototype.setStorage(metadata.getStorageNodes()
                .stream()
                .map(this::toPrototype)
                .collect(Collectors.toSet()));
        prototype.setClusterSecret(metadata.getClusterSecret());
        return prototype;
    }

    private NodePrototype toPrototype(Node node) {
        NodePrototype prototype = new NodePrototype();
        prototype.setId(node.id().id());
        prototype.setHost(node.host());
        prototype.setPort(node.tcpPort());
        return prototype;
    }

    @Override
    public void setClusterMetadata(ClusterMetadata metadata) {
        try {
            File configFile = new File(metadataUrl.replaceFirst("file://", ""));
            Files.createParentDirs(configFile);
            ClusterMetadataPrototype metadataPrototype = toPrototype(metadata);
            mapper.writeValue(configFile, metadataPrototype);
            cachedMetadata.set(fetchMetadata(metadataUrl));
            providerService.clusterMetadataChanged(new Versioned<>(metadata, configFile.lastModified()));
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    public void addActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void removeActivePartitionMember(PartitionId partitionId, NodeId nodeId) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<NodeId> getActivePartitionMembers(PartitionId partitionId) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isAvailable() {
        try {
            URL url = new URL(metadataUrl);
            if ("file".equals(url.getProtocol())) {
                File file = new File(metadataUrl.replaceFirst("file://", ""));
                return file.exists();
            } else {
                // Return true for HTTP URLs since we allow blocking until HTTP servers come up
                return "http".equals(url.getProtocol());
            }
        } catch (Exception e) {
            log.warn("Exception accessing metadata file at {}:", metadataUrl, e);
            return false;
        }
    }

    private Versioned<ClusterMetadata> blockForMetadata(String metadataUrl) {
        long iterations = 0;
        for (;;) {
            try {
                Versioned<ClusterMetadata> metadata = fetchMetadata(metadataUrl);
                if (metadata != null) {
                    return metadata;
                }
            } catch (Exception e) {
                log.warn("Exception attempting to access metadata file at {}: {}", metadataUrl, e);
            }

            try {
                Thread.sleep((int) Math.pow(2, iterations < 7 ? ++iterations : iterations) * 10L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException(e);
            }
        }
    }

    private static NodeId getNodeId(NodePrototype node) {
        if (node.getId() != null) {
            return NodeId.nodeId(node.getId());
        } else if (node.getHost() != null) {
            return NodeId.nodeId(node.getHost());
        } else if (node.getIp() != null) {
            return NodeId.nodeId(node.getIp());
        } else {
            return NodeId.nodeId(UUID.randomUUID().toString());
        }
    }

    private static String getNodeHost(NodePrototype node) {
        if (node.getHost() != null) {
            return node.getHost();
        } else if (node.getIp() != null) {
            return node.getIp();
        } else {
            throw new IllegalArgumentException(
                "Malformed cluster configuration: No host specified for node " + node.getId());
        }
    }

    private static int getNodePort(NodePrototype node) {
        if (node.getPort() != null) {
            return node.getPort();
        }
        return DefaultControllerNode.DEFAULT_PORT;
    }

    private Versioned<ClusterMetadata> fetchMetadata(String metadataUrl) {
        try {
            URL url = new URL(metadataUrl);
            ClusterMetadataPrototype metadata = null;
            long version = 0;
            if ("file".equals(url.getProtocol())) {
                File file = new File(metadataUrl.replaceFirst("file://", ""));
                version = file.lastModified();
                metadata = mapper.readValue(new FileInputStream(file), ClusterMetadataPrototype.class);
            } else if ("http".equals(url.getProtocol())) {
                try {
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                        log.warn("Could not reach metadata URL {}. Retrying...", url);
                        return null;
                    }
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
                        return null;
                    }
                    version = conn.getLastModified();
                    metadata = mapper.readValue(conn.getInputStream(), ClusterMetadataPrototype.class);
                } catch (IOException e) {
                    log.warn("Could not reach metadata URL {}. Retrying...", url);
                    return null;
                }
            }

            if (null == metadata) {
                log.warn("Metadata is null in the function fetchMetadata");
                throw new NullPointerException();
            }

            return new Versioned<>(new ClusterMetadata(
                PROVIDER_ID,
                metadata.getName(),
                metadata.getNode() != null ?
                    new DefaultControllerNode(
                        getNodeId(metadata.getNode()),
                        getNodeHost(metadata.getNode()),
                        getNodePort(metadata.getNode())) : null,
                    metadata.getController()
                        .stream()
                        .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
                        .collect(Collectors.toSet()),
                    metadata.getStorageDnsService(),
                    metadata.getStorage()
                        .stream()
                        .map(node -> new DefaultControllerNode(getNodeId(node), getNodeHost(node), getNodePort(node)))
                        .collect(Collectors.toSet()),
                    metadata.getClusterSecret()),
                version);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Monitors the metadata url for any updates and notifies providerService accordingly.
     */
    private void watchUrl(String metadataUrl) {
        if (!isAvailable()) {
            return;
        }
        // TODO: We are merely polling the url.
        // This can be easily addressed for files. For http urls we need to move to a push style protocol.
        try {
            Versioned<ClusterMetadata> latestMetadata = fetchMetadata(metadataUrl);
            if (cachedMetadata.get() != null && latestMetadata != null
                    && cachedMetadata.get().version() < latestMetadata.version()) {
                cachedMetadata.set(latestMetadata);
                providerService.clusterMetadataChanged(latestMetadata);
            }
        } catch (Exception e) {
            log.error("Unable to parse metadata : ", e);
        }
    }

    private static class ClusterMetadataPrototype {
        private String name;
        private NodePrototype node;
        private Set<NodePrototype> controller = Sets.newHashSet();
        private String storageDnsService;
        private Set<NodePrototype> storage = Sets.newHashSet();
        private String clusterSecret;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public NodePrototype getNode() {
            return node;
        }

        public void setNode(NodePrototype node) {
            this.node = node;
        }

        public Set<NodePrototype> getController() {
            return controller;
        }

        public void setController(Set<NodePrototype> controller) {
            this.controller = controller;
        }

        public String getStorageDnsService() {
            return storageDnsService;
        }

        public void setStorageDnsService(String storageDnsService) {
            this.storageDnsService = storageDnsService;
        }

        public Set<NodePrototype> getStorage() {
            return storage;
        }

        public void setStorage(Set<NodePrototype> storage) {
            this.storage = storage;
        }

        public void setClusterSecret(String clusterSecret) {
            this.clusterSecret = clusterSecret;
        }

        public String getClusterSecret() {
            return clusterSecret;
        }
    }

    private static class NodePrototype {
        private String id;
        private String ip;
        private String host;
        private Integer port;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public Integer getPort() {
            return port;
        }

        public void setPort(Integer port) {
            this.port = port;
        }
    }
}


text:
import React, { PropTypes } from 'react';
import Link from 'gatsby-link';
import theme from '../../../theme';
import invertedLogo from '../../../images/logo-inverted.svg';

function Item ({ path, label }) {
	return (

			<Link to={path} css={styles.link}>{label}</Link>

	);
};

export default function Navbar ({ isHome, items }) {
	return (

			<Link to="/" css={styles.brand}>

			</Link>

				{items.map(s => (
					<Item
						key={s.slug}
						label={s.section}
						path={s.slug}
					/>
				))}

	);
};

Navbar.PropTypes = {
	isHome: PropTypes.bool,
	items: PropTypes.oneOfType([
		PropTypes.arrayOf(PropTypes.node),
		PropTypes.node,
	]).isRequired,
};

/* eslint quote-props: ["error", "as-needed"] */
const styles = {
	nav: {
		alignItems: 'center',
		backgroundColor: theme.color.blue,
		display: 'flex',
		justifyContent: 'space-between',
	},
	list: {
		display: 'inline-flex',
		listStyle: 'none',
		margin: 0,
	},

	// brand
	brand: {
		display: 'block',
		lineHeight: 0,
		textDecoration: 'none',
		paddingLeft: '1em',
		paddingRight: '1em',
	},
	brandIcon: {
		height: 30,
		margin: 0,
	},

	// items
	item: {
		display: 'inline-flex',
		margin: 0,
	},
	link: {
		color: 'white',
		display: 'block',
		padding: '1em',
		textDecoration: 'none',
	},
	link__active: {
		opacity: 1,
	},
};


text:
package one.util.huntbugs.detect;

import com.strobel.assembler.metadata.MethodReference;
import com.strobel.decompiler.ast.AstCode;
import com.strobel.decompiler.ast.Expression;

import one.util.huntbugs.flow.ValuesFlow;
import one.util.huntbugs.registry.MethodContext;
import one.util.huntbugs.registry.anno.AstNodes;
import one.util.huntbugs.registry.anno.AstVisitor;
import one.util.huntbugs.registry.anno.WarningDefinition;
import one.util.huntbugs.util.Exprs;
import one.util.huntbugs.util.Nodes;
import one.util.huntbugs.warning.Role.LocationRole;
import one.util.huntbugs.warning.Role.TypeRole;

/**
 * @author Tagir Valeev
 *
 */
@WarningDefinition(category = "Correctness", name = "AppendObjectOutputStream", maxScore = 65)
public class AppendObjectOutputStream {
    private static final LocationRole STREAM_CREATED_AT = LocationRole.forName("STREAM_CREATED_AT");
    private static final TypeRole OOS_TYPE = TypeRole.forName("OOS_TYPE");

    @AstVisitor(nodes = AstNodes.EXPRESSIONS)
    public void visit(Expression expr, MethodContext mc) {
        if (expr.getCode() != AstCode.InitObject)
            return;
        MethodReference ctor = (MethodReference) expr.getOperand();
        if (!ctor.getDeclaringType().getInternalName().equals("java/io/ObjectOutputStream")
            || !ctor.getSignature().equals("(Ljava/io/OutputStream;)V"))
            return;
        Expression outStream = Exprs.getChild(expr, 0);
        while (isBufferedStream(outStream))
            outStream = Exprs.getChild(outStream, 0);
        Expression target = ValuesFlow.findFirst(outStream, AppendObjectOutputStream::isAppendOutput);
        if (target != null) {
            mc.report("AppendObjectOutputStream", 0, expr, STREAM_CREATED_AT.create(mc, target), OOS_TYPE.create(ctor
                    .getDeclaringType()));
        }
    }

    private static boolean isBufferedStream(Expression expr) {
        if (expr.getCode() == AstCode.InitObject) {
            MethodReference ctor = (MethodReference) expr.getOperand();
            if (ctor.getDeclaringType().getInternalName().equals("java/io/BufferedOutputStream")
                && ctor.getSignature().equals("(Ljava/io/OutputStream;)V")) {
                return true;
            }
        }
        return false;
    }

    private static boolean isAppendOutput(Expression expr) {
        if (expr.getCode() == AstCode.InitObject) {
            MethodReference ctor = (MethodReference) expr.getOperand();
            if (ctor.getDeclaringType().getInternalName().equals("java/io/FileOutputStream")
                && (ctor.getSignature().equals("(Ljava/io/File;Z)V") || ctor.getSignature().equals(
                    "(Ljava/lang/String;Z)V"))) {
                Object constant = Nodes.getConstant(expr.getArguments().get(1));
                if (constant instanceof Integer && ((Integer) constant).intValue() == 1) {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
package nl.nn.adapterframework.pipes;

import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.configuration.ConfigurationWarnings;

/**
 * Posts a message to another IBIS-adapter in the same JVM.
 *
 * An IbisJavaSender makes a call to a Receiver a {@link nl.nn.adapterframework.receivers.JavaListener JavaListener}
 * or any other application in the same JVM that has registered a RequestProcessor with the IbisServiceDispatcher.
 *
 *
Configuration:
 *

 *
attributes	description	default

 *
classname	nl.nn.adapterframework.pipes.IbisLocalSender

 *
{@link #setName(String) name}	name of the sender

 *
{@link #setServiceName(String) serviceName}	serviceName of the
 * {@link nl.nn.adapterframework.receivers.JavaListener JavaListener} that should be called

 *
{@link #setReturnedSessionKeys(String) returnedSessionKeys}	comma separated list of keys of session variables that should be returned to caller, for correct results as well as for erronous results. (Only for listeners that support it, like JavaListener)

 *

 *

 * Any parameters are copied to the PipeLineSession of the service called.
 *
 *
configuring IbisJavaSender and JavaListener

 *

 *
Define a GenericMessageSendingPipe with an IbisJavaSender

 *
Set the attribute serviceName to yourExternalServiceName

 *

 * In the Adapter to be called:
 *

 *
Define a Receiver with a JavaListener

 *
Set the attribute serviceName to yourExternalServiceName

 *

 * N.B. Please make sure that the IbisServiceDispatcher-1.1.jar is present on the class path of the server.
 *
 * @author  Gerrit van Brakel
 * @since   4.4.5
 * @version $Id$
 * @deprecated Please replace with nl.nn.adapterframework.senders.IbisJavaSender
 */
public class IbisJavaSender extends nl.nn.adapterframework.senders.IbisJavaSender {

	public void configure() throws ConfigurationException {
		ConfigurationWarnings configWarnings = ConfigurationWarnings.getInstance();
		String msg = getLogPrefix()+"The class ["+getClass().getName()+"] has been deprecated. Please change to ["+getClass().getSuperclass().getName()+"]";
		configWarnings.add(log, msg);
		super.configure();
	}
}


text:
import Popper from 'popper.js'
import clickoutMixin from './clickout'
import listenOnRootMixin from './listen-on-root'
import { from as arrayFrom } from '../utils/array'
import { assign } from '../utils/object'
import KeyCodes from '../utils/key-codes'
import warn from '../utils/warn'
import { isVisible, closest, selectAll, getAttr, eventOn, eventOff } from '../utils/dom'

// Return an Array of visible items
function filterVisible (els) {
  return (els || []).filter(isVisible)
}

// Dropdown item CSS selectors
// TODO: .dropdown-form handling
const ITEM_SELECTOR = '.dropdown-item:not(.disabled):not([disabled])'

// Popper attachment positions
const AttachmentMap = {
  // DropUp Left Align
  TOP: 'top-start',
  // DropUp Right Align
  TOPEND: 'top-end',
  // Dropdown left Align
  BOTTOM: 'bottom-start',
  // Dropdown Right Align
  BOTTOMEND: 'bottom-end'
}

export default {
  mixins: [clickoutMixin, listenOnRootMixin],
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    text: {
      // Button label
      type: String,
      default: ''
    },
    dropup: {
      // place on top if possible
      type: Boolean,
      default: false
    },
    right: {
      // Right align menu (default is left align)
      type: Boolean,
      default: false
    },
    offset: {
      // Number of pixels to offset menu, or a CSS unit value (i.e. 1px, 1rem, etc)
      type: [Number, String],
      default: 0
    },
    noFlip: {
      // Disable auto-flipping of menu from bottom<=>top
      type: Boolean,
      default: false
    },
    popperOpts: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      visible: false,
      inNavbar: null
    }
  },
  created () {
    // Create non-reactive property
    this._popper = null
  },
  mounted () {
    // To keep one dropdown opened on page
    this.listenOnRoot('bv::dropdown::shown', this.rootCloseListener)
    // Hide when clicked on links
    this.listenOnRoot('clicked::link', this.rootCloseListener)
    // Use new namespaced events
    this.listenOnRoot('bv::link::clicked', this.rootCloseListener)
  },
  /* istanbul ignore next: not easy to test */
  deactivated () {
    // In case we are inside a `<keep-alive>`
    this.visible = false
    this.setTouchStart(false)
    this.removePopper()
  },
  /* istanbul ignore next: not easy to test */
  beforeDestroy () {
    this.visible = false
    this.setTouchStart(false)
    this.removePopper()
  },
  watch: {
    visible (state, old) {
      if (state === old) {
        // Avoid duplicated emits
        return
      }
      if (state) {
        this.showMenu()
      } else {
        this.hideMenu()
      }
    },
    disabled (state, old) {
      if (state !== old && state && this.visible) {
        // Hide dropdown if disabled changes to true
        this.visible = false
      }
    }
  },
  computed: {
    toggler () {
      return this.$refs.toggle.$el || this.$refs.toggle
    }
  },
  methods: {
    showMenu () {
      if (this.disabled) {
        return
      }
      // TODO: move emit show to visible watcher, to allow cancelling of show
      this.$emit('show')
      // Ensure other menus are closed
      this.emitOnRoot('bv::dropdown::shown', this)

      // Are we in a navbar ?
      if (this.inNavbar === null && this.isNav) {
        this.inNavbar = Boolean(closest('.navbar', this.$el))
      }

      // Disable totally Popper.js for Dropdown in Navbar
      /* istnbul ignore next: can't test popper in JSDOM */
      if (!this.inNavbar) {
        if (typeof Popper === 'undefined') {
          warn('b-dropdown: Popper.js not found. Falling back to CSS positioning.')
        } else {
          // for dropup with alignment we use the parent element as popper container
          let element = ((this.dropup && this.right) || this.split) ? this.$el : this.$refs.toggle
          // Make sure we have a reference to an element, not a component!
          element = element.$el || element
          // Instantiate popper.js
          this.createPopper(element)
        }
      }

      this.setTouchStart(true)
      this.$emit('shown')

      // Focus on the first item on show
      this.$nextTick(this.focusFirstItem)
    },
    hideMenu () {
      // TODO: move emit hide to visible watcher, to allow cancelling of hide
      this.$emit('hide')
      this.setTouchStart(false)
      this.emitOnRoot('bv::dropdown::hidden', this)
      this.$emit('hidden')
      this.removePopper()
    },
    createPopper (element) {
      this.removePopper()
      this._popper = new Popper(element, this.$refs.menu, this.getPopperConfig())
    },
    removePopper () {
      if (this._popper) {
        // Ensure popper event listeners are removed cleanly
        this._popper.destroy()
      }
      this._popper = null
    },
    getPopperConfig /* istanbul ignore next: can't test popper in JSDOM */ () {
      let placement = AttachmentMap.BOTTOM
      if (this.dropup && this.right) {
        // dropup + right
        placement = AttachmentMap.TOPEND
      } else if (this.dropup) {
        // dropup + left
        placement = AttachmentMap.TOP
      } else if (this.right) {
        // dropdown + right
        placement = AttachmentMap.BOTTOMEND
      }
      const popperConfig = {
        placement,
        modifiers: {
          offset: {
            offset: this.offset || 0
          },
          flip: {
            enabled: !this.noFlip
          }
        }
      }
      if (this.boundary) {
        popperConfig.modifiers.preventOverflow = {
          boundariesElement: this.boundary
        }
      }
      return assign(popperConfig, this.popperOpts || {})
    },
    setTouchStart (on) {
      /*
       * If this is a touch-enabled device we add extra
       * empty mouseover listeners to the body's immediate children;
       * only needed because of broken event delegation on iOS
       * https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
       */
      if ('ontouchstart' in document.documentElement) {
        const children = arrayFrom(document.body.children)
        children.forEach(el => {
          if (on) {
            eventOn('mouseover', this._noop)
          } else {
            eventOff('mouseover', this._noop)
          }
        })
      }
    },
    /* istanbul ignore next: not easy to test */
    _noop () {
      // Do nothing event handler (used in touchstart event handler)
    },
    rootCloseListener (vm) {
      if (vm !== this) {
        this.visible = false
      }
    },
    clickOutListener () {
      this.visible = false
    },
    show () {
      // Public method to show dropdown
      if (this.disabled) {
        return
      }
      this.visible = true
    },
    hide () {
      // Public method to hide dropdown
      if (this.disabled) {
        return
      }
      this.visible = false
    },
    toggle (evt) {
      // Called only by a button that toggles the menu
      evt = evt || {}
      const type = evt.type
      const key = evt.keyCode
      if (type !== 'click' && !(type === 'keydown' && (key === KeyCodes.ENTER || key === KeyCodes.SPACE || key === KeyCodes.DOWN))) {
        // We only toggle on Click, Enter, Space, and Arrow Down
        return
      }
      evt.preventDefault()
      evt.stopPropagation()
      if (this.disabled) {
        this.visible = false
        return
      }
      // Toggle visibility
      this.visible = !this.visible
    },
    click (evt) {
      // Calle only in split button mode, for the split button
      if (this.disabled) {
        this.visible = false
        return
      }
      this.$emit('click', evt)
    },
    /* istanbul ignore next: not easy to test */
    onKeydown (evt) {
      // Called from dropdown menu context
      const key = evt.keyCode
      if (key === KeyCodes.ESC) {
        // Close on ESC
        this.onEsc(evt)
      } else if (key === KeyCodes.TAB) {
        // Close on tab out
        this.onTab(evt)
      } else if (key === KeyCodes.DOWN) {
        // Down Arrow
        this.focusNext(evt, false)
      } else if (key === KeyCodes.UP) {
        // Up Arrow
        this.focusNext(evt, true)
      }
    },
    /* istanbul ignore next: not easy to test */
    onEsc (evt) {
      if (this.visible) {
        this.visible = false
        evt.preventDefault()
        evt.stopPropagation()
        // Return focus to original trigger button
        this.$nextTick(this.focusToggler)
      }
    },
    /* istanbul ignore next: not easy to test */
    onTab (evt) {
      if (this.visible) {
        // TODO: Need special handler for dealing with form inputs
        // Tab, if in a text-like input, we should just focus next item in the dropdown
        // Note: Inputs are in a special .dropdown-form container
        this.visible = false
      }
    },
    onFocusOut (evt) {
      if (this.$refs.menu.contains(evt.relatedTarget)) {
        return
      }
      this.visible = false
    },
    /* istanbul ignore next: not easy to test */
    onMouseOver (evt) {
      // Focus the item on hover
      // TODO: Special handling for inputs? Inputs are in a special .dropdown-form container
      const item = evt.target
      if (
        item.classList.contains('dropdown-item') &&
                !item.disabled &&
                !item.classList.contains('disabled') &&
                item.focus
      ) {
        item.focus()
      }
    },
    focusNext (evt, up) {
      if (!this.visible) {
        return
      }
      evt.preventDefault()
      evt.stopPropagation()
      this.$nextTick(() => {
        const items = this.getItems()
        if (items.length < 1) {
          return
        }
        let index = items.indexOf(evt.target)
        if (up && index > 0) {
          index--
        } else if (!up && index < items.length - 1) {
          index++
        }
        if (index < 0) {
          index = 0
        }
        this.focusItem(index, items)
      })
    },
    focusItem (idx, items) {
      let el = items.find((el, i) => i === idx)
      if (el && getAttr(el, 'tabindex') !== '-1') {
        el.focus()
      }
    },
    getItems () {
      // Get all items
      return filterVisible(selectAll(ITEM_SELECTOR, this.$refs.menu))
    },
    getFirstItem () {
      // Get the first non-disabled item
      let item = this.getItems()[0]
      return item || null
    },
    focusFirstItem () {
      const item = this.getFirstItem()
      if (item) {
        this.focusItem(0, [item])
      }
    },
    focusToggler () {
      let toggler = this.toggler
      if (toggler && toggler.focus) {
        toggler.focus()
      }
    }
  }
}


text:
namespace Lauener.Core.Windows.TestGui.Windows
{
    /// <summary>
    /// Interaction logic for Main.xaml
    /// </summary>
    public partial class Main
    {
        public Main()
        {
            this.InitializeComponent();
        }
    }
}


text:
package org.apache.nifi.provenance.schema;

import static org.apache.nifi.repository.schema.Repetition.EXACTLY_ONE;
import static org.apache.nifi.repository.schema.Repetition.ZERO_OR_MORE;
import static org.apache.nifi.repository.schema.Repetition.ZERO_OR_ONE;

import org.apache.nifi.repository.schema.ComplexRecordField;
import org.apache.nifi.repository.schema.FieldType;
import org.apache.nifi.repository.schema.MapRecordField;
import org.apache.nifi.repository.schema.RecordField;
import org.apache.nifi.repository.schema.SimpleRecordField;

public class EventRecordFields {

    // General Event fields.
    public static final RecordField RECORD_IDENTIFIER = new SimpleRecordField(EventFieldNames.EVENT_IDENTIFIER, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField EVENT_TYPE = new SimpleRecordField(EventFieldNames.EVENT_TYPE, FieldType.STRING, EXACTLY_ONE);
    public static final RecordField EVENT_TIME = new SimpleRecordField(EventFieldNames.EVENT_TIME, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField FLOWFILE_ENTRY_DATE = new SimpleRecordField(EventFieldNames.FLOWFILE_ENTRY_DATE, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField EVENT_DURATION = new SimpleRecordField(EventFieldNames.EVENT_DURATION, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField LINEAGE_START_DATE = new SimpleRecordField(EventFieldNames.LINEAGE_START_DATE, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField COMPONENT_ID = new SimpleRecordField(EventFieldNames.COMPONENT_ID, FieldType.STRING, ZERO_OR_ONE);
    public static final RecordField COMPONENT_TYPE = new SimpleRecordField(EventFieldNames.COMPONENT_TYPE, FieldType.STRING, ZERO_OR_ONE);
    public static final RecordField FLOWFILE_UUID = new SimpleRecordField(EventFieldNames.FLOWFILE_UUID, FieldType.STRING, EXACTLY_ONE);
    public static final RecordField EVENT_DETAILS = new SimpleRecordField(EventFieldNames.EVENT_DETAILS, FieldType.STRING, ZERO_OR_ONE);
    public static final RecordField SOURCE_QUEUE_IDENTIFIER = new SimpleRecordField(EventFieldNames.SOURCE_QUEUE_IDENTIFIER, FieldType.STRING, ZERO_OR_ONE);

    // Attributes
    public static final RecordField ATTRIBUTE_NAME = new SimpleRecordField(EventFieldNames.ATTRIBUTE_NAME, FieldType.LONG_STRING, EXACTLY_ONE);
    public static final RecordField ATTRIBUTE_VALUE_REQUIRED = new SimpleRecordField(EventFieldNames.ATTRIBUTE_VALUE, FieldType.LONG_STRING, EXACTLY_ONE);
    public static final RecordField ATTRIBUTE_VALUE_OPTIONAL = new SimpleRecordField(EventFieldNames.ATTRIBUTE_VALUE, FieldType.LONG_STRING, ZERO_OR_ONE);

    public static final RecordField PREVIOUS_ATTRIBUTES = new MapRecordField(EventFieldNames.PREVIOUS_ATTRIBUTES, ATTRIBUTE_NAME, ATTRIBUTE_VALUE_REQUIRED, EXACTLY_ONE);
    public static final RecordField UPDATED_ATTRIBUTES = new MapRecordField(EventFieldNames.UPDATED_ATTRIBUTES, ATTRIBUTE_NAME, ATTRIBUTE_VALUE_OPTIONAL, EXACTLY_ONE);

    // Content Claims
    public static final RecordField CONTENT_CLAIM_CONTAINER = new SimpleRecordField(EventFieldNames.CONTENT_CLAIM_CONTAINER, FieldType.STRING, EXACTLY_ONE);
    public static final RecordField CONTENT_CLAIM_SECTION = new SimpleRecordField(EventFieldNames.CONTENT_CLAIM_SECTION, FieldType.STRING, EXACTLY_ONE);
    public static final RecordField CONTENT_CLAIM_IDENTIFIER = new SimpleRecordField(EventFieldNames.CONTENT_CLAIM_IDENTIFIER, FieldType.STRING, EXACTLY_ONE);
    public static final RecordField CONTENT_CLAIM_OFFSET = new SimpleRecordField(EventFieldNames.CONTENT_CLAIM_OFFSET, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField CONTENT_CLAIM_SIZE = new SimpleRecordField(EventFieldNames.CONTENT_CLAIM_SIZE, FieldType.LONG, EXACTLY_ONE);
    public static final RecordField CURRENT_CONTENT_CLAIM = new ComplexRecordField(EventFieldNames.CONTENT_CLAIM, ZERO_OR_ONE,
        CONTENT_CLAIM_CONTAINER, CONTENT_CLAIM_SECTION, CONTENT_CLAIM_IDENTIFIER, CONTENT_CLAIM_OFFSET, CONTENT_CLAIM_SIZE);
    public static final RecordField PREVIOUS_CONTENT_CLAIM = new ComplexRecordField(EventFieldNames.PREVIOUS_CONTENT_CLAIM, ZERO_OR_ONE,
        CONTENT_CLAIM_CONTAINER, CONTENT_CLAIM_SECTION, CONTENT_CLAIM_IDENTIFIER, CONTENT_CLAIM_OFFSET, CONTENT_CLAIM_SIZE);

    // EventType-Specific fields
    // for FORK, JOIN, CLONE, REPLAY
    public static final RecordField PARENT_UUIDS = new SimpleRecordField(EventFieldNames.PARENT_UUIDS, FieldType.STRING, ZERO_OR_MORE);
    public static final RecordField CHILD_UUIDS = new SimpleRecordField(EventFieldNames.CHILD_UUIDS, FieldType.STRING, ZERO_OR_MORE);

    // for SEND/RECEIVE/FETCH
    public static final RecordField TRANSIT_URI = new SimpleRecordField(EventFieldNames.TRANSIT_URI, FieldType.STRING, ZERO_OR_ONE);
    public static final RecordField SOURCE_SYSTEM_FLOWFILE_IDENTIFIER = new SimpleRecordField(EventFieldNames.SOURCE_SYSTEM_FLOWFILE_IDENTIFIER, FieldType.STRING, ZERO_OR_ONE);

    // for ADD_INFO
    public static final RecordField ALTERNATE_IDENTIFIER = new SimpleRecordField(EventFieldNames.ALTERNATE_IDENTIFIER, FieldType.STRING, ZERO_OR_ONE);
    public static final RecordField RELATIONSHIP = new SimpleRecordField(EventFieldNames.RELATIONSHIP, FieldType.STRING, ZERO_OR_ONE);
}


text:
<?php

/**
 * Data associated with an advertiser experiment for this adgroup.
 * This is disabled for AdX.
 * @package    Google_Api_Ads_AdWords_v201605
 * @subpackage v201605
 */
class AdGroupExperimentData
{

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
    const XSI_TYPE = "AdGroupExperimentData";

    /**
     * @access public
     * @var integer
     */
    public $experimentId;

    /**
     * @access public
     * @var tnsExperimentDeltaStatus
     */
    public $experimentDeltaStatus;

    /**
     * @access public
     * @var tnsExperimentDataStatus
     */
    public $experimentDataStatus;

    /**
     * @access public
     * @var AdGroupExperimentBidMultipliers
     */
    public $experimentBidMultipliers;

    /**
     * Gets the namesapce of this class
     * @return string the namespace of this class
     */
    public function getNamespace()
    {
        return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return string the xsi:type name of this class
     */
    public function getXsiTypeName()
    {
        return self::XSI_TYPE;
    }

    public function __construct(
        $experimentId = null,
        $experimentDeltaStatus = null,
        $experimentDataStatus = null,
        $experimentBidMultipliers = null
    ) {
        $this->experimentId = $experimentId;
        $this->experimentDeltaStatus = $experimentDeltaStatus;
        $this->experimentDataStatus = $experimentDataStatus;
        $this->experimentBidMultipliers = $experimentBidMultipliers;
    }

}


text:
namespace subresource_filter {

namespace {

const mojom::ActivationState kDisabled;

RulesetVerificationStatus GetRulesetVerification() {
  RulesetService* service =
      g_browser_process->subresource_filter_ruleset_service();
  VerifiedRulesetDealer::Handle* dealer_handle = service->GetRulesetDealer();

  auto callback_method = [](base::OnceClosure quit_closure,
                            RulesetVerificationStatus* status,
                            VerifiedRulesetDealer* verified_dealer) {
    *status = verified_dealer->status();
    std::move(quit_closure).Run();
  };

  RulesetVerificationStatus status;
  base::RunLoop run_loop;
  auto callback =
      base::BindRepeating(callback_method, run_loop.QuitClosure(), &status);

  dealer_handle->GetDealerAsync(callback);
  run_loop.Run();
  return status;
}

const char kIndexedRulesetVerifyHistogram[] =
    "SubresourceFilter.IndexRuleset.Verify.Status";

}  // namespace

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
                       RulesetVerified_Activation) {
  base::HistogramTester histogram_tester;
  ASSERT_NO_FATAL_FAILURE(
      SetRulesetToDisallowURLsWithPathSuffix("included_script.js"));
  RulesetService* service =
      g_browser_process->subresource_filter_ruleset_service();
  ASSERT_TRUE(service->GetRulesetDealer());
  auto ruleset_handle =
      std::make_unique<VerifiedRuleset::Handle>(service->GetRulesetDealer());
  AsyncDocumentSubresourceFilter::InitializationParams params(
      GURL("https://example.com/"), mojom::ActivationLevel::kEnabled, false);

  testing::TestActivationStateCallbackReceiver receiver;
  AsyncDocumentSubresourceFilter filter(ruleset_handle.get(), std::move(params),
                                        receiver.GetCallback());
  receiver.WaitForActivationDecision();
  mojom::ActivationState expected_state;
  expected_state.activation_level = mojom::ActivationLevel::kEnabled;
  receiver.ExpectReceivedOnce(expected_state);
  histogram_tester.ExpectUniqueSample(kIndexedRulesetVerifyHistogram,
                                      VerifyStatus::kPassValidChecksum, 1);
}

// TODO(ericrobinson): Add a test using a PRE_ phase that corrupts the ruleset
// on disk to test something closer to an actual execution path for checksum.

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, NoRuleset_NoActivation) {
  base::HistogramTester histogram_tester;
  // Do not set the ruleset, which results in an invalid ruleset.
  RulesetService* service =
      g_browser_process->subresource_filter_ruleset_service();
  ASSERT_TRUE(service->GetRulesetDealer());
  auto ruleset_handle =
      std::make_unique<VerifiedRuleset::Handle>(service->GetRulesetDealer());
  AsyncDocumentSubresourceFilter::InitializationParams params(
      GURL("https://example.com/"), mojom::ActivationLevel::kEnabled, false);

  testing::TestActivationStateCallbackReceiver receiver;
  AsyncDocumentSubresourceFilter filter(ruleset_handle.get(), std::move(params),
                                        receiver.GetCallback());
  receiver.WaitForActivationDecision();
  receiver.ExpectReceivedOnce(kDisabled);
  histogram_tester.ExpectTotalCount(kIndexedRulesetVerifyHistogram, 0);
}

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest, InvalidRuleset_Checksum) {
  base::HistogramTester histogram_tester;
  const char kTestRulesetSuffix[] = "foo";
  const int kNumberOfRules = 500;
  TestRulesetCreator ruleset_creator;
  TestRulesetPair test_ruleset_pair;
  ASSERT_NO_FATAL_FAILURE(
      ruleset_creator.CreateRulesetToDisallowURLsWithManySuffixes(
          kTestRulesetSuffix, kNumberOfRules, &test_ruleset_pair));
  RulesetService* service =
      g_browser_process->subresource_filter_ruleset_service();

  // Publish the good ruleset.
  TestRulesetPublisher publisher(service);
  publisher.SetRuleset(test_ruleset_pair.unindexed);

  // Now corrupt it by flipping one entry.  This can only be detected
  // via the checksum, and not the Flatbuffer Verifier.  This was determined
  // at random by flipping elements until this test failed, then adding
  // the checksum code and ensuring it passed.
  testing::TestRuleset::CorruptByFilling(test_ruleset_pair.indexed, 28246,
                                         28247, 32);
  OpenAndPublishRuleset(service, test_ruleset_pair.indexed.path);
  ASSERT_TRUE(service->GetRulesetDealer());

  auto ruleset_handle =
      std::make_unique<VerifiedRuleset::Handle>(service->GetRulesetDealer());
  AsyncDocumentSubresourceFilter::InitializationParams params(
      GURL("https://example.com/"), mojom::ActivationLevel::kEnabled, false);

  testing::TestActivationStateCallbackReceiver receiver;
  AsyncDocumentSubresourceFilter filter(ruleset_handle.get(), std::move(params),
                                        receiver.GetCallback());
  receiver.WaitForActivationDecision();
  receiver.ExpectReceivedOnce(kDisabled);
  RulesetVerificationStatus dealer_status = GetRulesetVerification();
  EXPECT_EQ(RulesetVerificationStatus::kCorrupt, dealer_status);
  // If AdTagging is enabled, then the initial SetRuleset will trigger
  // a call to Verify.  Make sure we see that and the later failure.
  if (base::FeatureList::IsEnabled(kAdTagging)) {
    histogram_tester.ExpectBucketCount(kIndexedRulesetVerifyHistogram,
                                       VerifyStatus::kPassValidChecksum, 1);
    histogram_tester.ExpectBucketCount(kIndexedRulesetVerifyHistogram,
                                       VerifyStatus::kChecksumFailVerifierPass,
                                       1);
    histogram_tester.ExpectTotalCount(kIndexedRulesetVerifyHistogram, 2);
  } else {
    // Otherwise we see only a single Verify when the new ruleset is accessed,
    // and that should be a failure.
    histogram_tester.ExpectUniqueSample(kIndexedRulesetVerifyHistogram,
                                        VerifyStatus::kChecksumFailVerifierPass,
                                        1);
  }
}

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTest,
                       InvalidRuleset_NoActivation) {
  base::HistogramTester histogram_tester;
  const char kTestRulesetSuffix[] = "foo";
  const int kNumberOfRules = 500;
  TestRulesetCreator ruleset_creator;
  TestRulesetPair test_ruleset_pair;
  ASSERT_NO_FATAL_FAILURE(
      ruleset_creator.CreateRulesetToDisallowURLsWithManySuffixes(
          kTestRulesetSuffix, kNumberOfRules, &test_ruleset_pair));
  testing::TestRuleset::CorruptByTruncating(test_ruleset_pair.indexed, 123);

  // Just publish the corrupt indexed file directly, to simulate it being
  // corrupt on startup.
  RulesetService* service =
      g_browser_process->subresource_filter_ruleset_service();
  ASSERT_TRUE(service->GetRulesetDealer());
  OpenAndPublishRuleset(service, test_ruleset_pair.indexed.path);

  auto ruleset_handle =
      std::make_unique<VerifiedRuleset::Handle>(service->GetRulesetDealer());
  AsyncDocumentSubresourceFilter::InitializationParams params(
      GURL("https://example.com/"), mojom::ActivationLevel::kEnabled, false);

  testing::TestActivationStateCallbackReceiver receiver;
  AsyncDocumentSubresourceFilter filter(ruleset_handle.get(), std::move(params),
                                        receiver.GetCallback());
  receiver.WaitForActivationDecision();
  receiver.ExpectReceivedOnce(kDisabled);
  RulesetVerificationStatus dealer_status = GetRulesetVerification();
  EXPECT_EQ(RulesetVerificationStatus::kCorrupt, dealer_status);
  histogram_tester.ExpectUniqueSample(kIndexedRulesetVerifyHistogram,
                                      VerifyStatus::kVerifierFailChecksumZero,
                                      1);
}

class SubresourceFilterBrowserTestWithoutAdTagging
    : public SubresourceFilterBrowserTest {
 public:
  SubresourceFilterBrowserTestWithoutAdTagging() {
    feature_list_.InitAndDisableFeature(subresource_filter::kAdTagging);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTestWithoutAdTagging,
                       LazyRulesetValidation) {
  // The ruleset shouldn't be validated until it's used, unless ad tagging is
  // enabled.
  SetRulesetToDisallowURLsWithPathSuffix("included_script.js");
  RulesetVerificationStatus dealer_status = GetRulesetVerification();
  EXPECT_EQ(RulesetVerificationStatus::kNotVerified, dealer_status);
}

class SubresourceFilterBrowserTestWithAdTagging
    : public SubresourceFilterBrowserTest {
 public:
  SubresourceFilterBrowserTestWithAdTagging() {
    feature_list_.InitAndEnableFeature(subresource_filter::kAdTagging);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

IN_PROC_BROWSER_TEST_F(SubresourceFilterBrowserTestWithAdTagging,
                       AdsTaggingImmediateRulesetValidation) {
  // When Ads Tagging is enabled, the ruleset should be validated as soon as
  // it's published.
  SetRulesetToDisallowURLsWithPathSuffix("included_script.js");
  RulesetVerificationStatus dealer_status = GetRulesetVerification();
  EXPECT_EQ(RulesetVerificationStatus::kIntact, dealer_status);
}

}  // namespace subresource_filter


text:
var bcrypt = require('bcrypt-nodejs'),
	crypto = require('crypto');

exports.Product = require('./product');
exports.User = require('./user')(bcrypt, crypto);
exports.Order = require('./order');


text:
A personalized view of the latest news, journal scans, and expert commentaries

World-renowned experts that hand select content related to your chosen

Update your specialty(s), interests, and notification settings

The customized view of your selected interests

Highlighted topics related to your specialty

News, Research, Reviews, and Expert Opinions from across your specialty channel.

CME opportunities and seminal articles


text:
module Any
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def any
      limit(1).offset((count * rand).to_i).first
    end
  end
end

class ActiveRecord::Base
  include Any
end