text:
<?php

class GEN extends ProposalType {

    // Pages that this proposal type provides
    var $pages = array(
                   'image',
                   'dc',
                   'vstat',
                   );

    var $default = 'proposal';

    // base directory for all files
    var $dir = 'gen';

    // table and column to add data collection count to visit page
    var $visit_table = 'datacollection';
    var $session_column = 'datacollectionid';

    // Proposal menu
    var $prop_menu = array(
                       array('/proposal/visits','Visits'),
                  );

    // Extra menu items
    var $ext_menu =  array(
                        );

    // Extra admin items
    var $ext_admin = array(
                        );

    // Authentication method for this type of proposal
    function auth($require_staff, $parent) {
        $u = class_exists('phpCAS') ? phpCAS::getUser() : '';

        $groups = explode(' ', exec('groups ' . $u));
        $this->staff = in_array('mx_staff', $groups) ? True : False;
        if (!$this->staff && in_array('dls_dasc', $groups)) $this->staff = True;
        if (!$this->staff && in_array('b21_staff', $groups)) $this->staff = True;
        if (!$this->staff && in_array('i11_staff', $groups)) $this->staff = True;

        // Staff only pages
        if ($require_staff) {
            $auth = $this->staff;

        // Normal validation
        } else {
            $auth = False;

            // Registered visit or staff
            if ($this->staff) {
                $auth = True;

                if ($this->has_arg('prop')) {
                    $prop = $this->db->pq('SELECT p.proposalid FROM ispyb4a_db.proposal p WHERE p.proposalcode || p.proposalnumber LIKE :1', array($this->arg('prop')));

                    if (sizeof($prop)) $this->proposalid = $prop[0]['PROPOSALID'];
                }

            // Normal users
            } else {
                $rows = $this->db->pq("SELECT lower(i.visit_id) as vis from investigation@DICAT_RO i inner join investigationuser@DICAT_RO iu on i.id = iu.investigation_id inner join user_@DICAT_RO u on u.id = iu.user_id where u.name=:1", array($u));

                foreach ($rows as $row) {
                    array_push($this->visits, strtolower($row['VIS']));
                }

                if ($this->has_arg('id') || $this->has_arg('visit') || $this->has_arg('prop')) {

                    // Check user is in this visit
                    if ($this->has_arg('id')) {
                        $vis = $this->db->pq('SELECT p.proposalcode || p.proposalnumber || \'-\' || s.visit_number as vis FROM ispyb4a_db.blsession s INNER JOIN ispyb4a_db.proposal p ON (p.proposalid = s.proposalid) INNER JOIN ispyb4a_db.datacollection dc ON s.sessionid = dc.sessionid WHERE dc.emmovieid = :1', array($this->arg('id')));

                        $vis = sizeof($vis) ? $vis[0]['VIS'] : '';

                    } else if ($this->has_arg('visit')) {
                        $vis = $this->arg('visit');

                        $visp = $this->db->pq("SELECT p.proposalid FROM ispyb4a_db.blsession s INNER JOIN ispyb4a_db.proposal p ON (p.proposalid = s.proposalid) WHERE p.proposalcode || p.proposalnumber || '-' || s.visit_number LIKE :1", array($this->arg('visit')));

                        if (sizeof($visp)) $this->proposalid = $visp[0]['PROPOSALID'];

                    // Check user is in this proposal
                    } else if ($this->has_arg('prop')) {
                        $viss = $this->db->pq('SELECT p.proposalid, p.proposalcode || p.proposalnumber || \'-\' || s.visit_number as vis FROM ispyb4a_db.blsession s INNER JOIN ispyb4a_db.proposal p ON (p.proposalid = s.proposalid) WHERE p.proposalcode || p.proposalnumber LIKE :1', array($this->arg('prop')));

                        $vis = array();
                        foreach ($viss as $v) array_push($vis, $v['VIS']);
                        $this->proposalid = $viss[0]['PROPOSALID'];
                    }

                    if ($this->has_arg('id') || $this->has_arg('visit')) {
                        if (in_array($vis, $this->visits)) $auth = True;
                    } else {
                        if (sizeof(array_intersect($vis, $this->visits))) $auth = True;
                    }

                // No id or visit, anyone ok to view
                } else {
                    $auth = True;
                }
            }
        }

        // End execution, show not authed page template
        if (!$auth) {
            $this->msg('Access Denied', 'You dont have access to that page');
        }

        return $auth;
    }

}

?>


text:
This is a collection of the work performed investigating the PE32 Rich Header.

## Standalone
To execute the standalone version please execute the following:

```
python3 standalone.py <filename>
```

## Web Version
The web version can be run as a local tornado server or through the included dockerfile.

#### Output
```json
{
    "compids": [
        {
            "mcv": "<str>",
            "pid": "<str>",
            "cnt": "<str>",
        }
    ],
    "compids_dup": "<boolean>",
    "csum_calc": "<int>",
    "csum_file": "<int>",
    "csum_valid": "<boolean>",
    "error": "<int>",
    "offset": "<int>",
}
```

#### Docker Usage
Build and start the docker container using the following commands

```
docker build -t richheader .
sudo docker run --name rich_header -v /tmp:/tmp:ro -p 8080:8080 richheader
```

Place the files you wish to extract the Rich Header from in /tmp and access using
`http://127.0.0.1:8080/analyze/?obj=<file_name>`

To read about the service please see
`http://127.0.0.1:8080/`

## Acknowledgement
This work was created with the blood sweat and tears of mamy people.
Thank you
* Zachary Hanif
* Julian Kirsch
* Bojan Kolosnjaji
* Christian von Pentz
* Marcel Schumacher
* George Webster
* Huang Xiao

redpajama_set_name: RedPajamaGithub


text:
package revocations

import (
	"github.com/leanovate/microzon-auth-go/common"
	"github.com/leanovate/microzon-auth-go/logging"
	"github.com/leanovate/microzon-auth-go/store"
	"time"
)

// Cache/manage revocations
// Benchmark
// BenchmarkRevocationsManagerFill-8	 1000000	      1653 ns/op	     234 B/op	       7 allocs/op
type RevocationsManager struct {
	*RevocationsValidator
	revocationsByVersion *versionWheel
	serverStore          store.ServerStore
}

// Create a new revocations cache
// Usually there should only be one
func NewRevocationsManager(store store.ServerStore, parent logging.Logger) (*RevocationsManager, error) {
	revocations := &RevocationsManager{
		RevocationsValidator: NewRevocationsValidator(store, parent),
		revocationsByVersion: newVersionWheel(17),
		serverStore:          store,
	}
	go revocations.StartCleanup()

	if err := store.SetRevocationsListener(revocations.onNewRevocation); err != nil {
		return nil, err
	}

	return revocations, nil
}

// Add a revocation
func (r *RevocationsManager) AddRevocation(sha256 common.RawSha256, expiresAt time.Time) error {
	return r.serverStore.AddRevocation(sha256, expiresAt)
}

// Get all revocations since a given version
func (r *RevocationsManager) GetRevocationsSinceVersion(version uint64, maxLength int) *RevocationListVO {
	r.lock.RLock()
	defer r.lock.RUnlock()

	maxVersion := r.revocationsByVersion.lastVersion

	result := make([]*RevocationVO, 0, maxLength)
	revocation := r.revocationsByVersion.next(version)
	for revocation != nil {
		result = append(result, revocation)
		if len(result) >= maxLength {
			return NewRevocationListVO(revocation.Version, result)
		}
		revocation = r.revocationsByVersion.next(revocation.Version)
	}

	return NewRevocationListVO(maxVersion, result)
}

func (r *RevocationsManager) CurrentVersion() uint64 {
	r.lock.RLock()
	r.lock.RUnlock()

	return r.revocationsByVersion.lastVersion
}

// Cleanup expired revocations
func (r *RevocationsManager) cleanup() {
	r.logger.Debug("Do cleanup")
	expiredRevocations := r.expirationTimeWheel.getExpiredRevocations(time.Now())

	if len(expiredRevocations) == 0 {
		r.logger.Debug("Nothing to cleanup")
		return
	}
	r.lock.Lock()
	defer r.lock.Unlock()

	r.logger.Debugf("Cleaning up %d revocations", len(expiredRevocations))
	for _, revocation := range expiredRevocations {
		r.revocationHashes.removeHash(revocation.Sha256)
		r.revocationsByVersion.removeVersion(revocation.Version)
	}
}

func (r *RevocationsManager) StartCleanup() {
	r.logger.Debug("Start cleanup loop")
	for {
		diff := time.Now().Unix() - r.expirationTimeWheel.lastCleanup
		if diff <= 0 {
			time.Sleep(1 * time.Second)
		}
		r.cleanup()
	}
}

func (r *RevocationsManager) onNewRevocation(version uint64, sha256 common.RawSha256, expiresAt time.Time) {
	revocation := NewRevokationVO(version, sha256, expiresAt)

	r.lock.Lock()
	triggerNotify := false
	if version > r.revocationsByVersion.lastVersion {
		triggerNotify = true
	}
	r.revocationHashes.addRevocation(revocation)
	r.revocationsByVersion.addRevocation(revocation)
	r.lock.Unlock()
	r.expirationTimeWheel.AddEntry(revocation)
	if triggerNotify {
		r.Observe.Notify(ObserveState(version))
	}
}


text:
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/dns/serial_worker.h"

#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/callback.h"
#include "base/check.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "net/base/backoff_entry.h"
#include "net/test/test_with_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {
constexpr base::TimeDelta kBackoffInitialDelay = base::Milliseconds(100);
constexpr int kBackoffMultiplyFactor = 2;
constexpr int kMaxRetries = 3;

static const BackoffEntry::Policy kTestBackoffPolicy = {
    0,  // Number of initial errors to ignore without backoff.
    static_cast<int>(
        kBackoffInitialDelay
            .InMilliseconds()),  // Initial delay for backoff in ms.
    kBackoffMultiplyFactor,      // Factor to multiply for exponential backoff.
    0,                           // Fuzzing percentage.
    static_cast<int>(
        base::Seconds(1).InMilliseconds()),  // Maximum time to delay requests
                                             // in ms: 1 second.
    -1,                                      // Don't discard entry.
    false  // Don't use initial delay unless the last was an error.
};

class SerialWorkerTest : public TestWithTaskEnvironment {
 public:
  // The class under test
  class TestSerialWorker : public SerialWorker {
   public:
    class TestWorkItem : public SerialWorker::WorkItem {
     public:
      explicit TestWorkItem(SerialWorkerTest* test) : test_(test) {}

      void DoWork() override {
        ASSERT_TRUE(test_);
        test_->OnWork();
      }

