text:
var _ = require("lodash");
var debug = require("debug")("dogwood:tests:integration");
var chai = require("chai");
var expect = chai.expect;
var should = chai.should;
var assert = chai.assert;
var request = require("superagent");

module.exports = function () {

    var routes = {
        apiRoot: "http://localhost:7000/api/",
        auth: {
            createUser: "auth/register",
            login: "auth/login"
        }
    };

    var testData = {
        validUser: {
            username: "testuser",
            password: "P@s$w0rd!",
            email: "text@example.com",
            firstName: "Test",
            lastName: "User"
        }
    };

    function useData(data) {
        return _.clone(data, true);
    }

    describe("Auth", function () {

        describe("Register/Create User", function () {

            it("should successfully register a user with valid input data", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.createUser)
                    .send(useData(testData.validUser))
                    .end(function (res) {
                        expect(res.body.success).to.be.true;
                        expect(res.body.data).to.exist;
                        expect(res.body.data.id).to.be.an.integer;
                        done();
                    });
            });

            it("should return an error when attempting to register a user without a username", function (done) {
                var data = useData(testData.validUser);
                data = _.omit(data, "username");

                request
                    .post(routes.apiRoot + routes.auth.createUser)
                    .send(data)
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.statusCode).to.equal(500);
                        done();
                    });
            });

            it("should return an error when attempting to register a user with an invalid password", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.createUser)
                    .send(_.extend(useData(testData.validUser), { password: "foo" }))
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.statusCode).to.equal(500);
                        done();
                    });
            });

            it("should return an error when attempting to register a user with a username that already exists", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.createUser)
                    .send(useData(testData.validUser))
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.message).to.have.string("Error registering user");
                        expect(res.body.data).to.have.string("Username already exists");
                        done();
                    });
            });

            it("should return an error when attempting to register a user with an email that already exists", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.createUser)
                    .send(_.extend(useData(testData.validUser), { username: "testuser2" }))
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.message).to.have.string("Error registering user");
                        expect(res.body.data).to.have.string("Email address already in use");
                        done();
                    });
            });

        });

        describe("Login", function () {

            var credentials;

            beforeEach(function () {
                credentials = useData(testData.validUser);
                credentials = {
                    username: credentials.username,
                    password: credentials.password
                };
            });

            it("should return login success when valid credentials are passed", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.login)
                    .send(credentials)
                    .end(function (res) {
                        expect(res.body.success).to.be.true;
                        expect(res.body.message).to.have.string("Authentication success");
                        done();
                    });
            });

            it("should fail when attempting to login with a username that doesn't exist", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.login)
                    .send(_.extend(credentials, { username: "foo" }))
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.message).to.have.string("Authentication failed");
                        expect(res.body.data).to.have.string("User not found");
                        done();
                    });
            });

            it("should fail when attempting to login with a valid user and an invalid password", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.login)
                    .send(_.extend(credentials, { password: "Pas$w0rd!"}))
                    .end(function (res) {
                        expect(res.body.success).to.be.false;
                        expect(res.body.message).to.have.string("Authentication failed");
                        expect(res.body.data).to.have.string("Invalid password");
                        done();
                    });
            });

            xit("should establish a user session after successful login/authentication", function (done) {
                request
                    .post(routes.apiRoot + routes.auth.login)
                    .send(credentials)
                    .end(function (res) {
                        done();
                    });
            });

        });

        describe("Logout", function () {

            xit("should destroy the existing user session after successful logout", function (done) {

            });

        });

        describe("Change password", function () {

        });

    });

};


text:
import pprint

from oslo_config import cfg
from oslo_log import log as logging

from designate.manage import base
from designate import objects

LOG = logging.getLogger(__name__)
CONF = cfg.CONF

class PoolCommands(base.Commands):
    def show_config(self):
        print('*' * 100)
        print('Pool Configuration:')
        print('*' * 100)
        pprint.pprint(objects.Pool.from_config(CONF).to_dict())

redpajama_set_name: RedPajamaGithub


text:
module GH
  class Client

    attr_reader :client_id, :client_secret

    attr_accessor :access_token

    def initialize(client_id, client_secret, access_token = nil)
      @client_id, @client_secret, @access_token = client_id, client_secret, access_token
    end

    def get_access_token!(code)
      result = Request.post(
        'https://github.com/login/oauth/access_token',
        payload: {
          client_id: client_id,
          client_secret: client_secret,
          code: code
        }
      )

      self.access_token = JSON.parse(result)['access_token']
    end

    def fetch(url)
      result = Request.get(url, access_token: access_token, client_id: client_id, client_secret: client_secret)
      JSON.parse(result)
    end

    def user
      @user ||= if access_token
                  user = GH::User.new(self)
                  user.fetch!
                  user
                end
    end

  end
end


text:
require 'rails_helper'

RSpec.describe Scoutlander::Reader::Base do
  let(:base) { Scoutlander::Reader::Base.new }

  describe '.find_collection_elements_with' do
    before do
      @adults = []
      @adults << @adult1 = Scoutlander::Datum::Person.new(first_name: 'Rufus', last_name: 'Smith', rank: '1')
      @adults << @adult2 = Scoutlander::Datum::Person.new(first_name: 'Rob', last_name: 'Smith', rank: '2')
      @adults << @adult3 = Scoutlander::Datum::Person.new(first_name: 'Rufus', last_name: 'Smith', rank: '3')
      @adults << @adult4 = Scoutlander::Datum::Person.new(first_name: 'Tom', last_name: 'Thomas', rank: '4')
      base.collection = @adults
    end

    specify { expect(base.find_collection_elements_with(first_name: 'Rob')).to be_a(Array) }
    specify { expect(base.find_collection_elements_with(first_name: 'asdfasdf')).to be_a(Array) }

    context 'with single element finder' do
      specify { expect(base.find_collection_elements_with(first_name: 'Rob')).to include(@adult2) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rob')).to eq([@adult2]) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rob')).not_to include(@adult1) }

      specify { expect(base.find_collection_elements_with(first_name: 'Tom')).to include(@adult4) }
      specify { expect(base.find_collection_elements_with(first_name: 'Tom')).not_to include(@adult1) }

      specify { expect(base.find_collection_elements_with(rank: '3')).to eq([@adult3]) }
      specify { expect(base.find_collection_elements_with(rank: '5')).to eq([]) }
    end

    context 'multiple element finder' do
      specify { expect(base.find_collection_elements_with(first_name: 'Rob', last_name: 'Smith')).to include(@adult2) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rob', last_name: 'Smith')).not_to include(@adult1) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rob', last_name: 'Smith')).not_to include(@adult3) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rob', last_name: 'Smith')).not_to include(@adult4) }
    end

    context 'returns multiple found elements' do
      specify { expect(base.find_collection_elements_with(first_name: 'Rufus', last_name: 'Smith')).to include(@adult1) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rufus', last_name: 'Smith')).to include(@adult3) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rufus', last_name: 'Smith')).not_to include(@adult2) }
      specify { expect(base.find_collection_elements_with(first_name: 'Rufus', last_name: 'Smith')).not_to include(@adult4) }
    end
  end
end


text:
FROM aasmith/haproxy:1.7

COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg

CMD haproxy -db -f /usr/local/etc/haproxy/haproxy.cfg


text:
namespace content {

namespace {

void RunSoon(const base::Closure& closure) {
  base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, closure);
}

}  // namespace

typedef ServiceWorkerRegisterJobBase::RegistrationJobType RegistrationJobType;

ServiceWorkerRegisterJob::ServiceWorkerRegisterJob(
    base::WeakPtr<ServiceWorkerContextCore> context,
    const GURL& pattern,
    const GURL& script_url)
    : context_(context),
      job_type_(REGISTRATION_JOB),
      pattern_(pattern),
      script_url_(script_url),
      phase_(INITIAL),
      doom_installing_worker_(false),
      is_promise_resolved_(false),
      should_uninstall_on_failure_(false),
      force_bypass_cache_(false),
      promise_resolved_status_(SERVICE_WORKER_OK),
      weak_factory_(this) {
}

ServiceWorkerRegisterJob::ServiceWorkerRegisterJob(
    base::WeakPtr<ServiceWorkerContextCore> context,
    ServiceWorkerRegistration* registration,
    bool force_bypass_cache)
    : context_(context),
      job_type_(UPDATE_JOB),
      pattern_(registration->pattern()),
      script_url_(registration->GetNewestVersion()->script_url()),
      phase_(INITIAL),
      doom_installing_worker_(false),
      is_promise_resolved_(false),
      should_uninstall_on_failure_(false),
      force_bypass_cache_(force_bypass_cache),
      promise_resolved_status_(SERVICE_WORKER_OK),
      weak_factory_(this) {
  internal_.registration = registration;
}

ServiceWorkerRegisterJob::~ServiceWorkerRegisterJob() {
  DCHECK(!context_ ||
         phase_ == INITIAL || phase_ == COMPLETE || phase_ == ABORT)
      << "Jobs should only be interrupted during shutdown.";
}

void ServiceWorkerRegisterJob::AddCallback(
    const RegistrationCallback& callback,
    ServiceWorkerProviderHost* provider_host) {
  if (!is_promise_resolved_) {
    callbacks_.push_back(callback);
    if (provider_host)
      provider_host->AddScopedProcessReferenceToPattern(pattern_);
    return;
  }
  RunSoon(base::Bind(callback, promise_resolved_status_,
                     promise_resolved_status_message_,
                     promise_resolved_registration_));
}

void ServiceWorkerRegisterJob::Start() {
  BrowserThread::PostAfterStartupTask(
      FROM_HERE, base::ThreadTaskRunnerHandle::Get(),
      base::Bind(&ServiceWorkerRegisterJob::StartImpl,
                 weak_factory_.GetWeakPtr()));
}

void ServiceWorkerRegisterJob::StartImpl() {
  SetPhase(START);
  ServiceWorkerStorage::FindRegistrationCallback next_step;
  if (job_type_ == REGISTRATION_JOB) {
    next_step = base::Bind(
        &ServiceWorkerRegisterJob::ContinueWithRegistration,
        weak_factory_.GetWeakPtr());
  } else {
    next_step = base::Bind(
        &ServiceWorkerRegisterJob::ContinueWithUpdate,
        weak_factory_.GetWeakPtr());
  }

  scoped_refptr<ServiceWorkerRegistration> registration =
      context_->storage()->GetUninstallingRegistration(pattern_);
  if (registration.get())
    RunSoon(base::Bind(next_step, SERVICE_WORKER_OK, registration));
  else
    context_->storage()->FindRegistrationForPattern(pattern_, next_step);
}