      void FollowupWork(base::OnceClosure closure) override {
        ASSERT_TRUE(test_);
        test_->OnFollowup(std::move(closure));
      }

     private:
      raw_ptr<SerialWorkerTest> test_;
    };

    explicit TestSerialWorker(SerialWorkerTest* t)
        : SerialWorker(/*max_number_of_retries=*/kMaxRetries,
                       &kTestBackoffPolicy),
          test_(t) {}
    ~TestSerialWorker() override = default;

    std::unique_ptr<SerialWorker::WorkItem> CreateWorkItem() override {
      return std::make_unique<TestWorkItem>(test_);
    }

    bool OnWorkFinished(
        std::unique_ptr<SerialWorker::WorkItem> work_item) override {
      CHECK(test_);
      return test_->OnWorkFinished();
    }

   private:
    raw_ptr<SerialWorkerTest> test_;
  };

  SerialWorkerTest(const SerialWorkerTest&) = delete;
  SerialWorkerTest& operator=(const SerialWorkerTest&) = delete;

  // Mocks

  void OnWork() {
    { // Check that OnWork is executed serially.
      base::AutoLock lock(work_lock_);
      EXPECT_FALSE(work_running_) << "`DoWork()` is not called serially!";
      work_running_ = true;
    }
    num_work_calls_observed_++;
    BreakNow("OnWork");
    {
      base::ScopedAllowBaseSyncPrimitivesForTesting
          scoped_allow_base_sync_primitives;
      work_allowed_.Wait();
    }
    // Calling from ThreadPool, but protected by work_allowed_/work_called_.
    output_value_ = input_value_;

    { // This lock might be destroyed after work_called_ is signalled.
      base::AutoLock lock(work_lock_);
      work_running_ = false;
    }
    work_called_.Signal();
  }

  void OnFollowup(base::OnceClosure closure) {
    EXPECT_TRUE(task_runner_->BelongsToCurrentThread());

    followup_closure_ = std::move(closure);
    BreakNow("OnFollowup");

    if (followup_immediately_)
      CompleteFollowup();
  }

  bool OnWorkFinished() {
    EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
    EXPECT_EQ(output_value_, input_value_);
    ++work_finished_calls_;
    BreakNow("OnWorkFinished");
    return on_work_finished_should_report_success_;
  }

 protected:
  void BreakCallback(const std::string& breakpoint) {
    breakpoint_ = breakpoint;
    run_loop_->Quit();
  }

  void BreakNow(const std::string& b) {
    task_runner_->PostTask(FROM_HERE,
                           base::BindOnce(&SerialWorkerTest::BreakCallback,
                                          base::Unretained(this), b));
  }

  void RunUntilBreak(const std::string& b) {
    base::RunLoop run_loop;
    ASSERT_FALSE(run_loop_);
    run_loop_ = &run_loop;
    run_loop_->Run();
    run_loop_ = nullptr;
    ASSERT_EQ(breakpoint_, b);
  }

  void CompleteFollowup() {
    ASSERT_TRUE(followup_closure_);
    task_runner_->PostTask(FROM_HERE, std::move(followup_closure_));
  }

  SerialWorkerTest()
      : TestWithTaskEnvironment(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        work_allowed_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
                      base::WaitableEvent::InitialState::NOT_SIGNALED),
        work_called_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
                     base::WaitableEvent::InitialState::NOT_SIGNALED),
        work_running_(false) {}

  // Helpers for tests.

  // Lets OnWork run and waits for it to complete. Can only return if OnWork is
  // executed on a concurrent thread. Before calling, OnWork() must already have
  // been started and blocked (ensured by running `RunUntilBreak("OnWork")`).
  void UnblockWork() {
    ASSERT_TRUE(work_running_);
    work_allowed_.Signal();
    work_called_.Wait();
  }

  // test::Test methods
  void SetUp() override {
    task_runner_ = base::ThreadTaskRunnerHandle::Get();
  }

  void TearDown() override {
    // Cancel the worker to catch if it makes a late DoWork call.
    if (worker_)
      worker_->Cancel();
    // Check if OnWork is stalled.
    EXPECT_FALSE(work_running_) << "OnWork should be done by TearDown";
    // Release it for cleanliness.
    if (work_running_) {
      UnblockWork();
    }
  }

  // Input value read on WorkerPool.
  int input_value_ = 0;
  // Output value written on WorkerPool.
  int output_value_ = -1;
  // The number of times we saw an OnWork call.
  int num_work_calls_observed_ = 0;
  bool on_work_finished_should_report_success_ = true;

  // read is called on WorkerPool so we need to synchronize with it.
  base::WaitableEvent work_allowed_;
  base::WaitableEvent work_called_;

  // Protected by read_lock_. Used to verify that read calls are serialized.
  bool work_running_;
  base::Lock work_lock_;

  int work_finished_calls_ = 0;

  // Task runner for this thread.
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;

  // WatcherDelegate under test.
  std::unique_ptr<TestSerialWorker> worker_ =
      std::make_unique<TestSerialWorker>(this);

  std::string breakpoint_;
  raw_ptr<base::RunLoop> run_loop_ = nullptr;

  bool followup_immediately_ = true;
  base::OnceClosure followup_closure_;
};

TEST_F(SerialWorkerTest, RunWorkMultipleTimes) {
  for (int i = 0; i < 3; ++i) {
    ++input_value_;
    worker_->WorkNow();
    RunUntilBreak("OnWork");
    EXPECT_EQ(work_finished_calls_, i);
    UnblockWork();
    RunUntilBreak("OnFollowup");
    RunUntilBreak("OnWorkFinished");
    EXPECT_EQ(work_finished_calls_, i + 1);

    EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
  }
}

TEST_F(SerialWorkerTest, TriggerTwoTimesBeforeRun) {
  // Schedule two calls. OnWork checks if it is called serially.
  ++input_value_;
  worker_->WorkNow();
  // Work is blocked, so this will have to induce re-work
  worker_->WorkNow();

  // Expect 2 cycles through work.
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  EXPECT_EQ(work_finished_calls_, 1);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, TriggerThreeTimesBeforeRun) {
  // Schedule two calls. OnWork checks if it is called serially.
  ++input_value_;
  worker_->WorkNow();
  // Work is blocked, so this will have to induce re-work
  worker_->WorkNow();
  // Repeat work is already scheduled, so this should be a noop.
  worker_->WorkNow();

  // Expect 2 cycles through work.
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  EXPECT_EQ(work_finished_calls_, 1);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, DelayFollowupCompletion) {
  followup_immediately_ = false;
  worker_->WorkNow();

  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());

  CompleteFollowup();
  RunUntilBreak("OnWorkFinished");

  EXPECT_EQ(work_finished_calls_, 1);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, RetriggerDuringRun) {
  // Trigger work and wait until blocked.
  worker_->WorkNow();
  RunUntilBreak("OnWork");

  worker_->WorkNow();
  worker_->WorkNow();

  // Expect a second work cycle after completion of current.
  UnblockWork();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  EXPECT_EQ(work_finished_calls_, 1);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, RetriggerDuringFollowup) {
  // Trigger work and wait until blocked on followup.
  followup_immediately_ = false;
  worker_->WorkNow();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");

  worker_->WorkNow();
  worker_->WorkNow();

  // Expect a second work cycle after completion of followup.
  CompleteFollowup();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  CompleteFollowup();
  RunUntilBreak("OnWorkFinished");

  EXPECT_EQ(work_finished_calls_, 1);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, CancelDuringWork) {
  worker_->WorkNow();

  RunUntilBreak("OnWork");

  worker_->Cancel();
  UnblockWork();

  RunUntilIdle();
  EXPECT_EQ(breakpoint_, "OnWork");

  EXPECT_EQ(work_finished_calls_, 0);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, CancelDuringFollowup) {
  followup_immediately_ = false;
  worker_->WorkNow();

  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");

  worker_->Cancel();
  CompleteFollowup();

  RunUntilIdle();
  EXPECT_EQ(breakpoint_, "OnFollowup");

  EXPECT_EQ(work_finished_calls_, 0);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, DeleteDuringWork) {
  worker_->WorkNow();

  RunUntilBreak("OnWork");

  worker_.reset();
  UnblockWork();

  RunUntilIdle();
  EXPECT_EQ(breakpoint_, "OnWork");

  EXPECT_EQ(work_finished_calls_, 0);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, DeleteDuringFollowup) {
  followup_immediately_ = false;
  worker_->WorkNow();

  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");

  worker_.reset();
  CompleteFollowup();

  RunUntilIdle();
  EXPECT_EQ(breakpoint_, "OnFollowup");

  EXPECT_EQ(work_finished_calls_, 0);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, RetryAndThenSucceed) {
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());

  // Induce a failure.
  on_work_finished_should_report_success_ = false;
  ++input_value_;
  worker_->WorkNow();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  // Confirm it failed and that a retry was scheduled.
  ASSERT_EQ(1, worker_->GetBackoffEntryForTesting().failure_count());
  EXPECT_EQ(kBackoffInitialDelay,
            worker_->GetBackoffEntryForTesting().GetTimeUntilRelease());

  // Make the subsequent attempt succeed.
  on_work_finished_should_report_success_ = true;

  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());

  EXPECT_EQ(2, num_work_calls_observed_);

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, ExternalWorkRequestResetsRetryState) {
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());

  // Induce a failure.
  on_work_finished_should_report_success_ = false;
  ++input_value_;
  worker_->WorkNow();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  // Confirm it failed and that a retry was scheduled.
  ASSERT_EQ(1, worker_->GetBackoffEntryForTesting().failure_count());
  EXPECT_TRUE(worker_->GetRetryTimerForTesting().IsRunning());
  EXPECT_EQ(kBackoffInitialDelay,
            worker_->GetBackoffEntryForTesting().GetTimeUntilRelease());
  on_work_finished_should_report_success_ = true;

  // The retry state should be reset before we see OnWorkFinished.
  worker_->WorkNow();
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());
  EXPECT_FALSE(worker_->GetRetryTimerForTesting().IsRunning());
  EXPECT_EQ(base::TimeDelta(),
            worker_->GetBackoffEntryForTesting().GetTimeUntilRelease());
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