void ServiceWorkerRegisterJob::Abort() {
  SetPhase(ABORT);
  CompleteInternal(SERVICE_WORKER_ERROR_ABORT, std::string());
  // Don't have to call FinishJob() because the caller takes care of removing
  // the jobs from the queue.
}

bool ServiceWorkerRegisterJob::Equals(ServiceWorkerRegisterJobBase* job) const {
  if (job->GetType() != GetType())
    return false;
  ServiceWorkerRegisterJob* register_job =
      static_cast<ServiceWorkerRegisterJob*>(job);
  return register_job->pattern_ == pattern_ &&
         register_job->script_url_ == script_url_;
}

RegistrationJobType ServiceWorkerRegisterJob::GetType() const {
  return job_type_;
}

void ServiceWorkerRegisterJob::DoomInstallingWorker() {
  doom_installing_worker_ = true;
  if (phase_ == INSTALL)
    Complete(SERVICE_WORKER_ERROR_INSTALL_WORKER_FAILED, std::string());
}

ServiceWorkerRegisterJob::Internal::Internal() {}

ServiceWorkerRegisterJob::Internal::~Internal() {}

void ServiceWorkerRegisterJob::set_registration(
    const scoped_refptr<ServiceWorkerRegistration>& registration) {
  DCHECK(phase_ == START || phase_ == REGISTER) << phase_;
  DCHECK(!internal_.registration.get());
  internal_.registration = registration;
}

ServiceWorkerRegistration* ServiceWorkerRegisterJob::registration() {
  DCHECK(phase_ >= REGISTER || job_type_ == UPDATE_JOB) << phase_;
  return internal_.registration.get();
}

void ServiceWorkerRegisterJob::set_new_version(
    ServiceWorkerVersion* version) {
  DCHECK(phase_ == UPDATE) << phase_;
  DCHECK(!internal_.new_version.get());
  internal_.new_version = version;
}

ServiceWorkerVersion* ServiceWorkerRegisterJob::new_version() {
  DCHECK(phase_ >= UPDATE) << phase_;
  return internal_.new_version.get();
}

void ServiceWorkerRegisterJob::SetPhase(Phase phase) {
  switch (phase) {
    case INITIAL:
      NOTREACHED();
      break;
    case START:
      DCHECK(phase_ == INITIAL) << phase_;
      break;
    case REGISTER:
      DCHECK(phase_ == START) << phase_;
      break;
    case UPDATE:
      DCHECK(phase_ == START || phase_ == REGISTER) << phase_;
      break;
    case INSTALL:
      DCHECK(phase_ == UPDATE) << phase_;
      break;
    case STORE:
      DCHECK(phase_ == INSTALL) << phase_;
      break;
    case COMPLETE:
      DCHECK(phase_ != INITIAL && phase_ != COMPLETE) << phase_;
      break;
    case ABORT:
      break;
  }
  phase_ = phase;
}

// This function corresponds to the steps in [[Register]] following
// "Let registration be the result of running the [[GetRegistration]] algorithm.
// Throughout this file, comments in quotes are excerpts from the spec.
void ServiceWorkerRegisterJob::ContinueWithRegistration(
    ServiceWorkerStatusCode status,
    const scoped_refptr<ServiceWorkerRegistration>& existing_registration) {
  DCHECK_EQ(REGISTRATION_JOB, job_type_);
  if (status != SERVICE_WORKER_ERROR_NOT_FOUND && status != SERVICE_WORKER_OK) {
    Complete(status);
    return;
  }

  if (!existing_registration.get() || existing_registration->is_uninstalled()) {
    RegisterAndContinue();
    return;
  }

  DCHECK(existing_registration->GetNewestVersion());
  // "If scriptURL is equal to registration.[[ScriptURL]], then:"
  if (existing_registration->GetNewestVersion()->script_url() == script_url_) {
    // "Set registration.[[Uninstalling]] to false."
    existing_registration->AbortPendingClear(base::Bind(
        &ServiceWorkerRegisterJob::ContinueWithRegistrationForSameScriptUrl,
        weak_factory_.GetWeakPtr(),
        existing_registration));
    return;
  }

  if (existing_registration->is_uninstalling()) {
    existing_registration->AbortPendingClear(base::Bind(
        &ServiceWorkerRegisterJob::ContinueWithUninstallingRegistration,
        weak_factory_.GetWeakPtr(),
        existing_registration));
    return;
  }

  // "Return the result of running the [[Update]] algorithm, or its equivalent,
  // passing registration as the argument."
  set_registration(existing_registration);
  UpdateAndContinue();
}

void ServiceWorkerRegisterJob::ContinueWithUpdate(
    ServiceWorkerStatusCode status,
    const scoped_refptr<ServiceWorkerRegistration>& existing_registration) {
  DCHECK_EQ(UPDATE_JOB, job_type_);
  if (status != SERVICE_WORKER_OK) {
    Complete(status);
    return;
  }

  if (existing_registration.get() != registration()) {
    Complete(SERVICE_WORKER_ERROR_NOT_FOUND);
    return;
  }

  // A previous job may have unregistered or installed a new version to this
  // registration.
  if (registration()->is_uninstalling() ||
      registration()->GetNewestVersion()->script_url() != script_url_) {
    Complete(SERVICE_WORKER_ERROR_NOT_FOUND);
    return;
  }

  // TODO(michaeln): If the last update check was less than 24 hours
  // ago, depending on the freshness of the cached worker script we
  // may be able to complete the update job right here.

  UpdateAndContinue();
}

// Creates a new ServiceWorkerRegistration.
void ServiceWorkerRegisterJob::RegisterAndContinue() {
  SetPhase(REGISTER);

  set_registration(new ServiceWorkerRegistration(
      pattern_, context_->storage()->NewRegistrationId(), context_));
  AddRegistrationToMatchingProviderHosts(registration());
  UpdateAndContinue();
}

void ServiceWorkerRegisterJob::ContinueWithUninstallingRegistration(
    const scoped_refptr<ServiceWorkerRegistration>& existing_registration,
    ServiceWorkerStatusCode status) {
  if (status != SERVICE_WORKER_OK) {
    Complete(status);
    return;
  }
  should_uninstall_on_failure_ = true;
  set_registration(existing_registration);
  UpdateAndContinue();
}

void ServiceWorkerRegisterJob::ContinueWithRegistrationForSameScriptUrl(
    const scoped_refptr<ServiceWorkerRegistration>& existing_registration,
    ServiceWorkerStatusCode status) {
  if (status != SERVICE_WORKER_OK) {
    Complete(status);
    return;
  }
  set_registration(existing_registration);

  // "If newestWorker is not null, and scriptURL is equal to
  // newestWorker.scriptURL, then:
  // Return a promise resolved with registration."
  // We resolve only if there's an active version. If there's not,
  // then there is either no version or only a waiting version from
  // the last browser session; it makes sense to proceed with registration in
  // either case.
  DCHECK(!existing_registration->installing_version());
  if (existing_registration->active_version()) {
    ResolvePromise(status, std::string(), existing_registration.get());
    Complete(SERVICE_WORKER_OK);
    return;
  }

  // "Return the result of running the [[Update]] algorithm, or its equivalent,
  // passing registration as the argument."
  UpdateAndContinue();
}

// This function corresponds to the spec's [[Update]] algorithm.
void ServiceWorkerRegisterJob::UpdateAndContinue() {
  SetPhase(UPDATE);
  context_->storage()->NotifyInstallingRegistration(registration());

  // "Let worker be a new ServiceWorker object..." and start
  // the worker.
  set_new_version(new ServiceWorkerVersion(registration(),
                                           script_url_,
                                           context_->storage()->NewVersionId(),
                                           context_));
  new_version()->set_force_bypass_cache_for_scripts(force_bypass_cache_);
  new_version()->StartWorker(
      base::Bind(&ServiceWorkerRegisterJob::OnStartWorkerFinished,
                 weak_factory_.GetWeakPtr()));
}

void ServiceWorkerRegisterJob::OnStartWorkerFinished(
    ServiceWorkerStatusCode status) {
  if (status == SERVICE_WORKER_OK) {
    InstallAndContinue();
    return;
  }

  // The updated worker is identical to the incumbent.
  if (status == SERVICE_WORKER_ERROR_EXISTS) {
    // Only bump the last check time when we've bypassed the browser cache.
    base::TimeDelta time_since_last_check =
        base::Time::Now() - registration()->last_update_check();
    if (time_since_last_check > base::TimeDelta::FromHours(
                                    kServiceWorkerScriptMaxCacheAgeInHours) ||
        new_version()->force_bypass_cache_for_scripts()) {
      registration()->set_last_update_check(base::Time::Now());
      context_->storage()->UpdateLastUpdateCheckTime(registration());
    }

    ResolvePromise(SERVICE_WORKER_OK, std::string(), registration());
    Complete(status, "The updated worker is identical to the incumbent.");
    return;
  }

  // "If serviceWorker fails to start up..." then reject the promise with an
  // error and abort.
  if (status == SERVICE_WORKER_ERROR_TIMEOUT) {
    Complete(status, "Timed out while trying to start the Service Worker.");
    return;
  }

  const net::URLRequestStatus& main_script_status =
      new_version()->script_cache_map()->main_script_status();
  std::string message;
  if (main_script_status.status() != net::URLRequestStatus::SUCCESS) {
    message = new_version()->script_cache_map()->main_script_status_message();
    if (message.empty())
      message = kFetchScriptError;
  }
  Complete(status, message);
}