TEST_F(SerialWorkerTest, MultipleFailureExponentialBackoff) {
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());

  // Induce a failure.
  on_work_finished_should_report_success_ = false;
  ++input_value_;
  worker_->WorkNow();
  RunUntilBreak("OnWork");
  UnblockWork();
  RunUntilBreak("OnFollowup");
  RunUntilBreak("OnWorkFinished");

  for (int retry_attempt_count = 1; retry_attempt_count <= kMaxRetries;
       retry_attempt_count++) {
    // Confirm it failed and that a retry was scheduled.
    ASSERT_EQ(retry_attempt_count,
              worker_->GetBackoffEntryForTesting().failure_count());
    EXPECT_TRUE(worker_->GetRetryTimerForTesting().IsRunning());
    base::TimeDelta expected_backoff_delay;
    if (retry_attempt_count == 1) {
      expected_backoff_delay = kBackoffInitialDelay;
    } else {
      expected_backoff_delay = kBackoffInitialDelay * kBackoffMultiplyFactor *
                               (retry_attempt_count - 1);
    }
    EXPECT_EQ(expected_backoff_delay,
              worker_->GetBackoffEntryForTesting().GetTimeUntilRelease())
        << "retry_attempt_count=" << retry_attempt_count;

    // |on_work_finished_should_report_success_| is still false, so the retry
    // will fail too
    RunUntilBreak("OnWork");
    UnblockWork();
    RunUntilBreak("OnFollowup");
    RunUntilBreak("OnWorkFinished");
  }

  // The last retry attempt resets the retry state.
  ASSERT_EQ(0, worker_->GetBackoffEntryForTesting().failure_count());
  EXPECT_FALSE(worker_->GetRetryTimerForTesting().IsRunning());
  EXPECT_EQ(base::TimeDelta(),
            worker_->GetBackoffEntryForTesting().GetTimeUntilRelease());
  on_work_finished_should_report_success_ = true;

  // No more tasks should remain.
  EXPECT_TRUE(base::CurrentThread::Get()->IsIdleForTesting());
}

}  // namespace

}  // namespace net


text:
#ifndef WRAPPER_H_
#define WRAPPER_H_

#include "config.h"
#include "libssh/libssh.h"
#include "libssh/libcrypto.h"
#include "libssh/libgcrypt.h"

enum ssh_mac_e {
  SSH_MAC_SHA1=1,
  SSH_MAC_SHA256,
  SSH_MAC_SHA384,
  SSH_MAC_SHA512
};

enum ssh_hmac_e {
  SSH_HMAC_SHA1 = 1,
  SSH_HMAC_SHA256,
  SSH_HMAC_SHA384,
  SSH_HMAC_SHA512,
  SSH_HMAC_MD5
};

enum ssh_des_e {
  SSH_3DES,
  SSH_DES
};

struct ssh_hmac_struct {
  const char* name;
  enum ssh_hmac_e hmac_type;
};

typedef struct ssh_mac_ctx_struct *ssh_mac_ctx;
MD5CTX md5_init(void);
void md5_update(MD5CTX c, const void *data, unsigned long len);
void md5_final(unsigned char *md,MD5CTX c);

SHACTX sha1_init(void);
void sha1_update(SHACTX c, const void *data, unsigned long len);
void sha1_final(unsigned char *md,SHACTX c);
void sha1(unsigned char *digest,int len,unsigned char *hash);

SHA256CTX sha256_init(void);
void sha256_update(SHA256CTX c, const void *data, unsigned long len);
void sha256_final(unsigned char *md,SHA256CTX c);
void sha256(unsigned char *digest, int len, unsigned char *hash);

SHA384CTX sha384_init(void);
void sha384_update(SHA384CTX c, const void *data, unsigned long len);
void sha384_final(unsigned char *md,SHA384CTX c);
void sha384(unsigned char *digest, int len, unsigned char *hash);

SHA512CTX sha512_init(void);
void sha512_update(SHA512CTX c, const void *data, unsigned long len);
void sha512_final(unsigned char *md,SHA512CTX c);
void sha512(unsigned char *digest, int len, unsigned char *hash);

void evp(int nid, unsigned char *digest, int len, unsigned char *hash, unsigned int *hlen);
EVPCTX evp_init(int nid);
void evp_update(EVPCTX ctx, const void *data, unsigned long len);
void evp_final(EVPCTX ctx, unsigned char *md, unsigned int *mdlen);

ssh_mac_ctx ssh_mac_ctx_init(enum ssh_mac_e type);
void ssh_mac_update(ssh_mac_ctx ctx, const void *data, unsigned long len);
void ssh_mac_final(unsigned char *md, ssh_mac_ctx ctx);

HMACCTX hmac_init(const void *key,int len, enum ssh_hmac_e type);
void hmac_update(HMACCTX c, const void *data, unsigned long len);
void hmac_final(HMACCTX ctx,unsigned char *hashmacbuf,unsigned int *len);
size_t hmac_digest_len(enum ssh_hmac_e type);

int crypt_set_algorithms(ssh_session session, enum ssh_des_e des_type);
int crypt_set_algorithms_server(ssh_session session);
struct ssh_crypto_struct *crypto_new(void);
void crypto_free(struct ssh_crypto_struct *crypto);

void ssh_reseed(void);

void ssh_cipher_clear(struct ssh_cipher_struct *cipher);
struct ssh_hmac_struct *ssh_get_hmactab(void);
const char *ssh_hmac_type_to_string(enum ssh_hmac_e hmac_type);

#endif /* WRAPPER_H_ */


text:
package collection;

import java.util.ArrayDeque;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * Created by sun on 2016/12/29.
 */
public class QueueTest {
    public static void main(String[] args){
        //测试PriorityQueue用法
        System.out.println("---测试PriorityQueue用法---");
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
        priorityQueue.offer(1);
        priorityQueue.offer(3);
        priorityQueue.offer(5);
        priorityQueue.offer(5);
        priorityQueue.offer(7);
        printQueue(priorityQueue);
        System.out.println(priorityQueue.poll() + "\n-----");
        System.out.println(priorityQueue.peek() + "\n-----");
        printQueue(priorityQueue);

        //测试ArrayDeque用法
        System.out.println("---测试ArrayDeque用法---");
        ArrayDeque<Integer> arrayDeque = new ArrayDeque<Integer>();
        arrayDeque.offer(1);
        arrayDeque.offer(2);
        arrayDeque.offer(3);
        arrayDeque.offer(5);
        printQueue(arrayDeque);
        System.out.println(arrayDeque.poll() + "\n-----");
        System.out.println(arrayDeque.peek() + "\n-----");
        printQueue(arrayDeque);

        //用ArrayDeque来表示一个栈
        System.out.println("---用ArrayDeque来表示一个栈---");
        ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
        stack.offerFirst(1);
        stack.offerFirst(3);
        stack.offerFirst(9);
        stack.offerFirst(11);
        printQueue(stack);
        System.out.println(stack.pollFirst() + "\n-----");
        System.out.println(stack.peekFirst() + "\n-----");
        printQueue(stack);

        //用ArrayDeque来表示一个队列
        System.out.println("---用ArrayDeque来表示一个队列---");
        ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
        queue.offerLast(1);
        queue.offerLast(2);
        queue.offerLast(5);
        queue.offerLast(7);
        printQueue(queue);
        System.out.println(queue.pollFirst() + "\n-----");
        System.out.println(queue.peekFirst() + "\n-----");
        printQueue(queue);

    }

    /**
     * 打印Integer类型的Queue实现类的对象
     * @param queue Integer类型的Queue实现类的对象
     */
    public static void printQueue(Queue<Integer> queue){
        for (Integer element : queue) {
            System.out.println(element);
        }
        System.out.println("-----");
    }
}


text:
import Vue from 'vue'

import * as api from '../../api'
import * as types from '../mutation-types'

// initial state
const state = {
    categories: []
}

// getters
const getters = {
    categories: state => state.categories
}

// actions
const actions = {
    createCategory ({ commit }, data) {
        return api.createCategory(data).then(response => {
            commit(types.ADD_CATEGORY, { category: response.data })
        })
    },

    getCategories ({ commit }) {
        return api.getCategories().then(response => {
            commit(types.SET_CATEGORIES, { categories: response.data })
        })
    },

    updateCategory ({ commit }, data) {
        return api.updateCategory(data.pk, data).then(response => {
            commit(types.UPDATE_CATEGORY, { category: response.data })
        })
    },

    deleteCategory ({ commit }, data) {
        return api.deleteCategory(data.pk).then(response => {
            commit(types.DELETE_CATEGORY, { pk: data.pk })
        })
    }
}

// mutations
const mutations = {
    [types.ADD_CATEGORY] (state, { category }) {
        state.categories.push(category)
    },

    [types.SET_CATEGORIES] (state, { categories }) {
        state.categories = categories
    },

    [types.UPDATE_CATEGORY] (state, { category }) {
        state.categories.filter(function (item, pos) {
            if (item.pk === category.pk) {
                Vue.set(state.categories, pos, category)
            }
        })
    },

    [types.DELETE_CATEGORY] (state, { pk }) {
        state.categories = state.categories.filter(function (category) {
            return category.pk !== pk
        })
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}


text:
using EPiServer.Forms.Helpers.Internal;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;

namespace EPiServer.Forms.Samples
{
    public class FormsSamplePublicStaticFileStartupFilter : IStartupFilter
    {
        public System.Action<IApplicationBuilder> Configure(System.Action<IApplicationBuilder> next) =>
            app =>
            {
                app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath = ModuleHelper.GetPublicVirtualPath("EPiServer.Forms.Samples"),
                    FileProvider = new ManifestEmbeddedFileProvider(typeof(FormsSamplePublicStaticFileStartupFilter).Assembly, "/ClientResources/ViewMode")
                });

                next(app);
            };
    }
}


text:
// Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.index;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

import com.google.common.base.CharMatcher;
import com.google.gwtorm.server.OrmException;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Definition of a field stored in the secondary index.
 *
 * @param <I> input type from which documents are created and search results are returned.
 * @param <T> type that should be extracted from the input object when converting to an index
 *     document.
 */
public final class FieldDef<I, T> {
  public static FieldDef.Builder<String> exact(String name) {
    return new FieldDef.Builder<>(FieldType.EXACT, name);
  }

  public static FieldDef.Builder<String> fullText(String name) {
    return new FieldDef.Builder<>(FieldType.FULL_TEXT, name);
  }

  public static FieldDef.Builder<Integer> intRange(String name) {
    return new FieldDef.Builder<>(FieldType.INTEGER_RANGE, name).stored();
  }

  public static FieldDef.Builder<Integer> integer(String name) {
    return new FieldDef.Builder<>(FieldType.INTEGER, name);
  }

  public static FieldDef.Builder<String> prefix(String name) {
    return new FieldDef.Builder<>(FieldType.PREFIX, name);
  }

  public static FieldDef.Builder<byte[]> storedOnly(String name) {
    return new FieldDef.Builder<>(FieldType.STORED_ONLY, name).stored();
  }

  public static FieldDef.Builder<Timestamp> timestamp(String name) {
    return new FieldDef.Builder<>(FieldType.TIMESTAMP, name);
  }