// This function corresponds to the spec's [[Install]] algorithm.
void ServiceWorkerRegisterJob::InstallAndContinue() {
  SetPhase(INSTALL);

  // "Set registration.installingWorker to worker."
  DCHECK(!registration()->installing_version());
  registration()->SetInstallingVersion(new_version());

  // "Run the Update State algorithm passing registration's installing worker
  // and installing as the arguments."
  new_version()->SetStatus(ServiceWorkerVersion::INSTALLING);

  // "Resolve registrationPromise with registration."
  ResolvePromise(SERVICE_WORKER_OK, std::string(), registration());

  // "Fire a simple event named updatefound..."
  registration()->NotifyUpdateFound();

  // "Fire an event named install..."
  new_version()->DispatchInstallEvent(
      base::Bind(&ServiceWorkerRegisterJob::OnInstallFinished,
                 weak_factory_.GetWeakPtr()));

  // A subsequent registration job may terminate our installing worker. It can
  // only do so after we've started the worker and dispatched the install
  // event, as those are atomic substeps in the [[Install]] algorithm.
  if (doom_installing_worker_)
    Complete(SERVICE_WORKER_ERROR_INSTALL_WORKER_FAILED);
}

void ServiceWorkerRegisterJob::OnInstallFinished(
    ServiceWorkerStatusCode status) {
  ServiceWorkerMetrics::RecordInstallEventStatus(status);

  if (status != SERVICE_WORKER_OK) {
    // "8. If installFailed is true, then:..."
    Complete(status);
    return;
  }

  SetPhase(STORE);
  registration()->set_last_update_check(base::Time::Now());
  context_->storage()->StoreRegistration(
      registration(),
      new_version(),
      base::Bind(&ServiceWorkerRegisterJob::OnStoreRegistrationComplete,
                 weak_factory_.GetWeakPtr()));
}

void ServiceWorkerRegisterJob::OnStoreRegistrationComplete(
    ServiceWorkerStatusCode status) {
  if (status != SERVICE_WORKER_OK) {
    Complete(status);
    return;
  }

  // "9. If registration.waitingWorker is not null, then:..."
  if (registration()->waiting_version()) {
    // "1. Run the [[UpdateState]] algorithm passing registration.waitingWorker
    // and "redundant" as the arguments."
    registration()->waiting_version()->SetStatus(
        ServiceWorkerVersion::REDUNDANT);
  }

  // "10. Set registration.waitingWorker to registration.installingWorker."
  // "11. Set registration.installingWorker to null."
  registration()->SetWaitingVersion(new_version());

  // "12. Run the [[UpdateState]] algorithm passing registration.waitingWorker
  // and "installed" as the arguments."
  new_version()->SetStatus(ServiceWorkerVersion::INSTALLED);

  // "If registration's waiting worker's skip waiting flag is set:" then
  // activate the worker immediately otherwise "wait until no service worker
  // client is using registration as their service worker registration."
  registration()->ActivateWaitingVersionWhenReady();

  Complete(SERVICE_WORKER_OK);
}

void ServiceWorkerRegisterJob::Complete(ServiceWorkerStatusCode status) {
  Complete(status, std::string());
}

void ServiceWorkerRegisterJob::Complete(ServiceWorkerStatusCode status,
                                        const std::string& status_message) {
  CompleteInternal(status, status_message);
  context_->job_coordinator()->FinishJob(pattern_, this);
}

void ServiceWorkerRegisterJob::CompleteInternal(
    ServiceWorkerStatusCode status,
    const std::string& status_message) {
  SetPhase(COMPLETE);
  if (status != SERVICE_WORKER_OK) {
    if (registration()) {
      if (should_uninstall_on_failure_)
        registration()->ClearWhenReady();
      if (new_version()) {
        if (status == SERVICE_WORKER_ERROR_EXISTS)
          new_version()->SetStartWorkerStatusCode(SERVICE_WORKER_ERROR_EXISTS);
        else
          new_version()->ReportError(status, status_message);
        registration()->UnsetVersion(new_version());
        new_version()->Doom();
      }
      if (!registration()->waiting_version() &&
          !registration()->active_version()) {
        registration()->NotifyRegistrationFailed();
        context_->storage()->DeleteRegistration(
            registration()->id(),
            registration()->pattern().GetOrigin(),
            base::Bind(&ServiceWorkerUtils::NoOpStatusCallback));
      }
    }
    if (!is_promise_resolved_)
      ResolvePromise(status, status_message, NULL);
  }
  DCHECK(callbacks_.empty());
  if (registration()) {
    context_->storage()->NotifyDoneInstallingRegistration(
        registration(), new_version(), status);
    if (registration()->waiting_version() || registration()->active_version())
      registration()->set_is_uninstalled(false);
  }
}

void ServiceWorkerRegisterJob::ResolvePromise(
    ServiceWorkerStatusCode status,
    const std::string& status_message,
    ServiceWorkerRegistration* registration) {
  DCHECK(!is_promise_resolved_);

  is_promise_resolved_ = true;
  promise_resolved_status_ = status;
  promise_resolved_status_message_ = status_message,
  promise_resolved_registration_ = registration;
  for (std::vector<RegistrationCallback>::iterator it = callbacks_.begin();
       it != callbacks_.end();
       ++it) {
    it->Run(status, status_message, registration);
  }
  callbacks_.clear();
}

void ServiceWorkerRegisterJob::AddRegistrationToMatchingProviderHosts(
    ServiceWorkerRegistration* registration) {
  DCHECK(registration);
  for (scoped_ptr<ServiceWorkerContextCore::ProviderHostIterator> it =
           context_->GetProviderHostIterator();
       !it->IsAtEnd(); it->Advance()) {
    ServiceWorkerProviderHost* host = it->GetProviderHost();
    if (host->IsHostToRunningServiceWorker())
      continue;
    if (!ServiceWorkerUtils::ScopeMatches(registration->pattern(),
                                          host->document_url()))
      continue;
    host->AddMatchingRegistration(registration);
  }
}

}  // namespace content


text:
package com.asha.vrlib.model;

import com.asha.vrlib.MD360Director;

/**
 * Created by hzqiujiadi on 2017/4/20.
 * hzqiujiadi ashqalcn@gmail.com
 */

public class MDDirectorSnapshot {

    private float[] viewMatrix = new float[16];
    private float[] projectionMatrix = new float[16];
    private float viewportWidth;
    private float viewportHeight;

    public float[] getViewMatrix() {
        return viewMatrix;
    }

    public float[] getProjectionMatrix() {
        return projectionMatrix;
    }

    public float getViewportWidth() {
        return viewportWidth;
    }

    public float getViewportHeight() {
        return viewportHeight;
    }

    public void copy(MD360Director director) {
        this.viewportWidth = director.getViewportWidth();
        this.viewportHeight = director.getViewportHeight();

        System.arraycopy(director.getViewMatrix(), 0, viewMatrix, 0, 16);
        System.arraycopy(director.getProjectionMatrix(), 0, projectionMatrix, 0, 16);
    }
}


text:
#import "../AmazonServiceRequest.h"

#import "SimpleDBRequest.h"
#import "SimpleDBCreateDomainRequest.h"

/**
 * Create Domain Request Marshaller
 */
@interface SimpleDBCreateDomainRequestMarshaller:NSObject {
}

+(AmazonServiceRequest *)createRequest:(SimpleDBCreateDomainRequest *)createDomainRequest;

@end


text:
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

const Badge = ({ className, newIcon, children, ...props }) => {
  let classes = {
    badge: true,
    'new': newIcon
  };

  return (
    <span {...props} className={cx(classes, className)}>
      {children}
    </span>
  );
};

Badge.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  /**
   * Add the <b>new</b> class name
   */
  newIcon: PropTypes.bool
};

export default Badge;


text:
package br.com.caelum;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class Inicializador extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { Configurador.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		super.onStartup(servletContext);

		// Descomente abaixo para ligar log4j!

		//servletContext.setInitParameter("log4jConfigLocation", "/WEB-INF/log4j.xml");
		//servletContext.addListener(new Log4jConfigListener());

	}

}


text:
/*************************************************
 * dict.formatter.ewords.js
 **************************************************/
;(function($){
'use strict';
var D= $.dict_extend();
// A plugin name starts with `auto_` will call `Auto Mode` first.
// Then when prefix match prefix defined in NON `auto` version, NON `auto` version will be fired
// Why do this: search result from google is much better.
D.DICT_PLUGINS.auto_ewords = {
    'autoKey'   : 'site:e-words.jp', // a key will append to search result when `Auto Mode`
    'nextLoader': 'ewords',  // same as defined bellow.
}
var option = D.DICT_PLUGINS.ewords = {
    'type' : 'ewords',
    'host' : '//e-words.jp/w',
    //'mobile_host' : '//sp.e-words.jp', // NG cause e-words SP layout not support YQL
    'prefix': [ /^http:\/\/e\-words\.jp\/w\/([^\/]+).html$/   ,  /^http:\/\/sp\.e\-words\.jp\/w\/([^\/]+).html$/  ] ,  // key is not always a word. e.g: E8A898E686B6E5AA92E4BD93.html
    'format': formatEWords,
    'removeTags': ['title','meta','iframe','noscript','script','link','form','nobr'],
    'isCleanLinks': true,
};

// JSON sample
function formatEWords(src) {
    console.log(D.LC, '[dict.formatter.ewords.js] format start...');
    return D.preFormat(option, src, customizePage);
}

// Customize for this page
function customizePage($target){//,#left-navigation

    var $sideBar = $('td#side', $target);
    var $content = $sideBar.parent().parent().parent();

    var $styles = $('style', $target);
    $content.append($styles); // add tooltips
    //$sideBar.prependTo($sideBar.parent()); // Move side bar to left side

    $('[width]', $content).andSelf().removeAttr('width').css("width","auto");
    $('.adsbygoogle', $content).remove();
    //$('#linkunit>div', $content).nextAll().remove();

    // Enable tooltips
    $('a', $content).addClass('dict-css-tooltip');

    var $delTheGenDate = $("#hr", $target).nextAll();
    if ( /\/\/[0-9.]+生成/.test( $delTheGenDate.text().replace(/\s|\n/g,'') ) ){
        $delTheGenDate.remove();
    }
    // use return for replacing $target with $content
    return $content;
}

})(jQuery);


text:
@implementation UIDevice (WLAddForInfo)

+ (NSString *)systemVersion{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *) idForDevice;
{
    NSString *result = @"";
//    BOOL found=FALSE;
//
//    NSError *error = nil;
//    SSKeychainQuery *query = [[SSKeychainQuery alloc] init];
//    query.service = @"com.chuansongmen.welianos";
//    query.account = @"udid";
//    [query fetch:&error];
//
//    if ([error code] == errSecItemNotFound) {
//        NSLog(@"Udid NOT FOUND in keychain.");
//    } else if (error != nil) {
//        NSLog(@"Some other error occurred when query keychain: %@", [error localizedDescription]);
//    } else {
//        //取出存储的UdId
//        result=query.password;
//        found=TRUE;
//        NSLog(@"Udid FOUND in keychain.");
//    }
//
//    if (!found) {
//        UIDevice *thisDevice = [UIDevice currentDevice];
//        if ([thisDevice respondsToSelector: @selector(identifierForVendor)])
//        {
//            NSUUID *myID = [[UIDevice currentDevice] identifierForVendor];
//            result = [myID UUIDString];
//        }
//        else
//        {
//            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//            result = [defaults objectForKey: @"appDeviceId"];
//            if (!result)
//            {
//                CFUUIDRef myCFUUID = CFUUIDCreate(kCFAllocatorDefault);
//                result = (__bridge_transfer NSString *) CFUUIDCreateString(kCFAllocatorDefault, myCFUUID);
//                result=[result copy];
//                [defaults setObject: result forKey: @"appDeviceId"];
//                [defaults synchronize];
//                CFRelease(myCFUUID);
//            }
//        }
//
//        //存储Udid
//        query.password = result;
//        [query save:&error];
//
//        if (error != nil) {
//            NSLog(@"Some other error occurred when save keychain: %@", [error localizedDescription]);
//        }
//        else
//            NSLog(@"Save udid to keychain successed!");
//
//    }

    return result;
}

#pragma mark -
+ (NSDictionary *)getDeviceList {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"DeviceList" ofType:@"plist"];
    NSDictionary *deviceList = [NSDictionary dictionaryWithContentsOfFile:path];
    NSAssert(deviceList != nil, @"DevicePlist not found in the bundle.");
    return deviceList;
}

+ (NSString*)hardwareDescription {
    NSString *hardware = [self hardwareString];
    NSDictionary *deviceList = [self getDeviceList];
    NSString *hardwareDescription = [[deviceList objectForKey:hardware] objectForKey:@"name"];
    if (hardwareDescription) {
        return hardwareDescription;
    }
    else {
        return [NSString stringWithFormat:@"iOS Unknow Device:%@",hardware];
    }
}

+ (NSString*)hardwareString {
    int name[] = {CTL_HW,HW_MACHINE};
    size_t size = 100;
    sysctl(name, 2, NULL, &size, NULL, 0); // getting size of answer
    char *hw_machine = malloc(size);

    sysctl(name, 2, hw_machine, &size, NULL, 0);
    NSString *hardware = [NSString stringWithUTF8String:hw_machine];
    free(hw_machine);
    return hardware;
}

+ (NSString *)description{
    NSString *desc = [NSString stringWithFormat:@"\n设备型号:%@;\n系统版本:%@;\n设备ID:%@;\n",[self hardwareDescription],[self systemVersion],[self idForDevice]];
//    DLog(@"%@",desc);
    return desc;
}

@end


text:
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar

from msrest import Serializer

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models as _models
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_list_request(
    subscription_id: str,
    *,
    billing_location: Optional[str] = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop('api_version', _params.pop('api-version', "2016-03-01"))  # type: str
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/subscriptions/{subscriptionId}/providers/Microsoft.Web/billingMeters")
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    if billing_location is not None:
        _params['billingLocation'] = _SERIALIZER.query("billing_location", billing_location, 'str')
    _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        params=_params,
        headers=_headers,
        **kwargs
    )

class BillingMetersOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.web.v2016_03_01.WebSiteManagementClient`'s
        :attr:`billing_meters` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self,
        billing_location: Optional[str] = None,
        **kwargs: Any
    ) -> Iterable[_models.BillingMeterCollection]:
        """Gets a list of meters for a given location.

        Gets a list of meters for a given location.

        :param billing_location: Azure Location of billable resource. Default value is None.
        :type billing_location: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either BillingMeterCollection or the result of
         cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.web.v2016_03_01.models.BillingMeterCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2016-03-01"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.BillingMeterCollection]

        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})
        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_request(
                    subscription_id=self._config.subscription_id,
                    api_version=api_version,
                    billing_location=billing_location,
                    template_url=self.list.metadata['url'],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:

                request = build_list_request(
                    subscription_id=self._config.subscription_id,
                    api_version=api_version,
                    billing_location=billing_location,
                    template_url=next_link,
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("BillingMeterCollection", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # pylint: disable=protected-access
                request,
                stream=False,
                **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list.metadata = {'url': "/subscriptions/{subscriptionId}/providers/Microsoft.Web/billingMeters"}  # type: ignore


text:
package org.agilos.zendesk_jira_plugin.testframework;

public class JIRAVersion {
	public static final String JIRA_432 = "4.3.2";

	public static String getJiraVersion() {
		return System.getProperty("jira.deploy.version", "4.3.2");
	}
}


text:
"""Replacements for sys.displayhook that publish over ZMQ."""

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

import sys

from IPython.core.displayhook import DisplayHook
from ipykernel.jsonutil import encode_images, json_clean
from ipython_genutils.py3compat import builtin_mod
from traitlets import Instance, Dict, Any
from jupyter_client.session import extract_header, Session

class ZMQDisplayHook(object):
    """A simple displayhook that publishes the object's repr over a ZeroMQ
    socket."""
    topic = b'execute_result'

    def __init__(self, session, pub_socket):
        self.session = session
        self.pub_socket = pub_socket
        self.parent_header = {}

    def get_execution_count(self):
        """This method is replaced in kernelapp"""
        return 0

    def __call__(self, obj):
        if obj is None:
            return

        builtin_mod._ = obj
        sys.stdout.flush()
        sys.stderr.flush()
        contents = {u'execution_count': self.get_execution_count(),
                    u'data': {'text/plain': repr(obj)},
                    u'metadata': {}}
        self.session.send(self.pub_socket, u'execute_result', contents,
                          parent=self.parent_header, ident=self.topic)

    def set_parent(self, parent):
        self.parent_header = extract_header(parent)

class ZMQShellDisplayHook(DisplayHook):
    """A displayhook subclass that publishes data using ZeroMQ. This is intended
    to work with an InteractiveShell instance. It sends a dict of different
    representations of the object."""
    topic=None

    session = Instance(Session, allow_none=True)
    pub_socket = Any(allow_none=True)
    parent_header = Dict({})

    def set_parent(self, parent):
        """Set the parent for outbound messages."""
        self.parent_header = extract_header(parent)

    def start_displayhook(self):
        self.msg = self.session.msg(u'execute_result', {
            'data': {},
            'metadata': {},
        }, parent=self.parent_header)

    def write_output_prompt(self):
        """Write the output prompt."""
        self.msg['content']['execution_count'] = self.prompt_count

    def write_format_data(self, format_dict, md_dict=None):
        self.msg['content']['data'] = json_clean(encode_images(format_dict))
        self.msg['content']['metadata'] = md_dict

    def finish_displayhook(self):
        """Finish up all displayhook activities."""
        sys.stdout.flush()
        sys.stderr.flush()
        if self.msg['content']['data']:
            self.session.send(self.pub_socket, self.msg, ident=self.topic)
        self.msg = None


text:
// This file is automatically generated.

package adila.db;

/*
 * Multilaser Ms6
 *
 * DEVICE: MS6
 * MODEL: MS6
 */
final class ms6_ms6 {
    public static final String DATA = "Multilaser|Ms6|";
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>static_pages.css.scss</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" />

            static_pages.css.scss

app/assets/stylesheets/static_pages.css.scss

Last modified: 2014-12-20 08:45:12 -0300

// Place all the styles related to the static_pages controller here. //
They will automatically be included in application.css. // You can use Sass
(SCSS) here: sass-lang.com/


text:
package org.jetbrains.plugins.scala
package lang.completion

import com.intellij.codeInsight.completion._
import com.intellij.codeInsight.lookup.{LookupElement, LookupElementBuilder}
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.{PsiClass, PsiMethod, PsiParameter}
import com.intellij.ui.LayeredIcon
import com.intellij.util.ProcessingContext
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.icons.Icons
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScParameterizedTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.base.{ScConstructor, ScMethodLike}
import org.jetbrains.plugins.scala.lang.psi.api.expr.{ScArgumentExprList, ScMethodCall, ScReferenceExpression, ScSuperReference}
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScClass, ScTemplateDefinition}
import org.jetbrains.plugins.scala.lang.psi.types.api.TypeSystem
import org.jetbrains.plugins.scala.lang.psi.types.result.{Success, TypingContext}
import org.jetbrains.plugins.scala.lang.psi.types.{ScType, ScTypeExt}
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import org.jetbrains.plugins.scala.project.ProjectExt

import scala.collection.mutable.ArrayBuffer

/**
 * @author Alefas
 * @since 03.09.13
 */
class SameSignatureCallParametersProvider extends ScalaCompletionContributor {
  val constructorFilter = PlatformPatterns.psiElement().withParent(classOf[ScReferenceExpression]).
          withSuperParent(2, classOf[ScArgumentExprList]).withSuperParent(3, classOf[ScConstructor])

  val superCallFilter = PlatformPatterns.psiElement().withParent(classOf[ScReferenceExpression]).
          withSuperParent(2, classOf[ScArgumentExprList]).withSuperParent(3, classOf[ScMethodCall])

  extend(CompletionType.BASIC, constructorFilter, new CompletionProvider[CompletionParameters]() {
    def addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
      addConstructorCompletions(parameters, result)
    }
  })

  extend(CompletionType.SMART, constructorFilter, new CompletionProvider[CompletionParameters]() {
    def addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
      addConstructorCompletions(parameters, result)
    }
  })

  extend(CompletionType.BASIC, superCallFilter, new CompletionProvider[CompletionParameters]() {
    def addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
      addSuperCallCompletions(parameters, result)
    }
  })

  extend(CompletionType.SMART, superCallFilter, new CompletionProvider[CompletionParameters]() {
    def addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
      addSuperCallCompletions(parameters, result)
    }
  })

  private def addSuperCallCompletions(parameters: CompletionParameters, result: CompletionResultSet): Unit = {
    val position = positionFromParameters(parameters)
    val elementType = position.getNode.getElementType
    if (elementType != ScalaTokenTypes.tIDENTIFIER) return
    val call = PsiTreeUtil.getContextOfType(position, classOf[ScMethodCall])
    val args = PsiTreeUtil.getContextOfType(position, classOf[ScArgumentExprList])
    if (call == null || args == null) return
    val index = args.invocationCount - 1
    call.deepestInvokedExpr match {
      case ref: ScReferenceExpression =>
        ref.qualifier match {
          case Some(s: ScSuperReference) =>
            val function = PsiTreeUtil.getContextOfType(ref, classOf[ScFunction])
            if (function != null && function.name == ref.refName.inName) { //TODO: probably replace
              val variants = ref.getSimpleVariants(implicits = false, filterNotNamedVariants = false)
              val signatures = variants.toSeq.map {
                case ScalaResolveResult(fun: ScMethodLike, subst) =>
                  val params = fun.effectiveParameterClauses
                  if (params.length > index) params(index).effectiveParameters.map(p =>
                    (p.name, subst.subst(p.getType(TypingContext.empty).getOrAny)))
                  else Seq.empty
                case ScalaResolveResult(method: PsiMethod, subst) =>
                  if (index != 0) Seq.empty
                  else method.getParameterList.getParameters.toSeq.map {
                    case p: PsiParameter =>
                      (p.name, subst.subst(p.getType.toScType(position.getProject, position.getResolveScope)))
                  }
                case _ => Seq.empty
              }.filter(_.length > 1)

              if (signatures.isEmpty) return

              checkSignatures(signatures, function, result)
            }
          case _ =>
        }
      case _ =>
    }
  }

  private def addConstructorCompletions(parameters: CompletionParameters, result: CompletionResultSet) {
    val position = positionFromParameters(parameters)
    val elementType = position.getNode.getElementType
    if (elementType != ScalaTokenTypes.tIDENTIFIER) return
    PsiTreeUtil.getContextOfType(position, classOf[ScTemplateDefinition]) match {
      case c: ScClass =>
        val args = PsiTreeUtil.getContextOfType(position, classOf[ScArgumentExprList])
        val constructor = args.getContext.asInstanceOf[ScConstructor]
        val index = constructor.arguments.indexOf(args)
        val typeElement = constructor.typeElement
        typeElement.getType(TypingContext.empty) match {
          case Success(tp, _) =>
            val project = position.getProject
            implicit val typeSystem = project.typeSystem
            val signatures = tp.extractClassType(project) match {
              case Some((clazz: ScClass, subst)) if !clazz.hasTypeParameters || (clazz.hasTypeParameters &&
                      typeElement.isInstanceOf[ScParameterizedTypeElement]) =>
                clazz.constructors.toSeq.map {
                  case fun: ScMethodLike =>
                    val params = fun.effectiveParameterClauses
                    if (params.length > index) params(index).effectiveParameters.map(p =>
                      (p.name, subst.subst(p.getType(TypingContext.empty).getOrAny)))
                    else Seq.empty
                }.filter(_.length > 1)
              case Some((clazz: PsiClass, subst)) if !clazz.hasTypeParameters || (clazz.hasTypeParameters &&
                      typeElement.isInstanceOf[ScParameterizedTypeElement]) =>
                clazz.getConstructors.toSeq.map {
                  case c: PsiMethod =>
                    if (index != 0) Seq.empty
                    else c.getParameterList.getParameters.toSeq.map {
                      case p: PsiParameter =>
                        (p.name, subst.subst(p.getType.toScType(typeElement.getProject, typeElement.getResolveScope)))
                    }
                }.filter(_.length > 1)
              case _ => Seq.empty
            }

            if (signatures.isEmpty) return

            c.constructor match {
              case Some(constr) => checkSignatures(signatures, constr, result)
              case _ =>
            }
          case _ =>
        }
      case _ =>
    }
  }

  private def checkSignatures(signatures: Seq[Seq[(String, ScType)]], methodLike: ScMethodLike, result: CompletionResultSet)
                             (implicit typeSystem: TypeSystem = methodLike.typeSystem) {
    for (signature <- signatures if signature.forall(_._1 != null)) {
      val names = new ArrayBuffer[String]()
      val res = signature.map {
        case (name: String, tp: ScType) =>
          methodLike.parameterList.params.find(_.name == name) match {
            case Some(param) if param.getType(TypingContext.empty).getOrAny.conforms(tp) =>
              names += name
              name
            case _ => names += ""
          }
      }.mkString(", ")
      if (!names.contains("")) {
        val w: Int = Icons.PARAMETER.getIconWidth
        val icon: LayeredIcon = new LayeredIcon(2)
        icon.setIcon(Icons.PARAMETER, 0, 2 * w / 5, 0)
        icon.setIcon(Icons.PARAMETER, 1)
        val element = LookupElementBuilder.create(res).withIcon(icon).withInsertHandler(new InsertHandler[LookupElement] {
          def handleInsert(context: InsertionContext, item: LookupElement) {
            val completionChar = context.getCompletionChar
            if (completionChar == ')') return

            val file = context.getFile
            val element = file.findElementAt(context.getStartOffset)
            val exprs = PsiTreeUtil.getContextOfType(element, classOf[ScArgumentExprList])
            if (exprs == null) return
            context.getEditor.getCaretModel.moveToOffset(exprs.getTextRange.getEndOffset) // put caret after )
          }
        })
        element.putUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS, java.lang.Boolean.TRUE)
        result.addElement(element)
      }
    }
  }
}


text:
namespace Microsoft.Azure.Management.HealthcareApis.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// The mapping content.
    /// </summary>
    public partial class IotMappingProperties
    {
        /// <summary>
        /// Initializes a new instance of the IotMappingProperties class.
        /// </summary>
        public IotMappingProperties()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the IotMappingProperties class.
        /// </summary>
        /// <param name="content">The mapping.</param>
        public IotMappingProperties(object content = default(object))
        {
            Content = content;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the mapping.
        /// </summary>
        [JsonProperty(PropertyName = "content")]
        public object Content { get; set; }

    }
}


text:
/* Listing 44-6 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "tlpi_hdr.h"

#define SERVER_FIFO "/tmp/seqnum_sv"
                                /* Well-known name for server's FIFO */
#define CLIENT_FIFO_TEMPLATE "/tmp/seqnum_cl.%ld"
                                /* Template for building client FIFO name */
#define CLIENT_FIFO_NAME_LEN (sizeof(CLIENT_FIFO_TEMPLATE) + 20)
                                /* Space required for client FIFO pathname
                                  (+20 as a generous allowance for the PID) */

struct request {                /* Request (client --> server) */
    pid_t pid;                  /* PID of client */
    int seqLen;                 /* Length of desired sequence */
};

struct response {               /* Response (server --> client) */
    int seqNum;                 /* Start of sequence */
};


text:
call table_rotate('test_cs', 'test_table_rotate', 3);
call table_rotate('test_cs', 'test_table_rotate', 3);
call table_rotate('test_cs', 'test_table_rotate', 3);
SELECT
  table_exists('test_cs', 'test_table_rotate__3')
  and
  not table_exists('test_cs', 'test_table_rotate__4')
;


text:
package com.github.lukas_v.cdi.settings;

import java.util.Properties;

/**
 * Common interface for all classes that provide the ability
 * to load string representation of settings from implementation
 * dependent source.
 *
 * @author lukas-v
 */
public interface SettingsSource {

	/**
	 * Method returns string representation of current settings.
	 *
	 * @param properties library configuration that may be used
	 *
	 * @throws Exception exception may be thrown in case that something goes wrong
	 *
	 * @return string representation of current settings
	 */
	public String currentSettingsDocument(Properties properties) throws Exception;

}


text:
using AjourBT.Domain.Abstract;
using AjourBT.Helpers;
using Moq;
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace AjourBT.Tests.Helpers
{
    [TestFixture]
    public class CustomCreateWeekInterval
    {
        private class FakeHttpContext : HttpContextBase
        {
            private Dictionary<object, object> _items = new Dictionary<object, object>();
            public override IDictionary Items { get { return _items; } }
        }

        private class FakeViewDataContainer : IViewDataContainer
        {
            private ViewDataDictionary _viewData = new ViewDataDictionary();
            public ViewDataDictionary ViewData { get { return _viewData; } set { _viewData = value; } }
        }

        [Test]
        public void CustomWeekInterval_from2000_to2013()
        {
            //Arrange
            var vc = new ViewContext();
            vc.HttpContext = new FakeHttpContext();
            HtmlHelper helper = new HtmlHelper(vc, new FakeViewDataContainer());

            //Act
            List<Interval> result = helper.CustomCreateWeekInterval(2000, 2013, 12, 46);

            //Assert
            Assert.AreEqual(14, result.Count());
            Assert.AreEqual(12, result.ToArray()[0].weekFrom);
            Assert.AreEqual(52, result.ToArray()[0].weekTo);
            Assert.AreEqual(2000, result.ToArray()[0].year);
            Assert.AreEqual(1, result.ToArray()[6].weekFrom);
            Assert.AreEqual(52, result.ToArray()[6].weekTo);
            Assert.AreEqual(2006, result.ToArray()[6].year);
            Assert.AreEqual(1, result.ToArray()[13].weekFrom);
            Assert.AreEqual(46, result.ToArray()[13].weekTo);
            Assert.AreEqual(2013, result.ToArray()[13].year);
        }

        [Test]
        public void CustomInterval_from2013_to2013()
        {
            //Arrange
            var vc = new ViewContext();
            vc.HttpContext = new FakeHttpContext();
            HtmlHelper helper = new HtmlHelper(vc, new FakeViewDataContainer());

            //Act
            List<Interval> result = helper.CustomCreateWeekInterval(2013, 2013, 12, 46);

            //Assert
            Assert.AreEqual(1, result.Count());
            Assert.AreEqual(12, result.ToArray()[0].weekFrom);
            Assert.AreEqual(46, result.ToArray()[0].weekTo);
            Assert.AreEqual(2013, result.ToArray()[0].year);

        }
    }
}


text:
package de.jfranz.homepage.panel.menu;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.Fragment;

class LinkFragment extends Fragment {
	private static final long serialVersionUID = 1L;

	private static final String ID = "content";
	private static final String FRAGMENT_ID = "linkFragment";

	public LinkFragment(MenuItem link, WebMarkupContainer markupProvider) {
		super(ID, FRAGMENT_ID, markupProvider);
		setRenderBodyOnly(true);
		add(new ExternalLink("link", link.getHref(), link.getName()));
	}
}


text:
using OpenSage.Data.Ini;

namespace OpenSage.Logic.Object
{
    /// <summary>
    /// Special case module that allows parameters from W3DTankDraw and W3DTruckDraw to be used.
    /// Effectively this is a module that combines the other two.
    /// This can be useful for half track type units.
    /// </summary>
    public sealed class W3dTankTruckDrawModuleData : W3dTruckDrawModuleData
    {
        internal static new W3dTankTruckDrawModuleData Parse(IniParser parser) => parser.ParseBlock(FieldParseTable);

        internal static new readonly IniParseTable<W3dTankTruckDrawModuleData> FieldParseTable = W3dTruckDrawModuleData.FieldParseTable
            .Concat(new IniParseTable<W3dTankTruckDrawModuleData>
            {
                { "TreadAnimationRate", (parser, x) => x.TreadAnimationRate = parser.ParseFloat() },
                { "TreadDriveSpeedFraction", (parser, x) => x.TreadDriveSpeedFraction = parser.ParseFloat() },
                { "TreadPivotSpeedFraction", (parser, x) => x.TreadPivotSpeedFraction = parser.ParseFloat() },
            });

        // Duplicated from W3dTankDraw
        public float TreadAnimationRate { get; private set; }
        public float TreadDriveSpeedFraction { get; private set; }
        public float TreadPivotSpeedFraction { get; private set; }
    }
}


text:
package demo.oauth.server;

import java.io.Serializable;

public class ClientApp implements Serializable {
    private String clientName = "OAuth 1.0a client";
    private String callbackURL = "http://localhost:8080/app/callback";
    private String consumerKey;
    private String error;

    public String getClientName() {
        return clientName;
    }

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public String getCallbackURL() {
        return callbackURL;
    }

    public void setCallbackURL(String callbackURL) {
        this.callbackURL = callbackURL;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using TcpIpCore.Entity;

namespace TcpIpCore
{
    public class BasicClient
    {
        private Socket _SocketConnect = null;
        private IPEndPoint _SrvEndPoint;
        private string _Host = "127.0.0.1";
        private int _Port = 8888;

        public BasicClient()
        {
            InitClient();
        }

        private void InitClient()
        {
            _SocketConnect = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(_Host);
            _SrvEndPoint = new IPEndPoint(ip, _Port);

        }

        public void Connect(string ip,int port)
        {
            _Host = ip;
            _Port = port;
            Connect();
        }

        public void Connect()
        {
            _SocketConnect.BeginConnect(_SrvEndPoint, new AsyncCallback(ConnectAsyncCallBack), _SocketConnect);
        }

        void ConnectAsyncCallBack(IAsyncResult ar)
        {
            _SocketConnect.EndConnect(ar);
        }

        public void SendText(byte[] buf)
        {
            if (_SocketConnect != null)
            {
                TransferObject transObj = new TransferObject();
                transObj.HandlingStock = _SocketConnect;
                transObj.Buffer = buf;

                _SocketConnect.BeginSend(transObj.Buffer, 0, buf.Length, SocketFlags.None,
                    new AsyncCallback(SendAsyncCallBack), transObj);
            }
        }

        void SendAsyncCallBack(IAsyncResult ar)
        {
            _SocketConnect.EndSend(ar);
        }

    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Monograph of the Myxogastres (London) 18 (1892)

#### Original name
Lycoperdon velutinum Berk. & M.A. Curtis, 1892

### Remarks
null


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/html/helpwnd.h
// Purpose:     wxHtmlHelpWindow
// Notes:       Based on htmlhelp.cpp, implementing a monolithic
//              HTML Help controller class,  by Vaclav Slavik
// Author:      Harm van der Heijden and Vaclav Slavik
// RCS-ID:      $Id$
// Copyright:   (c) Harm van der Heijden and Vaclav Slavik
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

#ifndef _WX_HELPWND_H_
#define _WX_HELPWND_H_

#include "wx/defs.h"

#if wxUSE_WXHTML_HELP

#include "wx/helpbase.h"
#include "wx/html/helpdata.h"
#include "wx/window.h"
#include "wx/frame.h"
#include "wx/config.h"
#include "wx/splitter.h"
#include "wx/notebook.h"
#include "wx/listbox.h"
#include "wx/choice.h"
#include "wx/combobox.h"
#include "wx/checkbox.h"
#include "wx/stattext.h"
#include "wx/hash.h"
#include "wx/html/htmlwin.h"
#include "wx/html/htmprint.h"

class WXDLLIMPEXP_FWD_CORE wxButton;
class WXDLLIMPEXP_FWD_CORE wxTextCtrl;
class WXDLLIMPEXP_FWD_CORE wxTreeEvent;
class WXDLLIMPEXP_FWD_CORE wxTreeCtrl;

// style flags for the Help Frame
#define wxHF_TOOLBAR                0x0001
#define wxHF_CONTENTS               0x0002
#define wxHF_INDEX                  0x0004
#define wxHF_SEARCH                 0x0008
#define wxHF_BOOKMARKS              0x0010
#define wxHF_OPEN_FILES             0x0020
#define wxHF_PRINT                  0x0040
#define wxHF_FLAT_TOOLBAR           0x0080
#define wxHF_MERGE_BOOKS            0x0100
#define wxHF_ICONS_BOOK             0x0200
#define wxHF_ICONS_BOOK_CHAPTER     0x0400
#define wxHF_ICONS_FOLDER           0x0000 // this is 0 since it is default
#define wxHF_DEFAULT_STYLE          (wxHF_TOOLBAR | wxHF_CONTENTS | \
                                     wxHF_INDEX | wxHF_SEARCH | \
                                     wxHF_BOOKMARKS | wxHF_PRINT)
//compatibility:
#define wxHF_OPENFILES               wxHF_OPEN_FILES
#define wxHF_FLATTOOLBAR             wxHF_FLAT_TOOLBAR
#define wxHF_DEFAULTSTYLE            wxHF_DEFAULT_STYLE

struct wxHtmlHelpFrameCfg
{
    int x, y, w, h;
    long sashpos;
    bool navig_on;
};

struct wxHtmlHelpMergedIndexItem;
class wxHtmlHelpMergedIndex;

class WXDLLIMPEXP_FWD_CORE wxHelpControllerBase;
class WXDLLIMPEXP_FWD_HTML wxHtmlHelpController;

/*!
 * Help window
 */

class WXDLLIMPEXP_HTML wxHtmlHelpWindow : public wxWindow
{
    DECLARE_DYNAMIC_CLASS(wxHtmlHelpWindow)

public:
    wxHtmlHelpWindow(wxHtmlHelpData* data = NULL) { Init(data); }
    wxHtmlHelpWindow(wxWindow* parent, wxWindowID wxWindowID,
                    const wxPoint& pos = wxDefaultPosition,
                    const wxSize& size = wxDefaultSize,
                    int style = wxTAB_TRAVERSAL|wxNO_BORDER,
                    int helpStyle = wxHF_DEFAULT_STYLE,
                    wxHtmlHelpData* data = NULL);
    bool Create(wxWindow* parent, wxWindowID id,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                int style = wxTAB_TRAVERSAL|wxNO_BORDER,
                int helpStyle = wxHF_DEFAULT_STYLE);
    virtual ~wxHtmlHelpWindow();

    wxHtmlHelpData* GetData() { return m_Data; }
    wxHtmlHelpController* GetController() const { return m_helpController; }
    void SetController(wxHtmlHelpController* controller);

    // Displays page x. If not found it will offect the user a choice of
    // searching books.
    // Looking for the page runs in these steps:
    // 1. try to locate file named x (if x is for example "doc/howto.htm")
    // 2. try to open starting page of book x
    // 3. try to find x in contents (if x is for example "How To ...")
    // 4. try to find x in index (if x is for example "How To ...")
    bool Display(const wxString& x);

    // Alternative version that works with numeric ID.
    // (uses extension to MS format, <param name="ID" value=id>, see docs)
    bool Display(const int id);

    // Displays help window and focuses contents.
    bool DisplayContents();

    // Displays help window and focuses index.
    bool DisplayIndex();

    // Searches for keyword. Returns true and display page if found, return
    // false otherwise
    // Syntax of keyword is Altavista-like:
    // * words are separated by spaces
    //   (but "\"hello world\"" is only one world "hello world")
    // * word may be pretended by + or -
    //   (+ : page must contain the word ; - : page can't contain the word)
    // * if there is no + or - before the word, + is default
    bool KeywordSearch(const wxString& keyword,
                       wxHelpSearchMode mode = wxHELP_SEARCH_ALL);

#if wxUSE_CONFIG
    void UseConfig(wxConfigBase *config, const wxString& rootpath = wxEmptyString)
        {
            m_Config = config;
            m_ConfigRoot = rootpath;
            ReadCustomization(config, rootpath);
        }

    // Saves custom settings into cfg config. it will use the path 'path'
    // if given, otherwise it will save info into currently selected path.
    // saved values : things set by SetFonts, SetBorders.
    void ReadCustomization(wxConfigBase *cfg, const wxString& path = wxEmptyString);
    void WriteCustomization(wxConfigBase *cfg, const wxString& path = wxEmptyString);
#endif // wxUSE_CONFIG

    // call this to let wxHtmlHelpWindow know page changed
    void NotifyPageChanged();

    // Refreshes Contents and Index tabs
    void RefreshLists();

    // Gets the HTML window
    wxHtmlWindow* GetHtmlWindow() const { return m_HtmlWin; }

    // Gets the splitter window
    wxSplitterWindow* GetSplitterWindow() const { return m_Splitter; }

    // Gets the toolbar
    wxToolBar* GetToolBar() const { return m_toolBar; }

    // Gets the configuration data
    wxHtmlHelpFrameCfg& GetCfgData() { return m_Cfg; }

    // Gets the tree control
    wxTreeCtrl *GetTreeCtrl() const { return m_ContentsBox; }

protected:
    void Init(wxHtmlHelpData* data = NULL);

    // Adds items to m_Contents tree control
    void CreateContents();

    // Adds items to m_IndexList
    void CreateIndex();

    // Add books to search choice panel
    void CreateSearch();

    // Updates "merged index" structure that combines indexes of all books
    // into better searchable structure
    void UpdateMergedIndex();

    // Add custom buttons to toolbar
    virtual void AddToolbarButtons(wxToolBar *toolBar, int style);

    // Displays options dialog (fonts etc.)
    virtual void OptionsDialog();

    void OnToolbar(wxCommandEvent& event);
    void OnContentsSel(wxTreeEvent& event);
    void OnIndexSel(wxCommandEvent& event);
    void OnIndexFind(wxCommandEvent& event);
    void OnIndexAll(wxCommandEvent& event);
    void OnSearchSel(wxCommandEvent& event);
    void OnSearch(wxCommandEvent& event);
    void OnBookmarksSel(wxCommandEvent& event);
    void OnSize(wxSizeEvent& event);

    // Images:
    enum {
        IMG_Book = 0,
        IMG_Folder,
        IMG_Page
    };

protected:
    wxHtmlHelpData* m_Data;
    bool m_DataCreated;  // m_Data created by frame, or supplied?
    wxString m_TitleFormat;  // title of the help frame
    // below are various pointers to GUI components
    wxHtmlWindow *m_HtmlWin;
    wxSplitterWindow *m_Splitter;
    wxPanel *m_NavigPan;
    wxNotebook *m_NavigNotebook;
    wxTreeCtrl *m_ContentsBox;
    wxTextCtrl *m_IndexText;
    wxButton *m_IndexButton;
    wxButton *m_IndexButtonAll;
    wxListBox *m_IndexList;
    wxTextCtrl *m_SearchText;
    wxButton *m_SearchButton;
    wxListBox *m_SearchList;
    wxChoice *m_SearchChoice;
    wxStaticText *m_IndexCountInfo;
    wxCheckBox *m_SearchCaseSensitive;
    wxCheckBox *m_SearchWholeWords;
    wxToolBar*  m_toolBar;

    wxComboBox *m_Bookmarks;
    wxArrayString m_BookmarksNames, m_BookmarksPages;

    wxHtmlHelpFrameCfg m_Cfg;

#if wxUSE_CONFIG
    wxConfigBase *m_Config;
    wxString m_ConfigRoot;
#endif // wxUSE_CONFIG

    // pagenumbers of controls in notebook (usually 0,1,2)
    int m_ContentsPage;
    int m_IndexPage;
    int m_SearchPage;

    // lists of available fonts (used in options dialog)
    wxArrayString *m_NormalFonts, *m_FixedFonts;
    int m_FontSize; // 0,1,2 = small,medium,big
    wxString m_NormalFace, m_FixedFace;

    bool m_UpdateContents;

#if wxUSE_PRINTING_ARCHITECTURE
    wxHtmlEasyPrinting *m_Printer;
#endif
    wxHashTable *m_PagesHash;
    wxHtmlHelpController* m_helpController;

    int m_hfStyle;

private:
    void DoIndexFind();
    void DoIndexAll();
    void DisplayIndexItem(const wxHtmlHelpMergedIndexItem *it);
    wxHtmlHelpMergedIndex *m_mergedIndex;

    DECLARE_EVENT_TABLE()
    wxDECLARE_NO_COPY_CLASS(wxHtmlHelpWindow);
};

/*!
 * Command IDs
 */

enum
{
    //wxID_HTML_HELPFRAME = wxID_HIGHEST + 1,
    wxID_HTML_PANEL = wxID_HIGHEST + 2,
    wxID_HTML_BACK,
    wxID_HTML_FORWARD,
    wxID_HTML_UPNODE,
    wxID_HTML_UP,
    wxID_HTML_DOWN,
    wxID_HTML_PRINT,
    wxID_HTML_OPENFILE,
    wxID_HTML_OPTIONS,
    wxID_HTML_BOOKMARKSLIST,
    wxID_HTML_BOOKMARKSADD,
    wxID_HTML_BOOKMARKSREMOVE,
    wxID_HTML_TREECTRL,
    wxID_HTML_INDEXPAGE,
    wxID_HTML_INDEXLIST,
    wxID_HTML_INDEXTEXT,
    wxID_HTML_INDEXBUTTON,
    wxID_HTML_INDEXBUTTONALL,
    wxID_HTML_NOTEBOOK,
    wxID_HTML_SEARCHPAGE,
    wxID_HTML_SEARCHTEXT,
    wxID_HTML_SEARCHLIST,
    wxID_HTML_SEARCHBUTTON,
    wxID_HTML_SEARCHCHOICE,
    wxID_HTML_COUNTINFO
};

#endif // wxUSE_WXHTML_HELP

#endif


text:
package com.amazonaws.services.synthetics.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * How long, in seconds, for the canary to continue making regular runs according to the schedule in the
 * Expression value.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CanaryScheduleOutput implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * A rate expression or a cron expression that defines how often the canary is to run.
     *

     *

     * For a rate expression, The syntax is rate(number unit). unit can be
     * minute, minutes, or hour.
     *

     *

     * For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs it
     * once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a frequency between
     * rate(1 minute) and rate(1 hour).
     *

     *

     * Specifying rate(0 minute) or rate(0 hour) is a special value that causes the canary to
     * run only once when it is started.
     *

     *

     * Use cron(expression) to specify a cron expression. For information about the syntax for cron
     * expressions, see
     * Scheduling canary runs using cron.
     *

     */
    private String expression;
    /**
     *

     * How long, in seconds, for the canary to continue making regular runs after it was created. The runs are performed
     * according to the schedule in the Expression value.
     *

     */
    private Long durationInSeconds;

    /**
     *

     * A rate expression or a cron expression that defines how often the canary is to run.
     *

     *

     * For a rate expression, The syntax is rate(number unit). unit can be
     * minute, minutes, or hour.
     *

     *

     * For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs it
     * once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a frequency between
     * rate(1 minute) and rate(1 hour).
     *

     *

     * Specifying rate(0 minute) or rate(0 hour) is a special value that causes the canary to
     * run only once when it is started.
     *

     *

     * Use cron(expression) to specify a cron expression. For information about the syntax for cron
     * expressions, see
     * Scheduling canary runs using cron.
     *

     *
     * @param expression
     *        A rate expression or a cron expression that defines how often the canary is to
     *        run.

     *

     *        For a rate expression, The syntax is rate(number unit). unit can be
     *        minute, minutes, or hour.
     *

     *

     *        For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs
     *        it once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a
     *        frequency between rate(1 minute) and rate(1 hour).
     *

     *

     *        Specifying rate(0 minute) or rate(0 hour) is a special value that causes the
     *        canary to run only once when it is started.
     *

     *

     *        Use cron(expression) to specify a cron expression. For information about the syntax
     *        for cron expressions, see
     *        Scheduling canary runs using cron.
     */

    public void setExpression(String expression) {
        this.expression = expression;
    }

    /**
     *

     * A rate expression or a cron expression that defines how often the canary is to run.
     *

     *

     * For a rate expression, The syntax is rate(number unit). unit can be
     * minute, minutes, or hour.
     *

     *

     * For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs it
     * once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a frequency between
     * rate(1 minute) and rate(1 hour).
     *

     *

     * Specifying rate(0 minute) or rate(0 hour) is a special value that causes the canary to
     * run only once when it is started.
     *

     *

     * Use cron(expression) to specify a cron expression. For information about the syntax for cron
     * expressions, see
     * Scheduling canary runs using cron.
     *

     *
     * @return A rate expression or a cron expression that defines how often the canary is to
     *         run.

     *

     *         For a rate expression, The syntax is rate(number unit). unit can be
     *         minute, minutes, or hour.
     *

     *

     *         For example, rate(1 minute) runs the canary once a minute, rate(10 minutes)
     *         runs it once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a
     *         frequency between rate(1 minute) and rate(1 hour).
     *

     *

     *         Specifying rate(0 minute) or rate(0 hour) is a special value that causes the
     *         canary to run only once when it is started.
     *

     *

     *         Use cron(expression) to specify a cron expression. For information about the syntax
     *         for cron expressions, see  Scheduling canary runs using cron.
     */

    public String getExpression() {
        return this.expression;
    }

    /**
     *

     * A rate expression or a cron expression that defines how often the canary is to run.
     *

     *

     * For a rate expression, The syntax is rate(number unit). unit can be
     * minute, minutes, or hour.
     *

     *

     * For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs it
     * once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a frequency between
     * rate(1 minute) and rate(1 hour).
     *

     *

     * Specifying rate(0 minute) or rate(0 hour) is a special value that causes the canary to
     * run only once when it is started.
     *

     *

     * Use cron(expression) to specify a cron expression. For information about the syntax for cron
     * expressions, see
     * Scheduling canary runs using cron.
     *

     *
     * @param expression
     *        A rate expression or a cron expression that defines how often the canary is to
     *        run.

     *

     *        For a rate expression, The syntax is rate(number unit). unit can be
     *        minute, minutes, or hour.
     *

     *

     *        For example, rate(1 minute) runs the canary once a minute, rate(10 minutes) runs
     *        it once every 10 minutes, and rate(1 hour) runs it once every hour. You can specify a
     *        frequency between rate(1 minute) and rate(1 hour).
     *

     *

     *        Specifying rate(0 minute) or rate(0 hour) is a special value that causes the
     *        canary to run only once when it is started.
     *

     *

     *        Use cron(expression) to specify a cron expression. For information about the syntax
     *        for cron expressions, see
     *        Scheduling canary runs using cron.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CanaryScheduleOutput withExpression(String expression) {
        setExpression(expression);
        return this;
    }

    /**
     *

     * How long, in seconds, for the canary to continue making regular runs after it was created. The runs are performed
     * according to the schedule in the Expression value.
     *

     *
     * @param durationInSeconds
     *        How long, in seconds, for the canary to continue making regular runs after it was created. The runs are
     *        performed according to the schedule in the Expression value.
     */

    public void setDurationInSeconds(Long durationInSeconds) {
        this.durationInSeconds = durationInSeconds;
    }

    /**
     *

     * How long, in seconds, for the canary to continue making regular runs after it was created. The runs are performed
     * according to the schedule in the Expression value.
     *

     *
     * @return How long, in seconds, for the canary to continue making regular runs after it was created. The runs are
     *         performed according to the schedule in the Expression value.
     */

    public Long getDurationInSeconds() {
        return this.durationInSeconds;
    }

    /**
     *

     * How long, in seconds, for the canary to continue making regular runs after it was created. The runs are performed
     * according to the schedule in the Expression value.
     *

     *
     * @param durationInSeconds
     *        How long, in seconds, for the canary to continue making regular runs after it was created. The runs are
     *        performed according to the schedule in the Expression value.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CanaryScheduleOutput withDurationInSeconds(Long durationInSeconds) {
        setDurationInSeconds(durationInSeconds);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getExpression() != null)
            sb.append("Expression: ").append(getExpression()).append(",");
        if (getDurationInSeconds() != null)
            sb.append("DurationInSeconds: ").append(getDurationInSeconds());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CanaryScheduleOutput == false)
            return false;
        CanaryScheduleOutput other = (CanaryScheduleOutput) obj;
        if (other.getExpression() == null ^ this.getExpression() == null)
            return false;
        if (other.getExpression() != null && other.getExpression().equals(this.getExpression()) == false)
            return false;
        if (other.getDurationInSeconds() == null ^ this.getDurationInSeconds() == null)
            return false;
        if (other.getDurationInSeconds() != null && other.getDurationInSeconds().equals(this.getDurationInSeconds()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getExpression() == null) ? 0 : getExpression().hashCode());
        hashCode = prime * hashCode + ((getDurationInSeconds() == null) ? 0 : getDurationInSeconds().hashCode());
        return hashCode;
    }

    @Override
    public CanaryScheduleOutput clone() {
        try {
            return (CanaryScheduleOutput) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.synthetics.model.transform.CanaryScheduleOutputMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
ambari-presto-service
=====================

`Issues <https://github.com/prestodb/ambari-presto-service/issues>`_ |
`Github <https://github.com/prestodb/ambari-presto-service>`_