  @FunctionalInterface
  public interface Getter<I, T> {
    T get(I input) throws OrmException, IOException;
  }

  public static class Builder<T> {
    private final FieldType<T> type;
    private final String name;
    private boolean stored;

    public Builder(FieldType<T> type, String name) {
      this.type = requireNonNull(type);
      this.name = requireNonNull(name);
    }

    public Builder<T> stored() {
      this.stored = true;
      return this;
    }

    public <I> FieldDef<I, T> build(Getter<I, T> getter) {
      return new FieldDef<>(name, type, stored, false, getter);
    }

    public <I> FieldDef<I, Iterable<T>> buildRepeatable(Getter<I, Iterable<T>> getter) {
      return new FieldDef<>(name, type, stored, true, getter);
    }
  }

  private final String name;
  private final FieldType<?> type;
  private final boolean stored;
  private final boolean repeatable;
  private final Getter<I, T> getter;

  private FieldDef(
      String name, FieldType<?> type, boolean stored, boolean repeatable, Getter<I, T> getter) {
    checkArgument(
        !(repeatable && type == FieldType.INTEGER_RANGE),
        "Range queries against repeated fields are unsupported");
    this.name = checkName(name);
    this.type = requireNonNull(type);
    this.stored = stored;
    this.repeatable = repeatable;
    this.getter = requireNonNull(getter);
  }

  private static String checkName(String name) {
    CharMatcher m = CharMatcher.anyOf("abcdefghijklmnopqrstuvwxyz0123456789_");
    checkArgument(name != null && m.matchesAllOf(name), "illegal field name: %s", name);
    return name;
  }

  /** @return name of the field. */
  public String getName() {
    return name;
  }

  /** @return type of the field; for repeatable fields, the inner type, not the iterable type. */
  public FieldType<?> getType() {
    return type;
  }

  /** @return whether the field should be stored in the index. */
  public boolean isStored() {
    return stored;
  }

  /**
   * Get the field contents from the input object.
   *
   * @param input input object.
   * @return the field value(s) to index.
   * @throws OrmException
   */
  public T get(I input) throws OrmException {
    try {
      return getter.get(input);
    } catch (IOException e) {
      throw new OrmException(e);
    }
  }

  /** @return whether the field is repeatable. */
  public boolean isRepeatable() {
    return repeatable;
  }
}


text:
package org.adligo.xml_io_tests.shared.models;

import java.util.HashSet;
import java.util.Set;

public class SimpleCollectionsWithComments  {

	/**
	 * roles
	 */
	protected Set<String> roles = new HashSet<String>();
	// <TESTS!> roles

}