Introduction
------------

This project contains the code and configuration needed to integrate
`Presto <https://prestodb.io/>`_ with `Ambari <https://ambari.apache.org/>`_.
Adding the Presto service to Ambari allows:

1. Installing and deploying Presto on a cluster from the Ambari UI.
2. Changing Presto configuration options via the Ambari UI.

Content
-------

.. toctree::
   :maxdepth: 3

   getting-started
   known-issues
   getting-help
   developers


text:
.. _hasura_logout:

Hasura CLI: hasura logout
-------------------------

Logout from `Hasura dashboard <https://hasura.io>`_.

Synopsis
~~~~~~~~

Logout from hasura.io and clear the current session

::

  hasura logout [flags]

Examples
~~~~~~~~

::

    # Logout and clear session for current user:
    $ hasura logout

Options
~~~~~~~

::

  -h, --help   help for logout

Options inherited from parent commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

      --project string   hasura project directory where the commands should be executed. (default: current directory)

SEE ALSO
~~~~~~~~

* :ref:`hasura <hasura>` 	 - hasura controls the hasura project

*Auto generated by spf13/cobra*


text:
package de.codesourcery.springmass.springmass;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

import de.codesourcery.springmass.math.Vector4;

public class Mass {

	public final Vector4 currentPosition=new Vector4();
	public Vector4 previousPosition=new Vector4();