text:
shared_examples_for 'empty_lines_around_class_or_module_body' do |type|
  context 'when EnforcedStyle is empty_lines_special' do
    let(:cop_config) { { 'EnforcedStyle' => 'empty_lines_special' } }

    context 'when first child is a method' do
      it "requires blank line at the beginning and ending of #{type} body" do
        expect_no_offenses(<<~RUBY)
          #{type} SomeObject

            def do_something; end

          end
        RUBY
      end

      context 'source without blank lines' do
        it "registers an offense for #{type} not beginning "\
           'and ending with a blank line' do
          expect_offense(<<~RUBY)
            #{type} SomeObject
              def do_something; end
            ^ #{missing_begin}
            end
            ^ #{missing_end}
          RUBY

          expect_correction(<<~RUBY)
            #{type} SomeObject

              def do_something; end

            end
          RUBY
        end
      end

      context "when #{type} has a namespace" do
        it 'requires no empty lines for namespace but '\
          "requires blank line at the beginning and ending of #{type} body" do
          expect_no_offenses(<<~RUBY)
            #{type} Parent
              #{type} SomeObject

                def do_something
                end

              end
            end
          RUBY
        end

        context 'source without blank lines' do
          it 'registers and autocorrects the offenses' do
            expect_offense(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  def do_something
              ^ #{missing_begin}
                  end
                end
              ^ #{missing_end}
              end
            RUBY

            expect_correction(<<~RUBY)
              #{type} Parent
                #{type} SomeObject

                  def do_something
                  end

                end
              end
            RUBY
          end
        end

        context 'source with blank lines' do
          it 'autocorrects the offenses' do
            expect_offense(<<~RUBY)
              #{type} Parent

              ^{} #{extra_begin}
                #{type} SomeObject

                  def do_something
                  end

                end

              ^{} #{extra_end}
              end
            RUBY

            expect_correction(<<~RUBY)
              #{type} Parent
                #{type} SomeObject

                  def do_something
                  end

                end
              end
            RUBY
          end
        end
      end
    end

    context 'when first child is an access modifier' do
      context "with blank lines at the beginning and ending of #{type} body" do
        it 'registers no offense' do
          expect_no_offenses(<<~RUBY)
            #{type} SomeObject

              private
              def do_something; end

            end
          RUBY
        end
      end

      context "with no blank lines at the beginning and ending of #{type} body" do
        it 'registers and corrects an offense' do
          expect_offense(<<~RUBY)
            #{type} SomeObject
              private
            ^ #{missing_begin}
              def do_something; end
            end
            ^ #{missing_end}
          RUBY

          expect_correction(<<~RUBY)
            #{type} SomeObject

              private
              def do_something; end

            end
          RUBY
        end
      end
    end

    context 'when first child is NOT a method' do
      it "does not require blank line at the beginning of #{type} body "\
        'but requires blank line before first def definition '\
        "and requires blank line at the end of #{type} body" do
        expect_no_offenses(<<~RUBY)
          #{type} SomeObject
            include Something

            def do_something; end

          end
        RUBY
      end

      context 'source without blank lines' do
        it "registers an offense for #{type} not ending with a blank line" do
          expect_offense(<<~RUBY)
            #{type} SomeObject
              include Something
              def do_something; end
            ^ #{missing_def}
            end
            ^ #{missing_end}
          RUBY

          expect_correction(<<~RUBY)
            #{type} SomeObject
              include Something

              def do_something; end

            end
          RUBY
        end
      end

      context 'source with blank lines' do
        it "registers an offense for #{type} beginning with a blank line" do
          expect_offense(<<~RUBY)
            #{type} SomeObject

            ^{} #{extra_begin}
              include Something
              def do_something; end
            ^ #{missing_def}

            end
          RUBY

          expect_correction(<<~RUBY)
            #{type} SomeObject
              include Something

              def do_something; end

            end
          RUBY
        end
      end

      context 'source with comment before method definition' do
        it "registers an offense for #{type} beginning with a blank line" do
          expect_offense(<<~RUBY)
            #{type} SomeObject

            ^{} #{extra_begin}
              include Something
              # Comment
            ^ #{missing_def}
              def do_something; end

            end
          RUBY

          expect_correction(<<~RUBY)
            #{type} SomeObject
              include Something

              # Comment
              def do_something; end

            end
          RUBY
        end
      end

      context "when #{type} has a namespace" do
        it 'requires no empty lines for namespace '\
          "and does not require blank line at the beginning of #{type} body "\
          "but requires blank line at the end of #{type} body" do
          expect_no_offenses(<<~RUBY)
            #{type} Parent
              #{type} SomeObject
                include Something

                def do_something
                end

              end
            end
          RUBY
        end

        context 'source without blank lines' do
          it 'registers and autocorrects the offenses' do
            expect_offense(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  include Something
                  def do_something
              ^ #{missing_def}
                  end
                end
              ^ #{missing_end}
              end
            RUBY

            expect_correction(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  include Something

                  def do_something
                  end

                end
              end
            RUBY
          end
        end

        context 'source with blank lines' do
          it 'registers and autocorrects the offenses' do
            expect_offense(<<~RUBY)
              #{type} Parent

              ^{} #{extra_begin}
                #{type} SomeObject

              ^{} #{extra_begin}
                  include Something

                  def do_something
                  end

                end

              ^{} #{extra_end}
              end
            RUBY

            expect_correction(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  include Something

                  def do_something
                  end

                end
              end
            RUBY
          end
        end

        context 'source with constants' do
          it 'registers and autocorrects the offenses' do
            expect_offense(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  URL = %q(http://example.com)
                  def do_something
              ^ #{missing_def}
                  end
                end
              ^ #{missing_end}
              end
            RUBY

            expect_correction(<<~RUBY)
              #{type} Parent
                #{type} SomeObject
                  URL = %q(http://example.com)

                  def do_something
                  end

                end
              end
            RUBY
          end
        end
      end
    end

    context 'when namespace has multiple children' do
      it 'requires empty lines for namespace' do
        expect_no_offenses(<<~RUBY)
          #{type} Parent

            #{type} Mom

              def do_something
              end

            end
            #{type} Dad

            end

          end
        RUBY
      end
    end

    context "#{type} with only constants" do
      it 'registers and autocorrects the offenses' do
        expect_offense(<<~RUBY)
          #{type} Parent
            #{type} SomeObject
              URL = %q(http://example.com)
              WSDL = %q(http://example.com/wsdl)
            end
          ^ #{missing_end}
          end
        RUBY

        expect_correction(<<~RUBY)
          #{type} Parent
            #{type} SomeObject
              URL = %q(http://example.com)
              WSDL = %q(http://example.com/wsdl)

            end
          end
        RUBY
      end
    end

    context "#{type} with constant and child #{type}" do
      it 'registers and autocorrects the offenses' do
        expect_offense(<<~RUBY)
          #{type} Parent
            URL = %q(http://example.com)
            #{type} SomeObject
          ^ #{missing_type}
              def do_something; end
          ^ #{missing_begin}
            end
          ^ #{missing_end}
          end
          ^ #{missing_end}
        RUBY

        expect_correction(<<~RUBY)
          #{type} Parent
            URL = %q(http://example.com)

            #{type} SomeObject

              def do_something; end

            end

          end
        RUBY
      end
    end

    context "#{type} with empty body" do
      context 'with empty line' do
        let(:source) do
          <<~RUBY
            #{type} SomeObject

            end
          RUBY
        end

        it 'does NOT register offenses' do
          expect_no_offenses(source)
        end
      end

      context 'without empty line' do
        let(:source) do
          <<~RUBY
            #{type} SomeObject
            end
          RUBY
        end

        it 'does NOT register offenses' do
          expect_no_offenses(source)
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;
using GRA.Domain.Repository;
using GRA.Domain.Service.Abstract;
using Microsoft.Extensions.Logging;

namespace GRA.Domain.Service
{
    public class AuthorizationCodeService : BaseUserService<AuthorizationCodeService>
    {
        private readonly IAuthorizationCodeRepository _authorizationCodeRepository;
        public AuthorizationCodeService(ILogger<AuthorizationCodeService> logger,
            GRA.Abstract.IDateTimeProvider dateTimeProvider,
            IUserContextProvider userContextProvider,
            IAuthorizationCodeRepository authorizationCodeRepository)
            : base(logger, dateTimeProvider, userContextProvider)
        {
            SetManagementPermission(Model.Permission.ManageRoles);
            _authorizationCodeRepository = authorizationCodeRepository
                ?? throw new ArgumentNullException(nameof(authorizationCodeRepository));
        }

        public async Task<DataWithCount<IEnumerable<AuthorizationCode>>>
            GetPaginatedListAsync(BaseFilter filter)
        {
            VerifyManagementPermission();
            filter.SiteId = GetCurrentSiteId();
            return await _authorizationCodeRepository.PageAsync(filter);
        }

        public async Task<AuthorizationCode> GetByIdAsync(int id)
        {
            VerifyManagementPermission();
            return await _authorizationCodeRepository.GetByIdAsync(id);
        }

        public async Task<AuthorizationCode> AddAsync(AuthorizationCode authorizationCode)
        {
            VerifyManagementPermission();
            var siteId = GetCurrentSiteId();

            var inUse = await _authorizationCodeRepository.GetByCodeAsync(siteId, authorizationCode.Code);
            if (inUse != null)
            {
                throw new GraException($"Code is already in use.");
            }

            authorizationCode.SiteId = siteId;

            return await _authorizationCodeRepository.AddSaveAsync(GetClaimId(ClaimType.UserId),
                authorizationCode);
        }

        public async Task UpdateAsync(AuthorizationCode authorizationCode)
        {
            VerifyManagementPermission();
            var authId = GetClaimId(ClaimType.UserId);
            var siteId = GetCurrentSiteId();
            var currentAuthorizationCode = await _authorizationCodeRepository.GetByIdAsync(
                authorizationCode.Id);
            if (currentAuthorizationCode.SiteId != siteId)
            {
                _logger.LogError($"User {authId} cannot update authorization code {currentAuthorizationCode.Id} for site {currentAuthorizationCode.SiteId}.");
                throw new GraException($"Permission denied - authorization code belongs to site id {currentAuthorizationCode.SiteId}.");
            }
            var existingCode = await _authorizationCodeRepository
                .GetByCodeAsync(siteId, authorizationCode.Code);
            if (existingCode != null && existingCode.Id != currentAuthorizationCode.Id)
            {
                throw new GraException($"Code is already in use.");
            }

            currentAuthorizationCode.Code = authorizationCode.Code;
            currentAuthorizationCode.Description = authorizationCode.Description;
            currentAuthorizationCode.IsSingleUse = authorizationCode.IsSingleUse;
            currentAuthorizationCode.RoleId = authorizationCode.RoleId;

            await _authorizationCodeRepository.UpdateSaveAsync(authId, currentAuthorizationCode);
        }

        public async Task RemoveAsync(int authorizationCodeId)
        {
            VerifyManagementPermission();
            var authId = GetClaimId(ClaimType.UserId);
            var siteId = GetCurrentSiteId();
            var authorizationCode = await _authorizationCodeRepository.GetByIdAsync(authorizationCodeId);
            if (authorizationCode.SiteId != siteId)
            {
                _logger.LogError($"User {authId} cannot delete authorization code {authorizationCodeId} for site {authorizationCode.SiteId}.");
                throw new GraException($"Permission denied - authorization code belongs to site id {authorizationCode.SiteId}.");
            }
            await _authorizationCodeRepository.RemoveSaveAsync(authId, authorizationCodeId);
        }

        public async Task<bool> ValidateAuthorizationCode(string authorizationCode)
        {
            string fixedCode = authorizationCode.Trim().ToLowerInvariant();
            int siteId = GetCurrentSiteId();
            var authCode = await _authorizationCodeRepository.GetByCodeAsync(siteId, fixedCode);
            if (authCode == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}


text:
import * as http from 'http';
import * as debug from 'debug';

import App from './routes';

debug('ts-express:server');

const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);

const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

function normalizePort(val: number | string): number | string | boolean {
    const portNum: number = (typeof val === 'string') ? parseInt(val, 10) : val;
    if (isNaN(portNum)) {
        return val;
    } else if (portNum >= 0) {
        return portNum;
    } else {
        return false;
    }
}

function onError(error: NodeJS.ErrnoException): void {
    if (error.syscall !== 'listen') {
        throw error;
    }
    const bind = (typeof port === 'string') ? 'Pipe ' + port : 'Port ' + port;
    switch (error.code) {
        case 'EACCES':
            console.error(`${bind} requires elevated privileges`);
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(`${bind} is already in use`);
            process.exit(1);
            break;
        default:
            throw error;
    }
}

function onListening(): void {
    const addr = server.address();
    const bind = (typeof addr === 'string') ? `pipe ${addr}` : `port ${addr.port}`;
    debug(`Listening on ${bind}`);
}


text:
(function() {'use strict';
angular.module('schedulerApp').
  controller('MainCtrl', ['$scope', 'schedules', 'teachers', 'student_groups',
              function ($scope, schedules, teachers, student_groups) {
    var date = new Date();
    date.setHours(9);
    date.setMinutes(10);
    date.setSeconds(0);

    $scope.days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
    var calendar = [];
    for (var k = 0; k <= 185; k++) {
      calendar.push({
        day: $scope.days[Math.floor(k/37)],
        id: k,
        startTime: moment(date).format('h:mm')
      });
      if ((k+1)%37 === 0) {
        date.setHours(9);
        date.setMinutes(10);
      } else date.setTime(date.getTime()+600000);
    }

    $scope.calendar = calendar;

    $scope.sortableOptions = {
      start: function(e, ui) {
        $scope.$apply(function() { $scope.dragging = true; });
      },
      cursorAt: { left: 0, top: 0 },
      stop: function(e, ui) {
        $scope.$apply(function() { $scope.dragging = false; });

        _.each($('.slot'), function(slot) {
          if (ui.offset.top > $(slot).offset().top &&
              ui.offset.top < $(slot).offset().top+$(slot).height() &&
              ui.offset.left > $(slot).offset().left &&
              ui.offset.left < $(slot).offset().left+$(slot).width()) {
            $scope.$apply(function() {
              var slot_id = parseInt($(slot).find('.slot_id').html(), 10);
              var data = _.find($scope.calendar, function(data) {
                return data.id === slot_id;
              });

              var teacher_id = parseInt(ui.item.find('.teacher_id').html(), 10);
              var teacher = _.find($scope.teachers, function(teacher) {
                return teacher.id === teacher_id;
              });

              data.teacher = teacher;

              var nextSlot = $scope.calendar[$scope.calendar.indexOf(data)+1];
              if (nextSlot.day === data.day) nextSlot.teacher = teacher;
            });
          }
        });
      }
    };

    $scope.changeGroup = function (id) {
      if (id !== $scope.selected_student_group) {
        $scope.selected_student_group = id;
      }
    };

    teachers.fetch().then(function (response) {
      $scope.teachers = response.data.teachers;
    });

    student_groups.fetch().then(function (response) {
      $scope.student_groups = response.data.student_groups;
      $scope.selected_student_group = $scope.student_groups[0].id;
    });

    schedules.fetch().then(function (response) {
      debugger;
    });
  }]);
}());


text:
package io.cloudracer.properties;

import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * Parse the XML configuration document, used for testing, to endure that it is properly formated.
 *
 * @author John McDonnell
 */
public class TestServerConfigurationParseXML {

    /**
     * Parse the XML configuration document that is used for testing.
     *
     * @throws Exception
     *
     */
    @Test
    public void parseXML() throws Exception { // NOSONAR
        final String xml = "/mocktcpserver.xml";
        final String schemaName = "/mocktcpserver.xsd";

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);

        DocumentBuilder parser;
        try {
            parser = builderFactory.newDocumentBuilder();

            Document document = parser.parse(ClassLoader.class.getResourceAsStream(xml));

            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            Source schemaFile = new StreamSource(ClassLoader.class.getResourceAsStream(schemaName));
            Schema schema = factory.newSchema(schemaFile);

            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(document));
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw e; // NOSONAR
        }
    }
}


text:
import * as React from "react";
import type { Observable } from "core/Misc/observable";
import type { PropertyChangedEvent } from "../../../propertyChangedEvent";
import type { Control } from "gui/2D/controls/control";
import { CommonControlPropertyGridComponent } from "../../../tabs/propertyGrids/gui/commonControlPropertyGridComponent";
import type { LockObject } from "../../../tabs/propertyGrids/lockObject";

interface IControlPropertyGridComponentProps {
    control: Control;
    lockObject: LockObject;
    onPropertyChangedObservable?: Observable<PropertyChangedEvent>;
}

export class ControlPropertyGridComponent extends React.Component<IControlPropertyGridComponentProps> {
    constructor(props: IControlPropertyGridComponentProps) {
        super(props);
    }

    render() {
        const control = this.props.control;

        return (
            <div className="pane">
                <CommonControlPropertyGridComponent lockObject={this.props.lockObject} control={control} onPropertyChangedObservable={this.props.onPropertyChangedObservable} />
            </div>
        );
    }
}


text:
import abc

from django.contrib.contenttypes.models import ContentType
from denorm.db import triggers
from django.db import connection
from django.db.models import sql, ManyToManyField
from django.db.models.fields.related import ManyToManyField
from django.db.models.manager import Manager
from denorm.models import DirtyInstance
from django.db.models.sql import Query
from django.db.models.sql.compiler import SQLCompiler
from django.db.models.sql.query import Query
from django.db.models.sql.where import WhereNode

# Remember all denormalizations.
# This is used to rebuild all denormalized values in the whole DB.
alldenorms = []

def many_to_many_pre_save(sender, instance, **kwargs):
    """
    Updates denormalised many-to-many fields for the model
    """
    if instance.pk:
        # Need a primary key to do m2m stuff
        for m2m in sender._meta.local_many_to_many:
            # This gets us all m2m fields, so limit it to just those that are denormed
            if hasattr(m2m, 'denorm'):
                # Does some extra jiggery-pokery for "through" m2m models.
                # May not work under lots of conditions.
                if hasattr(m2m.rel, 'through_model'):
                    # Clear exisiting through records (bit heavy handed?)
                    kwargs = {m2m.related.var_name: instance}

                    # Can't use m2m_column_name in a filter
                    # kwargs = { m2m.m2m_column_name(): instance.pk, }
                    m2m.rel.through_model.objects.filter(**kwargs).delete()

                    values = m2m.denorm.func(instance)
                    for value in values:
                        kwargs.update({m2m.m2m_reverse_name(): value.pk})
                        m2m.rel.through_model.objects.create(**kwargs)

                else:
                    values = m2m.denorm.func(instance)
                    setattr(instance, m2m.attname, values)

def many_to_many_post_save(sender, instance, created, **kwargs):
    if created:
        def check_resave():
            for m2m in sender._meta.local_many_to_many:
                if hasattr(m2m, 'denorm'):
                    return True
            return False

        if check_resave():
            instance.save()

class Denorm(object):
    def __init__(self, skip=None):
        self.func = None
        self.skip = skip

    def setup(self, **kwargs):
        """
        Adds 'self' to the global denorm list
        and connects all needed signals.
        """
        global alldenorms
        if self not in alldenorms:
            alldenorms.append(self)

    def update(self, qs):
        """
        Updates the denormalizations in all instances in the queryset 'qs'.
        """
        for instance in qs.distinct():
            # only write new values to the DB if they actually changed
            new_value = self.func(instance)

            # Get attribute name (required for denormalising ForeignKeys)
            attname = instance._meta.get_field(self.fieldname).attname

            if isinstance(getattr(instance, attname), Manager) and getattr(instance, attname).all() != new_value:
                # many to many field
                for o in qs.filter(pk=instance.pk):
                    o.attname = new_value
                instance.save()

            elif not getattr(instance, attname) == new_value:
                setattr(instance, attname, new_value)
                # an update before the save is needed to handle CountFields
                # CountField does not update its value during pre_save
                qs.filter(pk=instance.pk).update(**{attname: new_value})
                instance.save()
        flush()

    def get_triggers(self, using):
        return []

class BaseCallbackDenorm(Denorm):
    """
    Handles the denormalization of one field, using a python function
    as a callback.
    """

    def setup(self, **kwargs):
        """
        Calls setup() on all DenormDependency resolvers
        """
        super(BaseCallbackDenorm, self).setup(**kwargs)

        for dependency in self.depend:
            dependency.setup(self.model)

    def get_triggers(self, using):
        """
        Creates a list of all triggers needed to keep track of changes
        to fields this denorm depends on.
        """
        trigger_list = list()

        # Get the triggers of all DenormDependency instances attached
        # to our callback.
        for dependency in self.depend:
            trigger_list += dependency.get_triggers(using=using)

        return trigger_list + super(BaseCallbackDenorm, self).get_triggers(using=using)

class CallbackDenorm(BaseCallbackDenorm):
    """
    As above, but with extra triggers on self as described below
    """

    def get_triggers(self, using):
        content_type = str(ContentType.objects.get_for_model(self.model).pk)

        # Create a trigger that marks any updated or newly created
        # instance of the model containing the denormalized field
        # as dirty.
        # This is only really needed if the instance was changed without
        # using the ORM or if it was part of a bulk update.
        # In those cases the self_save_handler won't get called by the
        # pre_save signal, so we need to ensure flush() does this later.
        action = triggers.TriggerActionInsert(
            model=DirtyInstance,
            columns=("content_type_id", "object_id"),
            values=(content_type, "NEW.%s" % self.model._meta.pk.get_attname_column()[1])
        )
        trigger_list = [
            triggers.Trigger(self.model, "after", "update", [action], content_type, using, self.skip),
            triggers.Trigger(self.model, "after", "insert", [action], content_type, using, self.skip),
        ]

        return trigger_list + super(CallbackDenorm, self).get_triggers(using=using)

class BaseCacheKeyDenorm(Denorm):
    def __init__(self, depend_on_related, *args, **kwargs):
        self.depend = depend_on_related
        super(BaseCacheKeyDenorm, self).__init__(*args, **kwargs)
        import random
        self.func = lambda o: random.randint(-9223372036854775808, 9223372036854775807)

    def setup(self, **kwargs):
        """
        Calls setup() on all DenormDependency resolvers
        """
        super(BaseCacheKeyDenorm, self).setup(**kwargs)

        for dependency in self.depend:
            dependency.setup(self.model)

    def get_triggers(self, using):
        """
        Creates a list of all triggers needed to keep track of changes
        to fields this denorm depends on.
        """
        trigger_list = list()

        # Get the triggers of all DenormDependency instances attached
        # to our callback.
        for dependency in self.depend:
            trigger_list += dependency.get_triggers(using=using)

        return trigger_list + super(BaseCacheKeyDenorm, self).get_triggers(using=using)

class CacheKeyDenorm(BaseCacheKeyDenorm):
    """
    As above, but with extra triggers on self as described below
    """

    def get_triggers(self, using):
        content_type = str(ContentType.objects.get_for_model(self.model).pk)

        # This is only really needed if the instance was changed without
        # using the ORM or if it was part of a bulk update.
        # In those cases the self_save_handler won't get called by the
        # pre_save signal
        action = triggers.TriggerActionUpdate(
            model=self.model,
            columns=(self.fieldname,),
            values=(triggers.RandomBigInt(),),
            where="%s=NEW.%s" % ((self.model._meta.pk.get_attname_column()[1],) * 2),
        )
        trigger_list = [
            triggers.Trigger(self.model, "after", "update", [action], content_type, using, self.skip),
            triggers.Trigger(self.model, "after", "insert", [action], content_type, using, self.skip),
        ]

        return trigger_list + super(CacheKeyDenorm, self).get_triggers(using=using)

class TriggerWhereNode(WhereNode):
    def sql_for_columns(self, data, qn, connection):
        """
        Returns the SQL fragment used for the left-hand side of a column
        constraint (for example, the "T1.foo" portion in the clause
        "WHERE ... T1.foo = 6").
        """
        table_alias, name, db_type = data
        if table_alias:
            if table_alias in ('NEW', 'OLD'):
                lhs = '%s.%s' % (table_alias, qn(name))
            else:
                lhs = '%s.%s' % (qn(table_alias), qn(name))
        else:
            lhs = qn(name)
        return connection.ops.field_cast_sql(db_type) % lhs

class TriggerFilterQuery(sql.Query):
    def __init__(self, model, trigger_alias, where=TriggerWhereNode):
        super(TriggerFilterQuery, self).__init__(model, where)
        self.trigger_alias = trigger_alias

    def get_initial_alias(self):
        return self.trigger_alias

class AggregateDenorm(Denorm):
    __metaclass__ = abc.ABCMeta

    def __init__(self, skip=None):
        self.manager = None
        self.skip = skip

    def setup(self, sender, **kwargs):
        # as we connected to the ``class_prepared`` signal for any sender
        # and we only need to setup once, check if the sender is our model.
        if sender is self.model:
            super(AggregateDenorm, self).setup(sender=sender, **kwargs)

        # related managers will only be available after both models are initialized
        # so check if its available already, and get our manager
        if not self.manager and hasattr(self.model, self.manager_name):
            self.manager = getattr(self.model, self.manager_name)

    def get_related_where(self, fk_name, using, type):
        related_where = ["%s=%s.%s" % (self.model._meta.pk.get_attname_column()[1], type, fk_name)]
        related_query = Query(self.manager.related.model)
        for name, value in self.filter.iteritems():
            related_query.add_filter((name, value))
        related_query.add_extra(None, None,
            ["%s=%s.%s" % (self.model._meta.pk.get_attname_column()[1], type, self.manager.related.field.m2m_column_name())],
            None, None, None)
        related_query.add_count_column()
        related_query.clear_ordering(force_empty=True)
        related_query.default_cols = False
        related_filter_where, related_where_params = related_query.get_compiler(using=using,
            connection=connection).as_sql()
        if related_filter_where is not None:
            related_where.append('(' + related_filter_where + ') > 0')
        return related_where, related_where_params

    def m2m_triggers(self, content_type, fk_name, related_field, using):
        """
        Returns triggers for m2m relation
        """
        related_inc_where, _ = self.get_related_where(fk_name, using, 'NEW')
        related_dec_where, related_where_params = self.get_related_where(fk_name, using, 'OLD')
        related_increment = triggers.TriggerActionUpdate(
            model=self.model,
            columns=(self.fieldname,),
            values=("%s+1" % self.fieldname,),
            where=(' AND '.join(related_inc_where), related_where_params),
        )
        related_decrement = triggers.TriggerActionUpdate(
            model=self.model,
            columns=(self.fieldname,),
            values=("%s-1" % self.fieldname,),
            where=(' AND '.join(related_dec_where), related_where_params),
        )
        trigger_list = [
            triggers.Trigger(related_field, "after", "update", [related_increment, related_decrement], content_type,
                using,
                self.skip),
            triggers.Trigger(related_field, "after", "insert", [related_increment], content_type, using, self.skip),
            triggers.Trigger(related_field, "after", "delete", [related_decrement], content_type, using, self.skip),
            ]
        return trigger_list

    def get_triggers(self, using):
        related_field = self.manager.related.field
        if isinstance(related_field, ManyToManyField):
            fk_name = related_field.m2m_reverse_name()
            inc_where = ["%(id)s=(SELECT %(reverse_related)s FROM %(m2m_table)s WHERE %(related)s=NEW.%(id)s)" % {
                'id': self.model._meta.pk.get_attname_column()[0],
                'related': related_field.m2m_column_name(),
                'm2m_table': related_field.m2m_db_table(),
                'reverse_related': fk_name,
                }]
            dec_where = [action.replace('NEW.', 'OLD.') for action in inc_where]
        else:
            fk_name = related_field.attname
            inc_where = ["%s=NEW.%s" % (self.model._meta.pk.get_attname_column()[1], fk_name)]
            dec_where = ["%s=OLD.%s" % (self.model._meta.pk.get_attname_column()[1], fk_name)]

        content_type = str(ContentType.objects.get_for_model(self.model).pk)

        inc_query = TriggerFilterQuery(self.manager.related.model, trigger_alias='NEW')
        for name, value in self.filter.iteritems():
            inc_query.add_filter((name, value))
        inc_filter_where, _ = inc_query.where.as_sql(SQLCompiler(inc_query, connection, using).quote_name_unless_alias,
            connection)

        dec_query = TriggerFilterQuery(self.manager.related.model, trigger_alias='OLD')
        for name, value in self.filter.iteritems():
            dec_query.add_filter((name, value))
        dec_filter_where, where_params = dec_query.where.as_sql(
            SQLCompiler(inc_query, connection, using).quote_name_unless_alias, connection)

        if inc_filter_where is not None:
            inc_where.append(inc_filter_where)
        if dec_filter_where is not None:
            dec_where.append(dec_filter_where)
            # create the triggers for the incremental updates
        increment = triggers.TriggerActionUpdate(
            model=self.model,
            columns=(self.fieldname,),
            values=(self.get_increment_value(),),
            where=(' AND '.join(inc_where), where_params),
        )
        decrement = triggers.TriggerActionUpdate(
            model=self.model,
            columns=(self.fieldname,),
            values=(self.get_decrement_value(),),
            where=(' AND '.join(dec_where), where_params),
        )

        other_model = self.manager.related.model
        trigger_list = [
            triggers.Trigger(other_model, "after", "update", [increment, decrement], content_type, using, self.skip),
            triggers.Trigger(other_model, "after", "insert", [increment], content_type, using, self.skip),
            triggers.Trigger(other_model, "after", "delete", [decrement], content_type, using, self.skip),
            ]
        if isinstance(related_field, ManyToManyField):
            trigger_list.extend(self.m2m_triggers(content_type, fk_name, related_field, using))
        return trigger_list

    @abc.abstractmethod
    def get_increment_value(self):
        """
        Returns SQL for incrementing value
        """

    @abc.abstractmethod
    def get_decrement_value(self):
        """
        Returns SQL for decrementing value
        """

class SumDenorm(AggregateDenorm):
    """
    Handles denormalization of a sum field by doing incrementally updates.
    """
    def __init__(self, skip=None, field = None):
        super(SumDenorm, self).__init__(skip)
        # in case we want to set the value without relying on the
        # correctness of the incremental updates we create a function that
        # calculates it from scratch.
        self.sum_field = field
        self.func = lambda obj: getattr(obj, self.manager_name).filter(**self.filter).aggregate('sum')

    def get_increment_value(self):
        return "%s+NEW.%s" % (self.fieldname, self.sum_field)

    def get_decrement_value(self):
        return "%s-OLD.%s" % (self.fieldname, self.sum_field)

class CountDenorm(AggregateDenorm):
    """
    Handles the denormalization of a count field by doing incrementally
    updates.
    """

    def __init__(self, skip=None):
        super(CountDenorm, self).__init__(skip)
        # in case we want to set the value without relying on the
        # correctness of the incremental updates we create a function that
        # calculates it from scratch.
        self.func = lambda obj: getattr(obj, self.manager_name).filter(**self.filter).count()

    def get_increment_value(self):
        return "%s+1" % self.fieldname

    def get_decrement_value(self):
        return "%s-1" % self.fieldname

def rebuildall(verbose=False):
    """
    Updates all models containing denormalized fields.
    Used by the 'denormalize' management command.
    """
    global alldenorms
    for i, denorm in enumerate(alldenorms):
        if verbose:
            print 'rebuilding', '%s/%s' % (i + 1, len(alldenorms)), denorm.fieldname, 'in', denorm.model
        denorm.update(denorm.model.objects.all())

def drop_triggers(using=None):
    triggerset = triggers.TriggerSet(using=using)
    triggerset.drop()

def install_triggers(using=None):
    """
    Installs all required triggers in the database
    """
    build_triggerset(using=using).install()

def build_triggerset(using=None):
    global alldenorms

    # Use a TriggerSet to ensure each event gets just one trigger
    triggerset = triggers.TriggerSet(using=using)
    for denorm in alldenorms:
        triggerset.append(denorm.get_triggers(using=using))
    return triggerset

def flush():
    """
    Updates all model instances marked as dirty by the DirtyInstance
    model.
    After this method finishes the DirtyInstance table is empty and
    all denormalized fields have consistent data.
    """

    # Loop until break.
    # We may need multiple passes, because an update on one instance
    # may cause an other instance to be marked dirty (dependency chains)
    while True:
        # Get all dirty markers
        qs = DirtyInstance.objects.all()

        # DirtyInstance table is empty -> all data is consistent -> we're done
        if not qs:
            break

        # Call save() on all dirty instances, causing the self_save_handler()
        # getting called by the pre_save signal.
        for dirty_instance in qs:
            if dirty_instance.content_object:
                dirty_instance.content_object.save()
            dirty_instance.delete()


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheGetClippingPathMethod
        {
            [Fact]
            public void ShouldReturnTheFirstClippingPath()
            {
                using (var image = new MagickImage(Files.InvitationTIF))
                {
                    var clippingPath = image.GetClippingPath();
                    Assert.NotNull(clippingPath);
                }
            }

            [Fact]
            public void ShouldReturnTheSpecifiedClippingPath()
            {
                using (var image = new MagickImage(Files.InvitationTIF))
                {
                    var clippingPath = image.GetClippingPath("#1");
                    Assert.NotNull(clippingPath);
                }
            }
        }
    }
}


text:
Edit instancegroup

### Synopsis

Edit an instancegroup configuration.

This command changes the cloud specification in the registry.

It does not update the cloud resources, to apply the changes use "kops update cluster".

```
kops edit instancegroup
```

### Options inherited from parent commands

```
      --alsologtostderr                  log to standard error as well as files
      --config string                    config file (default is $HOME/.kops.yaml)
      --log_backtrace_at traceLocation   when logging hits line file:N, emit a stack trace (default :0)
      --log_dir string                   If non-empty, write log files in this directory
      --logtostderr                      log to standard error instead of files (default false)
      --name string                      Name of cluster
      --state string                     Location of state storage
      --stderrthreshold severity         logs at or above this threshold go to stderr (default 2)
  -v, --v Level                          log level for V logs
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO
* [kops edit](kops_edit.md)	 - Edit resource


text:
// # Copyright © 2011-2012, Novus Craft
// # All rights reserved.

using System;
using System.Linq;
using System.Web.Mvc;
using Machine.Specifications;
using Machine.Specifications.Mvc;
using NovusCraft.Model;
using NovusCraft.Specifications.SpecUtils;
using NovusCraft.Web.Controllers;
using NovusCraft.Web.ViewModels;

namespace NovusCraft.Specifications.WebSpecs.ControllerSpecs.BlogControllerSpecs
{
	[Subject(typeof(BlogController))]
	public class when_edit_blog_post_page_is_requested : blog_controller_spec
	{
		static ActionResult result;

		Because of = () =>
		{
			session.Store(new BlogPost
			{
				Id = 1,
				Title = "Test Title",
				Slug = "test-title",
				Content = "Test Content",
				Category = "Category A",
				PublishedOn = new DateTimeOffset(2011, 11, 10, 09, 08, 07, TimeSpan.Zero)
			});
			session.Store(new BlogPost { Id = 2, Category = "Category B" });
			session.SaveChanges();

			Spec.RequiresAutoMapperConfiguration();

			result = controller.EditBlogPost(1);
		};

		It should_display_blog_post_for_editing =
			() => result.ShouldBeAView().And().ShouldUseDefaultView();

		It should_return_blog_post_with_id =
			() => result.Model<UpdateBlogPostModel>().Id.ShouldEqual(1);

		It should_return_blog_post_with_title =
			() => result.Model<UpdateBlogPostModel>().Title.ShouldEqual("Test Title");

		It should_return_blog_post_with_slug =
			() => result.Model<UpdateBlogPostModel>().Slug.ShouldEqual("test-title");

		It should_return_blog_post_with_content =
			() => result.Model<UpdateBlogPostModel>().Content.ShouldEqual("Test Content");

		It should_return_blog_post_with_category_title =
			() => result.Model<UpdateBlogPostModel>().Category.ShouldEqual("Category A");

		It should_return_blog_post_with_publish_date =
			() => result.Model<UpdateBlogPostModel>().PublishedOn.ShouldEqual(new DateTimeOffset(2011, 11, 10, 09, 08, 07, TimeSpan.Zero));

		It should_return_model_with_existing_categories =
			() => result.Model<UpdateBlogPostModel>().ExistingCategories.First().ShouldEqual("Category A");

		It requires_authentication =
			() => This.Action<BlogController>(controller => controller.EditBlogPost(0)).ShouldBeDecoratedWith<AuthorizeAttribute>();
	}
}


text:
title: UCP System requirements
description: Learn about the system requirements for installing Docker Universal Control
  Plane.
keywords:
- docker, ucp, architecture, requirements
---

Docker Universal Control Plane can be installed on-premises or on the cloud.
Before installing, be sure your infrastructure has these requirements.

## Hardware and software requirements

You can install UCP on-premises or on a cloud provider. To install UCP,
all nodes must have:

* Linux kernel version 3.10 or higher
* CS Docker Engine version 1.12.1 or higher
* 2.00 GB of RAM
* 3.00 GB of available disk space
* A static IP address

For highly-available installations, you also need a way to transfer files
between hosts.

## Ports used

When installing UCP on a host, make sure the following ports are open:

| Hosts             | Direction | Port                    | Purpose                                                                           |
|:------------------|:---------:|:------------------------|:----------------------------------------------------------------------------------|
| managers, workers |    in     | TCP 443  (configurable) | Port for the UCP web UI and API                                                   |
| managers          |    in     | TCP 2376 (configurable) | Port for the Docker Swarm manager. Used for backwards compatibility               |
| managers, workers |    in     | TCP 2377 (configurable) | Port for communication between swarm nodes                                        |
| managers, workers |  in, out  | TCP, UDP 4789           | Port for overlay networking                                                       |
| managers, workers |  in, out  | TCP, UDP 7946           | Port  for overlay networking                                                      |
| managers, workers |    in     | TCP 12376               | Port for a TLS proxy that provides access to UCP, Docker Engine, and Docker Swarm |
| managers          |    in     | TCP 12379               | Port for internal node configuration, cluster configuration, and HA               |
| managers          |    in     | TCP 12380               | Port for internal node configuration, cluster configuration, and HA               |
| managers          |    in     | TCP 12381               | Port for the certificate authority                                                |
| managers          |    in     | TCP 12382               | Port for the UCP certificate authority                                            |
| managers          |    in     | TCP 12383               | Port for the authentication storage backend                                       |
| managers          |    in     | TCP 12384               | Port for the authentication storage backend for replication across managers       |
| managers          |    in     | TCP 12385               | Port for the authentication service API                                           |
| managers          |    in     | TCP 12386               | Port for the authentication worker                                                |

## Compatibility and maintenance lifecycle

Docker Datacenter is a software subscription that includes 3 products:

* CS Docker Engine,
* Docker Trusted Registry,
* Docker Universal Control Plane.

[Learn more about the maintenance lifecycle for these products](http://success.docker.com/Get_Help/Compatibility_Matrix_and_Maintenance_Lifecycle).

## Where to go next

* [UCP architecture](../architecture.md)
* [Plan a production installation](plan-production-install.md)


text:
package org.elasticsearch.search.aggregations.metrics.valuecount;

import org.apache.lucene.index.AtomicReaderContext;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.LongArray;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.metrics.NumericMetricsAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;

import java.io.IOException;

/**
 * A field data based aggregator that counts the number of values a specific field has within the aggregation context.
 *
 * This aggregator works in a multi-bucket mode, that is, when serves as a sub-aggregator, a single aggregator instance aggregates the
 * counts for all buckets owned by the parent aggregator)
 */
public class ValueCountAggregator extends NumericMetricsAggregator.SingleValue {

    private final ValuesSource valuesSource;
    private SortedBinaryDocValues values;

    // a count per bucket
    LongArray counts;

    public ValueCountAggregator(String name, long expectedBucketsCount, ValuesSource valuesSource, AggregationContext aggregationContext, Aggregator parent) {
        super(name, 0, aggregationContext, parent);
        this.valuesSource = valuesSource;
        if (valuesSource != null) {
            // expectedBucketsCount == 0 means it's a top level bucket
            final long initialSize = expectedBucketsCount < 2 ? 1 : expectedBucketsCount;
            counts = bigArrays.newLongArray(initialSize, true);
        }
    }

    @Override
    public boolean shouldCollect() {
        return valuesSource != null;
    }

    @Override
    public void setNextReader(AtomicReaderContext reader) {
        values = valuesSource.bytesValues();
    }

    @Override
    public void collect(int doc, long owningBucketOrdinal) throws IOException {
        counts = bigArrays.grow(counts, owningBucketOrdinal + 1);
        values.setDocument(doc);
        counts.increment(owningBucketOrdinal, values.count());
    }

    @Override
    public double metric(long owningBucketOrd) {
        return valuesSource == null ? 0 : counts.get(owningBucketOrd);
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) {
        if (valuesSource == null) {
            return new InternalValueCount(name, 0);
        }
        assert owningBucketOrdinal < counts.size();
        return new InternalValueCount(name, counts.get(owningBucketOrdinal));
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalValueCount(name, 0l);
    }

    @Override
    public void doClose() {
        Releasables.close(counts);
    }

    public static class Factory<VS extends ValuesSource> extends ValuesSourceAggregatorFactory.LeafOnly<VS> {

        public Factory(String name, ValuesSourceConfig<VS> config) {
            super(name, InternalValueCount.TYPE.name(), config);
        }

        @Override
        protected Aggregator createUnmapped(AggregationContext aggregationContext, Aggregator parent) {
            return new ValueCountAggregator(name, 0, null, aggregationContext, parent);
        }

        @Override
        protected Aggregator create(ValuesSource valuesSource, long expectedBucketsCount, AggregationContext aggregationContext, Aggregator parent) {
            return new ValueCountAggregator(name, expectedBucketsCount, valuesSource, aggregationContext, parent);
        }

    }

}


text:
namespace Lightstreamer.DotNet.Client
{
    using System;
    using System.Runtime.InteropServices;

    internal class Constants
    {
        public const string pushServerBindCmd = "/lightstreamer/bind_session.txt";
        public const string pushServerCmd = "/lightstreamer/create_session.txt";
        public const string pushServerControlCmd = "/lightstreamer/control.txt";
        public const string pushServerSendMessageCmd = "/lightstreamer/send_message.txt";
        public const string requestAccept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
        public const string requestContentType = "application/x-www-form-urlencoded";
        public const string requestUserAgent = "Lightstreamer .NET Client";

        public class CommandMode
        {
            public const string addCommand = "ADD";
            public const string commandField = "command";
            public const string deleteCommand = "DELETE";
            public const string keyField = "key";
            public const string updateCommand = "UPDATE";
        }

        public class ConnectionConstraints
        {
            public const double maxBandwidthNotSet = -1.0;
            public const double slowingFactorNotSet = -1.0;
            public const double topMaxFrequencyNotSet = -1.0;
        }

        [StructLayout(LayoutKind.Sequential, Size=1)]
        public struct FastItemsListener
        {
            public static readonly string UNCHANGED;
            static FastItemsListener()
            {
                UNCHANGED = Lightstreamer.DotNet.Client.ServerUpdateEvent.UNCHANGED;
            }
        }

        public class PushServerPage
        {
            public const string controlAddress = "ControlAddress:";
            public const string eosMarker = "EOS";
            public const string errorCommand = "ERROR";
            public const string keepaliveMillis = "KeepaliveMillis:";
            public const string loopCommand = "LOOP";
            public const string maxBandwidth = "MaxBandwidth:";
            public const string okCommand = "OK";
            public const string overflowMarker = "OV";
            public const string probeCommand = "PROBE";
            public const string requestLimit = "RequestLimit:";
            public const string sessionId = "SessionId:";
            public const string slowingFactor = "SlowingFactor:";
            public const string syncErrorCommand = "SYNC ERROR";
            public const string topMaxFreq = "TopMaxFrequency:";
        }

        public class PushServerQuery
        {
            public const string adapterKey = "LS_adapter";
            public const string contentLengthKey = "LS_content_length";
            public const string dataAdapterKey = "LS_data_adapter";
            public const string itemNameBase = "LS_id";
            public const string keepaliveMillisKey = "LS_keepalive_millis";
            public const string maxBandwidthKey = "LS_requested_max_bandwidth";
            public const string maxFrequencyKey = "LS_top_max_frequency";
            public const string messageKey = "LS_message";
            public const string opAdd = "add";
            public const string opConstrain = "constrain";
            public const string opDelete = "delete";
            public const string opKey = "LS_op";
            public const string passwordKey = "LS_password";
            public const string pollingIdleKey = "LS_idle_millis";
            public const string pollingKey = "LS_polling";
            public const string pollingMillisKey = "LS_polling_millis";
            public const string pushModeBase = "LS_mode";
            public const string reportKey = "LS_report_info";
            public const string schemaKey = "LS_schema";
            public const string selectorKey = "LS_selector";
            public const string sessionIdKey = "LS_session";
            public const string slowingFactorKey = "LS_slowing_factor";
            public const string snapshotKey = "LS_Snapshot";
            public const string snapshotOn = "true";
            public const string tableBufferSizeKey = "LS_requested_buffer_size";
            public const string tableEndKey = "LS_end";
            public const string tableFrequencyKey = "LS_requested_max_frequency";
            public const string tableStartKey = "LS_start";
            public const string unfilteredDispatching = "unfiltered";
            public const string userIdKey = "LS_user";
            public const string winCodeBase = "LS_window";
        }

        public class ServerUpdateEvent
        {
            public const int itemCodeNotSet = -1;
            public const int winCodeNotSet = -1;
        }

        [StructLayout(LayoutKind.Sequential, Size=1)]
        public struct SimpleTableListener
        {
            public static readonly string UNCHANGED;
            static SimpleTableListener()
            {
                UNCHANGED = Lightstreamer.DotNet.Client.ServerUpdateEvent.UNCHANGED;
            }
        }

        public class SubscribedTableKey
        {
            public const int keyValueNotSet = -1;
        }

        public class TableManager
        {
            public const int bufferSizeNotSet = -1;
            public const int distinctSnapshotLengthNotSet = -1;
            public const int endNotSet = -1;
            public const int maxBufferSizeNotSet = -1;
            public const double maxFrequencyNotSet = -1.0;
            public const int startNotSet = -1;
        }
    }
}


text:
var https = require('https')
var _ = require('underscore')

var h = require('./helpers')

module.exports = {
  send: send,
  sendFormat: sendFormat
}

var defaultReqOptions = {
  hostname: 'mandrillapp.com',
  method: 'POST',
  port: 443
}
var config = h.getConfig()
var apiPrefix = '/api/1.0/'

function callMandrill (json, path, callback) {
  var req = https.request(_.extend({
    path: path,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': json.length
    }
  }, defaultReqOptions), function(res) {
    if(res.statusCode == '200') callback(true)
  })
  req.write(json)
  req.end()
}

function send (message, callback) {
  var path = apiPrefix + 'messages/send.json'
  var requestJSON = JSON.stringify({
    key: config.mandrillAPIKey,
    message: message
  })
  callMandrill(requestJSON, path, callback)
}

function sendFormat (date, text, subject, recipient) {
  var tmp = new Date
  send({
    send_at: date,
    text: text,
    subject: subject,
    from_email: 'mandrill@ls7.ch',
    to: [{email: recipient}]
  }, function () {
    console.log('Notifier set! Will trigger at ' + (tmp.setTime(date*1000) && tmp))
  })
}


text:
<?php

class Ambimax_Import_Test_Helper_Import_Product extends Ambimax_Import_Test_Abstract
{
    /**
     * @expectedException Exception
     * @expectedExceptionMessageRegExp /sku is not set/
     */
    public function testGetUrlKeyWithMissingSku()
    {
        $mapperMock = $this->getMockBuilder('Ho_Import_Model_Mapper')
            ->setMethods(['mapItem'])
            ->getMock();

        $mapperMock
            ->expects($this->any())
            ->method('mapItem')
            ->willReturnCallback(array($this, 'mapResult'));

        $this->replaceByMock('singleton', 'ho_import/mapper', $mapperMock);

        /** @var Ambimax_Import_Helper_Import_Product $helper */
        $helper = Mage::helper('ambimax_import/import_product');

        call_user_func_array(array($helper, 'getUrlKeyWithSku'), array($line = array(), $sku = '')); // @codingStandardsIgnoreLine
    }

    /**
     * @expectedException Exception
     * @expectedExceptionMessageRegExp /url-key must not be empty for sku "invalid"/
     */
    public function testInvalidGetUrlKeyWithSku()
    {
        $mapperMock = $this->getMockBuilder('Ho_Import_Model_Mapper')
            ->setMethods(['mapItem'])
            ->getMock();

        $mapperMock
            ->expects($this->any())
            ->method('mapItem')
            ->willReturnCallback(array($this, 'mapResult'));

        $this->replaceByMock('singleton', 'ho_import/mapper', $mapperMock);

        /** @var Ambimax_Import_Helper_Import_Product $helper */
        $helper = Mage::helper('ambimax_import/import_product');

        call_user_func_array(array($helper, 'getUrlKeyWithSku'), array($line = array(), $sku = 'invalid')); // @codingStandardsIgnoreLine
    }

    /**
     * @dataProvider dataProvider
     */
    public function testGetUrlKeyWithSku($data, $expected)
    {
        $mapperMock = $this->getMockBuilder('Ho_Import_Model_Mapper')
            ->setMethods(['mapItem'])
            ->getMock();

        $mapperMock
            ->expects($this->any())
            ->method('mapItem')
            ->willReturnCallback(array($this, 'mapResult'));

        $this->replaceByMock('singleton', 'ho_import/mapper', $mapperMock);

        /** @var Ambimax_Import_Helper_Import_Product $helper */
        $helper = Mage::helper('ambimax_import/import_product');

        $this->assertEquals($expected, call_user_func_array(array($helper, 'getUrlKeyWithSku'), $data)); // @codingStandardsIgnoreLine
    }

    /**
     * Input/Output Result for mocks
     *
     * @param $param
     * @return mixed
     */
    public function mapResult($param)
    {
        return $param;
    }
}