	public final double mass;
	public final Color color;

	public final List<Spring> springs = new ArrayList<>();

	private byte flags;

	public static final byte FLAG_FIXED = 1<<0;
	public static final byte FLAG_SELECTED = 1<<1;

	@Override
	public String toString() {
		return "Mass( "+currentPosition+" )";
	}

	public void setPosition(Vector4 p) {
	    this.currentPosition.set(p);
	    this.previousPosition.set(p);
	}

	public double distanceTo(Mass other) {
		return currentPosition.distanceTo( other.currentPosition );
	}

	public Mass createCopyWithoutSprings()
	{
	    Mass result = new Mass(color,currentPosition,mass);
	    result.flags = flags;
	    result.previousPosition = new Vector4(previousPosition);
	    return result;
	}

	public void setFixed(boolean yesNo)
	{
	    if ( yesNo ) {
	        this.flags |= FLAG_FIXED;
	    } else {
	        this.flags &= ~FLAG_FIXED;
	    }
	}

	public void addSpring(Spring s)
	{
		s.m1.springs.add( s );
		s.m2.springs.add( s );
	}

	public boolean isFixed() {
		return (flags & FLAG_FIXED) != 0;
	}

	public void setSelected(boolean yesNo) {
        if ( yesNo ) {
            this.flags |= FLAG_SELECTED;
        } else {
            this.flags &= ~FLAG_SELECTED;
        }
	}

	public boolean isSelected() {
        return (flags & FLAG_SELECTED) != 0;
	}

	public boolean hasFlags(int bitMask) {
	    return (flags & bitMask) != 0;
	}

	public Mass(Color color,Vector4 position,double mass) {
		if (position == null) {
			throw new IllegalArgumentException("position must not be null");
		}
		this.color = color;
		this.mass = mass;
		setPosition(position);
	}

	public double squaredDistanceTo(Vector4 other) {
		return currentPosition.squaredDistanceTo( other );
	}

    public void copyPositionAndFlagsFrom(Mass mass2)
    {
        this.currentPosition.set( mass2.currentPosition );
        this.previousPosition.set( mass2.previousPosition );
        this.flags = mass2.flags;
    }
}


text:
@implementation Book (Addition)
+(NSArray *)arrayForResponseMapping
{
    return @[@"title",@"author", @"copyright", @"objectId",@"createdAt",@"updatedAt",@"sessionToken"];
}

+(NSDictionary *)dictionaryForResponseMapping
{
    return @{@"title":@"title",@"author":@"author", @"copyright":@"copyright",@"sessionToken":@"sessionToken",@"user":@"user.objectId"};

}
@end


text:
using SampleModels;
using System;
using System.Threading.Tasks;
using UniRx;

namespace SampleConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            MainAsync().Wait();
        }

        static async Task MainAsync()
        {
            var c = new Class1();

            var s = new Subject<string>();

            s.Subscribe(
                x => Console.WriteLine(x.Substring(0, 100)),
                ex => Console.WriteLine(ex.Message)
                );

            await c.RunAsync(s);
        }
    }
}


text:
.class public Lcom/tencent/mm/sdk/openapi/WXAPIFactory;
.super Ljava/lang/Object;

# static fields
.field private static final a:Ljava/lang/String; = "MicroMsg.PaySdk.WXFactory"

# direct methods
.method private constructor <init>()V
    .locals 3

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    new-instance v0, Ljava/lang/RuntimeException;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/Class;->getSimpleName()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, " should not be instantiated"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method public static createMsgListenerAPI(Landroid/content/Context;Ljava/lang/String;Z)Lcom/tencent/mm/sdk/openapi/IWXMsgListenAPI;
    .locals 3

    const-string v0, "MicroMsg.PaySdk.WXFactory"

    new-instance v1, Ljava/lang/StringBuilder;

    const-string v2, "createMsgListenerAPI, appId = "

    invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, ", checkSignature = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Lcom/tencent/mm/sdk/b/a;->c(Ljava/lang/String;Ljava/lang/String;)V

    new-instance v0, Lcom/tencent/mm/sdk/openapi/WXMsgListenerApiImplV10;

    invoke-direct {v0, p0, p1, p2}, Lcom/tencent/mm/sdk/openapi/WXMsgListenerApiImplV10;-><init>(Landroid/content/Context;Ljava/lang/String;Z)V

    return-object v0
.end method

.method public static createWXAPI(Landroid/content/Context;Ljava/lang/String;)Lcom/tencent/mm/sdk/openapi/IWXAPI;
    .locals 1

    const/4 v0, 0x0

    invoke-static {p0, p1, v0}, Lcom/tencent/mm/sdk/openapi/WXAPIFactory;->createWXAPI(Landroid/content/Context;Ljava/lang/String;Z)Lcom/tencent/mm/sdk/openapi/IWXAPI;

    move-result-object v0

    return-object v0
.end method

.method public static createWXAPI(Landroid/content/Context;Ljava/lang/String;Z)Lcom/tencent/mm/sdk/openapi/IWXAPI;
    .locals 3

    const-string v0, "MicroMsg.PaySdk.WXFactory"

    new-instance v1, Ljava/lang/StringBuilder;

    const-string v2, "createWXAPI, appId = "

    invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, ", checkSignature = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Lcom/tencent/mm/sdk/b/a;->c(Ljava/lang/String;Ljava/lang/String;)V

    new-instance v0, Lcom/tencent/mm/sdk/openapi/d;

    invoke-direct {v0, p0, p1, p2}, Lcom/tencent/mm/sdk/openapi/d;-><init>(Landroid/content/Context;Ljava/lang/String;Z)V

    return-object v0
.end method


text:
package com.intellij.ui;

import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.util.List;

/**
 * @author Konstantin Bulenkov
 */
public abstract class ColorChooserService {
  public static ColorChooserService getInstance() {
    return ServiceManager.getService(ColorChooserService.class);
  }

  /**
   * @deprecated this overload does not work with headless implementation, use one with the Project instead
   */
  @Deprecated
  @Nullable
  public abstract Color showDialog(Component parent, @Nls(capitalization = Nls.Capitalization.Title) String caption, Color preselectedColor, boolean enableOpacity,
                                   List<? extends ColorPickerListener> listeners, boolean opacityInPercent);
  @Nullable
  public abstract Color showDialog(Project project, Component parent, @Nls(capitalization = Nls.Capitalization.Title) String caption, Color preselectedColor, boolean enableOpacity,
                                   List<? extends ColorPickerListener> listeners, boolean opacityInPercent);
}