text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MicroNetCore.AspNetCore.Paging;
using MicroNetCore.Rest.Abstractions;
using MicroNetCore.Rest.MediaTypes.Hypermedia.Models;
using MicroNetCore.Rest.MediaTypes.Hypermedia.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace MicroNetCore.Rest.MediaTypes.Hypermedia
{
    public sealed class HypermediaSerializer : IHypermediaSerializer
    {
        #region Static

        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore
        };

        #endregion

        private readonly IHypermediaActionsService _actionsGenerator;
        private readonly IHypermediaClassService _classGenerator;
        private readonly IHypermediaLinksService _linksGenerator;
        private readonly IHypermediaPropertiesService _propertiesGenerator;
        private readonly IHypermediaSubEntitiesService _subEntitiesGenerator;
        private readonly IHypermediaTitleGenerator _titleGenerator;

        public HypermediaSerializer(
            IHypermediaActionsService actionsGenerator,
            IHypermediaClassService classGenerator,
            IHypermediaLinksService linksGenerator,
            IHypermediaPropertiesService propertiesGenerator,
            IHypermediaSubEntitiesService subEntitiesGenerator,
            IHypermediaTitleGenerator titleGenerator)
        {
            _actionsGenerator = actionsGenerator;
            _classGenerator = classGenerator;
            _linksGenerator = linksGenerator;
            _propertiesGenerator = propertiesGenerator;
            _subEntitiesGenerator = subEntitiesGenerator;
            _titleGenerator = titleGenerator;
        }

        public string Serialize(object obj, Encoding encoding)
        {
            var entity = CreateEntity(obj);
            return JsonConvert.SerializeObject(entity, Settings);
        }

        #region Helpers

        private Entity CreateEntity(object obj)
        {
            switch (obj)
            {
                case IResponseViewModel model:
                    return CreateEntity(model);
                case IEnumerable<IResponseViewModel> models:
                    return CreateEntity(models);
                case IEnumerablePage<IResponseViewModel> page:
                    return CreateEntity(page);
                default:
                    throw new Exception($"{obj.GetType().Name} can not be converted to a Hypermedia Entity.");
            }
        }

        private Entity CreateEntity(IResponseViewModel model)
        {
            return new Entity
            {
                Actions = _actionsGenerator.Get(model),
                Class = _classGenerator.Get(model),
                Links = _linksGenerator.Get(model),
                Properties = _propertiesGenerator.Get(model),
                Entities = _subEntitiesGenerator.Get(model),
                Title = _titleGenerator.Get(model)
            };
        }

        private Entity CreateEntity(IEnumerable<IResponseViewModel> models)
        {
            var modelsArray = models.ToArray();

            return new Entity
            {
                Actions = _actionsGenerator.Get(modelsArray),
                Class = _classGenerator.Get(modelsArray),
                Links = _linksGenerator.Get(modelsArray),
                Properties = _propertiesGenerator.Get(modelsArray),
                Entities = _subEntitiesGenerator.Get(modelsArray),
                Title = _titleGenerator.Get(modelsArray)
            };
        }

        private Entity CreateEntity(IEnumerablePage<IResponseViewModel> page)
        {
            return new Entity
            {
                Actions = _actionsGenerator.Get(page),
                Class = _classGenerator.Get(page),
                Links = _linksGenerator.Get(page),
                Properties = _propertiesGenerator.Get(page),
                Entities = _subEntitiesGenerator.Get(page),
                Title = _titleGenerator.Get(page)
            };
        }

        #endregion
    }
}


text:
ACCEPTED

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

#### Published in
Ann. Bot. (Usteri) 15: 4 (1795)

#### Original name
Bovista plumbea Pers., 1795

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package com.outbrain.ob1k.server.cors;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.cors.CorsHandler;

/**
 * Custom CorsHandler to suppress IO exceptions.
 *
 * @author Doug Chimento <dchimento@outbrain.com>
 */
public final class CorsWrapperHandler extends CorsHandler {
  private static final Logger logger = LoggerFactory.getLogger(CorsWrapperHandler.class);

  public CorsWrapperHandler(final CorsConfig config) {
    super(convertConfig(config));
  }

  @Override
  public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
    if (cause instanceof IOException) {
      logger.debug("caught IO exception in handler; remote host={}", ctx.channel().remoteAddress(), cause);
    } else {
      logger.warn("caught exception in handler; remote host={}", ctx.channel().remoteAddress(), cause);
    }
    ctx.close();
  }

  private static io.netty.handler.codec.http.cors.CorsConfig convertConfig(final CorsConfig corsConfig) {
    io.netty.handler.codec.http.cors.CorsConfig.Builder nettyBuilder;
    if (corsConfig.origins().isEmpty()) {
      nettyBuilder =  io.netty.handler.codec.http.cors.CorsConfig.withAnyOrigin();
    } else  {
      nettyBuilder = io.netty.handler.codec.http.cors.CorsConfig.withOrigins(corsConfig.origins().toArray(new String[]{}));
    }

    nettyBuilder.allowedRequestHeaders(corsConfig.allowedRequestHeaders().toArray(new String[]{}));
    nettyBuilder.exposeHeaders(corsConfig.exposedHeaders().toArray(new String[]{}));
    nettyBuilder.allowedRequestMethods(convertHeaders(corsConfig.allowedRequestMethods()));
    nettyBuilder.maxAge(corsConfig.maxAge());

    if (corsConfig.isCredentialsAllowed()) {
      nettyBuilder.allowCredentials();
    }
    if (corsConfig.isShortCircuit()) {
      nettyBuilder.shortCurcuit();
    }
    if (!corsConfig.isCorsSupportEnabled()) {
      nettyBuilder.disable();
    }
    if (corsConfig.isNullOriginAllowed()) {
      nettyBuilder.allowNullOrigin();
    }
    if (corsConfig.noPreflightHeaders()) {
      nettyBuilder.noPreflightResponseHeaders();
    }

    return nettyBuilder.build();
  }

  private static HttpMethod[] convertHeaders(final Set<String> sMethods) {
    HttpMethod[] methods = new HttpMethod[sMethods.size()];
    Iterator<String> iterator = sMethods.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      //TODO Handle Invalid Method?
      methods[i++] =  HttpMethod.valueOf(iterator.next());
    }
    return methods;
  }
}


text:
from __future__ import print_function
from time import time
from itertools import permutations

# Project Euler # 43

# only works on 0 to 9 pandigitals:
# (accepts a string or list, not an int)
# reversed sequence and indices for performance boost
seq = [17, 13, 11, 7, 5, 3, 2]
def is_special(n):
    for ind, val in enumerate(seq):
        number = int("".join(n[7 - ind:10 - ind]))
        if number % val != 0:
            return False
    return True

if __name__ == '__main__':
    start = time()
    digits = "0123456789"
    total = 0
    for n in permutations(digits):
        if is_special(n):
            total += int("".join(n))
            print("".join(n))
    print('Total:', total, "and took", time() - start, "seconds.")


text:
package module

import (
	"github.com/cheggaaa/Anteater/storage"
	"net/http"
)

type Module interface {
	OnSave(file *storage.File, w http.ResponseWriter, r *http.Request, s *storage.Storage) (err error)
	OnCommand(command, filename string, w http.ResponseWriter, r *http.Request, s *storage.Storage) (cont bool, err error)
}

var modules = make([]Module, 0)

func RegisterModules() {
	modules = append(modules, unZip{}, fileList{})
}

func OnSave(file *storage.File, w http.ResponseWriter, r *http.Request, s *storage.Storage) (err error) {
	for _, m := range modules {
		err = m.OnSave(file, w, r, s)
		if err != nil {
			break
		}
	}
	return
}

func OnCommand(command, filename string, w http.ResponseWriter, r *http.Request, s *storage.Storage) (cont bool, err error) {
	for _, m := range modules {
		cont, err = m.OnCommand(command, filename, w, r, s)
		if !cont || err != nil {
			break
		}
	}
	return
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using SharpTask.Core.Models.Task;

namespace SharpTask.Core.Models.TaskModule
{
    public class TaskInformation
    {
        /// <summary>
        /// The file based directory
        /// </summary>
        public DirectoryInfo Directory;

        /// <summary>
        /// The classes in the directory that can be ran
        /// </summary>
        public IEnumerable<ISharpTask> RunInstance;

        /// <summary>
        /// MD5 checksum for all files in the directory
        /// </summary>
        public string DirectoryMd5;

        /// <summary>
        /// The name of the directory, with original directory name and the file MD5 checksum
        /// </summary>
        public string DirectoryName
        {
            get
            {
                var name = Directory.Name;
                var idx = name.LastIndexOf("_MD5_", StringComparison.InvariantCulture);
                if (idx > 0) name = name.Substring(0, idx);

                return name +
                       "_MD5_" +
                       DirectoryMd5;
            }
        }
    }
}


text:
.container-fluid, .container{
    max-width: 1168px;
}

thead th{
    background: black !important;
    color: white;
}

.navbar{
    border-radius: 0px;
}

.navbar .container-fluid{
    padding: 0px !important;
}

.navbar-inverse{
    background-color: black !important;
}

.navbar-inverse .navbar-nav>li>a {
    color: white;
}

.navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
    background-color: #222;
    color: #F1B82D;
}

.gold-bar{
    margin: 0;
    border-color: #F1B82D;
}
.grid-view .button-column {
    width: 80px !important;
}

#search_policies{
    background-color: #F1B82D;
    border-radius: 4px 0px 0px 4px;
}

span.label-warning{
    margin-right: 5px;
}

span.label-warning a{
    color: #000000;
}

#footer {
    margin: 10px 0px;
    border-top: 1px solid #F1B82D !important;
}

.items h5{
    font-weight: bold;
}

.button-column a{
    color: black;
}


text:
<?php

namespace Omnipay\NetPay\Message;

/**
 * NetPay API Refund Request
 */
class ApiRefundRequest extends AbstractRequest
{
    public function getOrderId()
    {
        return $this->getParameter('orderId');
    }

    public function setOrderId($value)
    {
        return $this->setParameter('orderId', $value);
    }

    public function getData()
    {
        $this->setApiMethod('gateway/transaction');

        $this->validate('amount', 'currency', 'orderId');

        $data = $this->getBaseData();

        $data['merchant']['operation_type'] = 'REFUND';

        $data['transaction']['transaction_id'] = $this->createUniqueTransactionId($this->getTransactionId());
        $data['transaction']['amount'] = $this->getAmount();
        $data['transaction']['currency'] = $this->getCurrency();
        $data['transaction']['source'] = 'INTERNET';
        $description = trim(substr($this->getDescription(), 0, 100));
        if(strlen($description) === 0) {
            $description = substr("Refund with transaction id ".$this->getTransactionId()." and amount ".$this->getCurrency()." ".$this->getAmount()." has been requested.", 0, 100);
        }
        $data['transaction']['description'] = $description;

        $data['order']['order_id'] = $this->getOrderId();

        return $data;
    }

    protected function createResponse($data)
    {
        return $this->response = new ApiRefundResponse($this, $data);
    }
}


text:
class CreateProblems < ActiveRecord::Migration
  def self.up
    create_table :problems do |t|
      t.string :name
      t.timestamps
    end
  end

  def self.down
    drop_table :problems
  end
end


text:
actions :configure
default_action :configure

#[holland]
attribute :plugin_dirs, :kind_of => String, :default => "/usr/share/holland/plugins"
attribute :backup_directory, :kind_of => String, :default => "/var/spool/holland"
attribute :backupsets, :kind_of => String, :default => "default"
attribute :umask, :kind_of => String, :default => "0007"
attribute :path, :kind_of => String, :default => "/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin"

#[logging]
attribute :filename, :kind_of => String, :default => "/var/log/holland/holland.log"
attribute :level, :kind_of => String, :default => "info"

def initialize(*args)
    super
    @action = :configure
end


text:
using testing::DoAll;
using testing::Invoke;
using testing::Return;
using testing::ReturnRefOfCopy;
using testing::SetArgPointee;
using testing::WithArg;
using testing::_;

namespace {

void CheckInfoEqual(const history::DownloadRow& left,
                    const history::DownloadRow& right) {
  EXPECT_EQ(left.current_path.value(), right.current_path.value());
  EXPECT_EQ(left.target_path.value(), right.target_path.value());
  EXPECT_EQ(left.url_chain.size(), right.url_chain.size());
  for (unsigned int i = 0;
       i < left.url_chain.size() && i < right.url_chain.size();
       ++i) {
    EXPECT_EQ(left.url_chain[i].spec(), right.url_chain[i].spec());
  }
  EXPECT_EQ(left.referrer_url.spec(), right.referrer_url.spec());
  EXPECT_EQ(left.mime_type, right.mime_type);
  EXPECT_EQ(left.original_mime_type, right.original_mime_type);
  EXPECT_EQ(left.start_time.ToTimeT(), right.start_time.ToTimeT());
  EXPECT_EQ(left.end_time.ToTimeT(), right.end_time.ToTimeT());
  EXPECT_EQ(left.etag, right.etag);
  EXPECT_EQ(left.last_modified, right.last_modified);
  EXPECT_EQ(left.received_bytes, right.received_bytes);
  EXPECT_EQ(left.total_bytes, right.total_bytes);
  EXPECT_EQ(left.state, right.state);
  EXPECT_EQ(left.danger_type, right.danger_type);
  EXPECT_EQ(left.id, right.id);
  EXPECT_EQ(left.opened, right.opened);
  EXPECT_EQ(left.by_ext_id, right.by_ext_id);
  EXPECT_EQ(left.by_ext_name, right.by_ext_name);
}

typedef DownloadHistory::IdSet IdSet;
typedef std::vector<history::DownloadRow> InfoVector;
typedef testing::StrictMock<content::MockDownloadItem> StrictMockDownloadItem;

class FakeHistoryAdapter : public DownloadHistory::HistoryAdapter {
 public:
  FakeHistoryAdapter()
    : DownloadHistory::HistoryAdapter(NULL),
      slow_create_download_(false),
      fail_create_download_(false) {
  }

  ~FakeHistoryAdapter() override {}

  void QueryDownloads(
      const HistoryService::DownloadQueryCallback& callback) override {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
        base::Bind(&FakeHistoryAdapter::QueryDownloadsDone,
            base::Unretained(this), callback));
  }

  void QueryDownloadsDone(
      const HistoryService::DownloadQueryCallback& callback) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    CHECK(expect_query_downloads_.get());
    callback.Run(expect_query_downloads_.Pass());
  }

  void set_slow_create_download(bool slow) { slow_create_download_ = slow; }

  void CreateDownload(
      const history::DownloadRow& info,
      const HistoryService::DownloadCreateCallback& callback) override {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    create_download_info_ = info;
    // Must not call CreateDownload() again before FinishCreateDownload()!
    DCHECK(create_download_callback_.is_null());
    create_download_callback_ = base::Bind(callback, !fail_create_download_);
    fail_create_download_ = false;
    if (!slow_create_download_)
      FinishCreateDownload();
  }

  void FinishCreateDownload() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    create_download_callback_.Run();
    create_download_callback_.Reset();
  }

  void UpdateDownload(const history::DownloadRow& info) override {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    update_download_ = info;
  }

  void RemoveDownloads(const IdSet& ids) override {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    for (IdSet::const_iterator it = ids.begin();
         it != ids.end(); ++it) {
      remove_downloads_.insert(*it);
    }
  }

  void ExpectWillQueryDownloads(scoped_ptr<InfoVector> infos) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    expect_query_downloads_ = infos.Pass();
  }

  void ExpectQueryDownloadsDone() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    EXPECT_TRUE(NULL == expect_query_downloads_.get());
  }

  void FailCreateDownload() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    fail_create_download_ = true;
  }

  void ExpectDownloadCreated(
      const history::DownloadRow& info) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    CheckInfoEqual(info, create_download_info_);
    create_download_info_ = history::DownloadRow();
  }

  void ExpectNoDownloadCreated() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    CheckInfoEqual(history::DownloadRow(), create_download_info_);
  }

  void ExpectDownloadUpdated(const history::DownloadRow& info) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    CheckInfoEqual(update_download_, info);
    update_download_ = history::DownloadRow();
  }

  void ExpectNoDownloadUpdated() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    CheckInfoEqual(history::DownloadRow(), update_download_);
  }

  void ExpectNoDownloadsRemoved() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    EXPECT_EQ(0, static_cast<int>(remove_downloads_.size()));
  }

  void ExpectDownloadsRemoved(const IdSet& ids) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    IdSet differences = base::STLSetDifference<IdSet>(ids, remove_downloads_);
    for (IdSet::const_iterator different = differences.begin();
         different != differences.end(); ++different) {
      EXPECT_TRUE(false) << *different;
    }
    remove_downloads_.clear();
  }

 private:
  bool slow_create_download_;
  bool fail_create_download_;
  base::Closure create_download_callback_;
  history::DownloadRow update_download_;
  scoped_ptr<InfoVector> expect_query_downloads_;
  IdSet remove_downloads_;
  history::DownloadRow create_download_info_;

  DISALLOW_COPY_AND_ASSIGN(FakeHistoryAdapter);
};

class DownloadHistoryTest : public testing::Test {
 public:
  // Generic callback that receives a pointer to a StrictMockDownloadItem.
  typedef base::Callback<void(content::MockDownloadItem*)> DownloadItemCallback;

  DownloadHistoryTest()
      : ui_thread_(content::BrowserThread::UI, &loop_),
        manager_(new content::MockDownloadManager()),
        history_(NULL),
        manager_observer_(NULL),
        download_created_index_(0) {}
  ~DownloadHistoryTest() override { STLDeleteElements(&items_); }

 protected:
  void TearDown() override { download_history_.reset(); }

  content::MockDownloadManager& manager() { return *manager_.get(); }
  content::MockDownloadItem& item(size_t index) { return *items_[index]; }
  DownloadHistory* download_history() { return download_history_.get(); }

  void SetManagerObserver(
      content::DownloadManager::Observer* manager_observer) {
    manager_observer_ = manager_observer;
  }
  content::DownloadManager::Observer* manager_observer() {
    return manager_observer_;
  }

  void CreateDownloadHistory(scoped_ptr<InfoVector> infos) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    CHECK(infos.get());
    EXPECT_CALL(manager(), AddObserver(_)).WillOnce(WithArg<0>(Invoke(
        this, &DownloadHistoryTest::SetManagerObserver)));
    EXPECT_CALL(manager(), RemoveObserver(_));
    download_created_index_ = 0;
    for (size_t index = 0; index < infos->size(); ++index) {
      const history::DownloadRow& row = infos->at(index);
      content::MockDownloadManager::CreateDownloadItemAdapter adapter(
          history::ToContentDownloadId(row.id),
          row.current_path,
          row.target_path,
          row.url_chain,
          row.referrer_url,
          row.mime_type,
          row.original_mime_type,
          row.start_time,
          row.end_time,
          row.etag,
          row.last_modified,
          row.received_bytes,
          row.total_bytes,
          history::ToContentDownloadState(row.state),
          history::ToContentDownloadDangerType(row.danger_type),
          history::ToContentDownloadInterruptReason(row.interrupt_reason),
          row.opened);
      EXPECT_CALL(manager(), MockCreateDownloadItem(adapter))
        .WillOnce(DoAll(
            InvokeWithoutArgs(
                this, &DownloadHistoryTest::CallOnDownloadCreatedInOrder),
            Return(&item(index))));
    }
    EXPECT_CALL(manager(), CheckForHistoryFilesRemoval());
    history_ = new FakeHistoryAdapter();
    history_->ExpectWillQueryDownloads(infos.Pass());
    EXPECT_CALL(*manager_.get(), GetAllDownloads(_)).WillRepeatedly(Return());
    download_history_.reset(new DownloadHistory(
        &manager(), scoped_ptr<DownloadHistory::HistoryAdapter>(history_)));
    content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
    history_->ExpectQueryDownloadsDone();
  }

  void CallOnDownloadCreated(size_t index) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    if (!pre_on_create_handler_.is_null())
      pre_on_create_handler_.Run(&item(index));
    manager_observer()->OnDownloadCreated(&manager(), &item(index));
    if (!post_on_create_handler_.is_null())
      post_on_create_handler_.Run(&item(index));
  }

  void CallOnDownloadCreatedInOrder() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    // Gmock doesn't appear to support something like InvokeWithTheseArgs. Maybe
    // gmock needs to learn about base::Callback.
    CallOnDownloadCreated(download_created_index_++);
  }

  void set_slow_create_download(bool slow) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->set_slow_create_download(slow);
  }

  void FinishCreateDownload() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->FinishCreateDownload();
  }

  void FailCreateDownload() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->FailCreateDownload();
  }

  void ExpectDownloadCreated(
      const history::DownloadRow& info) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectDownloadCreated(info);
  }

  void ExpectNoDownloadCreated() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectNoDownloadCreated();
  }

  void ExpectDownloadUpdated(const history::DownloadRow& info) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectDownloadUpdated(info);
  }

  void ExpectNoDownloadUpdated() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectNoDownloadUpdated();
  }

  void ExpectNoDownloadsRemoved() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectNoDownloadsRemoved();
  }

  void ExpectDownloadsRemoved(const IdSet& ids) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    history_->ExpectDownloadsRemoved(ids);
  }

  void ExpectDownloadsRestoredFromHistory(bool expected_value) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
    pre_on_create_handler_ =
        base::Bind(&DownloadHistoryTest::CheckDownloadWasRestoredFromHistory,
                   base::Unretained(this),
                   expected_value);
    post_on_create_handler_ =
        base::Bind(&DownloadHistoryTest::CheckDownloadWasRestoredFromHistory,
                   base::Unretained(this),
                   expected_value);
  }

  void InitBasicItem(const base::FilePath::CharType* path,
                     const char* url_string,
                     const char* referrer_string,
                     history::DownloadRow* info) {
    GURL url(url_string);
    GURL referrer(referrer_string);
    std::vector<GURL> url_chain;
    url_chain.push_back(url);
    InitItem(static_cast<uint32>(items_.size() + 1),
             base::FilePath(path),
             base::FilePath(path),
             url_chain,
             referrer,
             "application/octet-stream",
             "application/octet-stream",
             (base::Time::Now() - base::TimeDelta::FromMinutes(10)),
             (base::Time::Now() - base::TimeDelta::FromMinutes(1)),
             "Etag",
             "abc",
             100,
             100,
             content::DownloadItem::COMPLETE,
             content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
             content::DOWNLOAD_INTERRUPT_REASON_NONE,
             false,
             std::string(),
             std::string(),
             info);
  }

  void InitItem(
      uint32 id,
      const base::FilePath& current_path,
      const base::FilePath& target_path,
      const std::vector<GURL>& url_chain,
      const GURL& referrer,
      const std::string& mime_type,
      const std::string& original_mime_type,
      const base::Time& start_time,
      const base::Time& end_time,
      const std::string& etag,
      const std::string& last_modified,
      int64 received_bytes,
      int64 total_bytes,
      content::DownloadItem::DownloadState state,
      content::DownloadDangerType danger_type,
      content::DownloadInterruptReason interrupt_reason,
      bool opened,
      const std::string& by_extension_id,
      const std::string& by_extension_name,
      history::DownloadRow* info) {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

    size_t index = items_.size();
    StrictMockDownloadItem* mock_item = new StrictMockDownloadItem();
    items_.push_back(mock_item);

    info->current_path = current_path;
    info->target_path = target_path;
    info->url_chain = url_chain;
    info->referrer_url = referrer;
    info->mime_type = mime_type;
    info->original_mime_type = original_mime_type;
    info->start_time = start_time;
    info->end_time = end_time;
    info->etag = etag;
    info->last_modified = last_modified;
    info->received_bytes = received_bytes;
    info->total_bytes = total_bytes;
    info->state = history::ToHistoryDownloadState(state);
    info->danger_type = history::ToHistoryDownloadDangerType(danger_type);
    info->interrupt_reason =
        history::ToHistoryDownloadInterruptReason(interrupt_reason);
    info->id = history::ToHistoryDownloadId(id);
    info->opened = opened;
    info->by_ext_id = by_extension_id;
    info->by_ext_name = by_extension_name;

    EXPECT_CALL(item(index), GetId()).WillRepeatedly(Return(id));
    EXPECT_CALL(item(index), GetFullPath())
        .WillRepeatedly(ReturnRefOfCopy(current_path));
    EXPECT_CALL(item(index), GetTargetFilePath())
        .WillRepeatedly(ReturnRefOfCopy(target_path));
    DCHECK_LE(1u, url_chain.size());
    EXPECT_CALL(item(index), GetURL())
        .WillRepeatedly(ReturnRefOfCopy(url_chain[0]));
    EXPECT_CALL(item(index), GetUrlChain())
        .WillRepeatedly(ReturnRefOfCopy(url_chain));
    EXPECT_CALL(item(index), GetMimeType()).WillRepeatedly(Return(mime_type));
    EXPECT_CALL(item(index), GetOriginalMimeType()).WillRepeatedly(Return(
        original_mime_type));
    EXPECT_CALL(item(index), GetReferrerUrl())
        .WillRepeatedly(ReturnRefOfCopy(referrer));
    EXPECT_CALL(item(index), GetStartTime()).WillRepeatedly(Return(start_time));
    EXPECT_CALL(item(index), GetEndTime()).WillRepeatedly(Return(end_time));
    EXPECT_CALL(item(index), GetETag()).WillRepeatedly(ReturnRefOfCopy(etag));
    EXPECT_CALL(item(index), GetLastModifiedTime())
        .WillRepeatedly(ReturnRefOfCopy(last_modified));
    EXPECT_CALL(item(index), GetReceivedBytes())
        .WillRepeatedly(Return(received_bytes));
    EXPECT_CALL(item(index), GetTotalBytes())
        .WillRepeatedly(Return(total_bytes));
    EXPECT_CALL(item(index), GetState()).WillRepeatedly(Return(state));
    EXPECT_CALL(item(index), GetDangerType())
        .WillRepeatedly(Return(danger_type));
    EXPECT_CALL(item(index), GetLastReason())
        .WillRepeatedly(Return(interrupt_reason));
    EXPECT_CALL(item(index), GetOpened()).WillRepeatedly(Return(opened));
    EXPECT_CALL(item(index), GetTargetDisposition())
        .WillRepeatedly(
            Return(content::DownloadItem::TARGET_DISPOSITION_OVERWRITE));
    EXPECT_CALL(manager(), GetDownload(id))
        .WillRepeatedly(Return(&item(index)));
    EXPECT_CALL(item(index), IsTemporary()).WillRepeatedly(Return(false));
#if defined(ENABLE_EXTENSIONS)
    new extensions::DownloadedByExtension(
        &item(index), by_extension_id, by_extension_name);
#endif

    std::vector<content::DownloadItem*> items;
    for (size_t i = 0; i < items_.size(); ++i) {
      items.push_back(&item(i));
    }
    EXPECT_CALL(*manager_.get(), GetAllDownloads(_))
        .WillRepeatedly(SetArgPointee<0>(items));
  }

 private:
  void CheckDownloadWasRestoredFromHistory(bool expected_value,
                                           content::MockDownloadItem* item) {
    ASSERT_TRUE(download_history_.get());
    EXPECT_EQ(expected_value, download_history_->WasRestoredFromHistory(item));
  }

  base::MessageLoopForUI loop_;
  content::TestBrowserThread ui_thread_;
  std::vector<StrictMockDownloadItem*> items_;
  scoped_ptr<content::MockDownloadManager> manager_;
  FakeHistoryAdapter* history_;
  scoped_ptr<DownloadHistory> download_history_;
  content::DownloadManager::Observer* manager_observer_;
  size_t download_created_index_;
  DownloadItemCallback pre_on_create_handler_;
  DownloadItemCallback post_on_create_handler_;

  DISALLOW_COPY_AND_ASSIGN(DownloadHistoryTest);
};

// Test loading an item from the database, changing it, saving it back, removing
// it.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_Load) {
  // Load a download from history, create the item, OnDownloadCreated,
  // OnDownloadUpdated, OnDownloadRemoved.
  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);
  {
    scoped_ptr<InfoVector> infos(new InfoVector());
    infos->push_back(info);
    CreateDownloadHistory(infos.Pass());
    ExpectNoDownloadCreated();
  }
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  // Pretend that something changed on the item.
  EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true));
  item(0).NotifyObserversDownloadUpdated();
  info.opened = true;
  ExpectDownloadUpdated(info);

  // Pretend that the user removed the item.
  IdSet ids;
  ids.insert(info.id);
  item(0).NotifyObserversDownloadRemoved();
  ExpectDownloadsRemoved(ids);
}

// Test that WasRestoredFromHistory accurately identifies downloads that were
// created from history, even during an OnDownloadCreated() handler.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_WasRestoredFromHistory_True) {
  // This sets DownloadHistoryTest to call DH::WasRestoredFromHistory() both
  // before and after DH::OnDownloadCreated() is called. At each call, the
  // expected return value is |true| since the download was restored from
  // history.
  ExpectDownloadsRestoredFromHistory(true);

  // Construct a DownloadHistory with a single history download. This results in
  // DownloadManager::CreateDownload() being called for the restored download.
  // The above test expectation should verify that the value of
  // WasRestoredFromHistory is correct for this download.
  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);
  scoped_ptr<InfoVector> infos(new InfoVector());
  infos->push_back(info);
  CreateDownloadHistory(infos.Pass());

  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));
}

// Test that WasRestoredFromHistory accurately identifies downloads that were
// not created from history.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_WasRestoredFromHistory_False) {
  // This sets DownloadHistoryTest to call DH::WasRestoredFromHistory() both
  // before and after DH::OnDownloadCreated() is called. At each call, the
  // expected return value is |true| since the download was restored from
  // history.
  ExpectDownloadsRestoredFromHistory(false);

  // Create a DownloadHistory with no history downloads. No
  // DownloadManager::CreateDownload() calls are expected.
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  // Notify DownloadHistory that a new download was created. The above test
  // expecation should verify that WasRestoredFromHistory is correct for this
  // download.
  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
}

// Test creating an item, saving it to the database, changing it, saving it
// back, removing it.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_Create) {
  // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated,
  // OnDownloadRemoved.
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);

  // Pretend the manager just created |item|.
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  // Pretend that something changed on the item.
  EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true));
  item(0).NotifyObserversDownloadUpdated();
  info.opened = true;
  ExpectDownloadUpdated(info);

  // Pretend that the user removed the item.
  IdSet ids;
  ids.insert(info.id);
  item(0).NotifyObserversDownloadRemoved();
  ExpectDownloadsRemoved(ids);
}

// Test that changes to persisted fields in a DownloadItem triggers database
// updates.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_Update) {
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  base::FilePath new_path(FILE_PATH_LITERAL("/foo/baz.txt"));
  base::Time new_time(base::Time::Now());
  std::string new_etag("new etag");
  std::string new_last_modifed("new last modified");

  // current_path
  EXPECT_CALL(item(0), GetFullPath()).WillRepeatedly(ReturnRefOfCopy(new_path));
  info.current_path = new_path;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // target_path
  EXPECT_CALL(item(0), GetTargetFilePath())
      .WillRepeatedly(ReturnRefOfCopy(new_path));
  info.target_path = new_path;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // end_time
  EXPECT_CALL(item(0), GetEndTime()).WillRepeatedly(Return(new_time));
  info.end_time = new_time;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // received_bytes
  EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(101));
  info.received_bytes = 101;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // total_bytes
  EXPECT_CALL(item(0), GetTotalBytes()).WillRepeatedly(Return(102));
  info.total_bytes = 102;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // etag
  EXPECT_CALL(item(0), GetETag()).WillRepeatedly(ReturnRefOfCopy(new_etag));
  info.etag = new_etag;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // last_modified
  EXPECT_CALL(item(0), GetLastModifiedTime())
      .WillRepeatedly(ReturnRefOfCopy(new_last_modifed));
  info.last_modified = new_last_modifed;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // state
  EXPECT_CALL(item(0), GetState())
      .WillRepeatedly(Return(content::DownloadItem::INTERRUPTED));
  info.state = history::DownloadState::INTERRUPTED;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // danger_type
  EXPECT_CALL(item(0), GetDangerType())
      .WillRepeatedly(Return(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT));
  info.danger_type = history::DownloadDangerType::DANGEROUS_CONTENT;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // interrupt_reason
  EXPECT_CALL(item(0), GetLastReason())
      .WillRepeatedly(Return(content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED));
  info.interrupt_reason = history::ToHistoryDownloadInterruptReason(
      content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED);
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);

  // opened
  EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true));
  info.opened = true;
  item(0).NotifyObserversDownloadUpdated();
  ExpectDownloadUpdated(info);
}

// Test creating a new item, saving it, removing it by setting it Temporary,
// changing it without saving it back because it's Temporary, clearing
// IsTemporary, saving it back, changing it, saving it back because it isn't
// Temporary anymore.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_Temporary) {
  // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated,
  // OnDownloadRemoved.
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);

  // Pretend the manager just created |item|.
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  // Pretend the item was marked temporary. DownloadHistory should remove it
  // from history and start ignoring it.
  EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(true));
  item(0).NotifyObserversDownloadUpdated();
  IdSet ids;
  ids.insert(info.id);
  ExpectDownloadsRemoved(ids);

  // Change something that would make DownloadHistory call UpdateDownload if the
  // item weren't temporary.
  EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(4200));
  item(0).NotifyObserversDownloadUpdated();
  ExpectNoDownloadUpdated();

  // Changing a temporary item back to a non-temporary item should make
  // DownloadHistory call CreateDownload.
  EXPECT_CALL(item(0), IsTemporary()).WillRepeatedly(Return(false));
  item(0).NotifyObserversDownloadUpdated();
  info.received_bytes = 4200;
  ExpectDownloadCreated(info);
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100));
  item(0).NotifyObserversDownloadUpdated();
  info.received_bytes = 100;
  ExpectDownloadUpdated(info);
}

// Test removing downloads while they're still being added.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_RemoveWhileAdding) {
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);

  // Instruct CreateDownload() to not callback to DownloadHistory immediately,
  // but to wait for FinishCreateDownload().
  set_slow_create_download(true);

  // Pretend the manager just created |item|.
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0)));

  // Call OnDownloadRemoved before calling back to DownloadHistory::ItemAdded().
  // Instead of calling RemoveDownloads() immediately, DownloadHistory should
  // add the item's id to removed_while_adding_. Then, ItemAdded should
  // immediately remove the item's record from history.
  item(0).NotifyObserversDownloadRemoved();
  EXPECT_CALL(manager(), GetDownload(item(0).GetId()))
    .WillRepeatedly(Return(static_cast<content::DownloadItem*>(NULL)));
  ExpectNoDownloadsRemoved();
  EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0)));

  // Now callback to DownloadHistory::ItemAdded(), and expect a call to
  // RemoveDownloads() for the item that was removed while it was being added.
  FinishCreateDownload();
  IdSet ids;
  ids.insert(info.id);
  ExpectDownloadsRemoved(ids);
  EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0)));
}

// Test loading multiple items from the database and removing them all.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_Multiple) {
  // Load a download from history, create the item, OnDownloadCreated,
  // OnDownloadUpdated, OnDownloadRemoved.
  history::DownloadRow info0, info1;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info0);
  InitBasicItem(FILE_PATH_LITERAL("/foo/qux.pdf"),
                "http://example.com/qux.pdf",
                "http://example.com/referrer1.html",
                &info1);
  {
    scoped_ptr<InfoVector> infos(new InfoVector());
    infos->push_back(info0);
    infos->push_back(info1);
    CreateDownloadHistory(infos.Pass());
    ExpectNoDownloadCreated();
  }

  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(1)));

  // Pretend that the user removed both items.
  IdSet ids;
  ids.insert(info0.id);
  ids.insert(info1.id);
  item(0).NotifyObserversDownloadRemoved();
  item(1).NotifyObserversDownloadRemoved();
  ExpectDownloadsRemoved(ids);
}

// Test what happens when HistoryService/CreateDownload::CreateDownload() fails.
TEST_F(DownloadHistoryTest, DownloadHistoryTest_CreateFailed) {
  // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated,
  // OnDownloadRemoved.
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);

  FailCreateDownload();
  // Pretend the manager just created |item|.
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0)));

  EXPECT_CALL(item(0), GetReceivedBytes()).WillRepeatedly(Return(100));
  item(0).NotifyObserversDownloadUpdated();
  info.received_bytes = 100;
  ExpectDownloadCreated(info);
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));
}

TEST_F(DownloadHistoryTest, DownloadHistoryTest_UpdateWhileAdding) {
  // Create a fresh item not from history, OnDownloadCreated, OnDownloadUpdated,
  // OnDownloadRemoved.
  CreateDownloadHistory(scoped_ptr<InfoVector>(new InfoVector()));

  history::DownloadRow info;
  InitBasicItem(FILE_PATH_LITERAL("/foo/bar.pdf"),
                "http://example.com/bar.pdf",
                "http://example.com/referrer.html",
                &info);

  // Instruct CreateDownload() to not callback to DownloadHistory immediately,
  // but to wait for FinishCreateDownload().
  set_slow_create_download(true);

  // Pretend the manager just created |item|.
  CallOnDownloadCreated(0);
  ExpectDownloadCreated(info);
  EXPECT_FALSE(DownloadHistory::IsPersisted(&item(0)));

  // Pretend that something changed on the item.
  EXPECT_CALL(item(0), GetOpened()).WillRepeatedly(Return(true));
  item(0).NotifyObserversDownloadUpdated();

  FinishCreateDownload();
  EXPECT_TRUE(DownloadHistory::IsPersisted(&item(0)));

  // ItemAdded should call OnDownloadUpdated, which should detect that the item
  // changed while it was being added and call UpdateDownload immediately.
  info.opened = true;
  ExpectDownloadUpdated(info);
}

}  // anonymous namespace


text:
var Table = require('./table.js');
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var hyperglue = require('hyperglue');

module.exports = Profiles;
inherits(Profiles, EventEmitter);

function Profiles (elem) {
    if (!(this instanceof Profiles)) return new Profiles(elem);
    EventEmitter.call(this);

    this.table = new Table(elem);
    this.template = this.table.element.querySelector('*[template=profile]');
}

Profiles.prototype.add = function (pair) {
    var self = this;
    var tr = hyperglue(self.template.cloneNode(true), {
        '.name': pair.name,
        '.hash': pair.hash
    });
    tr.style.display = 'table-row';
    tr.querySelector('button.remove').addEventListener('click', remove);

    this.table.add(pair.name, tr);
    return tr;

    function remove () {
        if (!confirm(
            'Removing a keypair could lock you out of access to services'
            + " you've previously authenticated with.\n"
            + "Click OK if you're really sure you want to remove this keypair."
        )) return; // for now

        self.emit('remove', pair);
    }
};

Profiles.prototype.remove = function (pair) {
    this.table.remove(pair.name);
};


text:
package com.company.PizzaTime;

import com.sun.org.apache.bcel.internal.classfile.ClassFormatException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String[] inputTokens = reader.readLine().split("\\s+");
        Pizza pizza = new Pizza();
        pizza.pizzaMethod(inputTokens);

        Class<?> pizzaClass = Pizza.class;
        Method[] methods = pizzaClass.getDeclaredMethods();
        List<Method> checkedMethods = Arrays.stream(methods)
                .filter(m -> m.getReturnType().getName().contains("Map"))
                .collect(Collectors.toList());

        if (checkedMethods.size() < 1) {
            throw new ClassFormatException();
        }

    }
}


text:
__all__ = ['resolvepy']

from .py import resolvepy


text:
<title> Pewter and Casting</title>

 WRA Digital Fab 2017

Week 9 | Casting and Molds

Assignments

Assignment Part 1- Molding From A Negative

1. Design an 3D ORIGINAL .stl file to use in the MDX40A.

2. Mill the part using subtractive manufacturing using the MDX40A. You will mill in wax.

3. Create a mold using Smooth-Sil 960.

4. Cast a chocolate part.

Assignment Part 2- Pewter Pendant

1. Design an 2D ORIGINAL .stl file to use in the MDX40A. Include a sprue and vents for your pour.

2. Mill the part using subtractive manufacturing using the MDX40A. It must be smaller than 2" by 2".

3. Cast the part you milled in pewter to make a pendant.

OR

1. Use the laser to create a mold for your pewter pendant. You will include a sprue and vents for your pour.

2. Use CorelDraw to engrave a 3" by 3" piece of MDF. You can see examples, One and Two

OR

1. You can use the MoldMax 60 from Smooth-On to create your mold. This will be done on Sunday, March 5th.

You will have to create your positive and then we will make the negative using Smooth-On MoldMax 60

These projects were spread out over the course of several weeks so there are some slight alterations. These next two steps were the final steps of the casting projects.

1. Finish your pewter mold. Recut your center mold using 1/8 MDF.

2. Document your pewter mold on your class page with at least one pictures and all your original files.

Chocolate Mold

Using Fusion 360 I designed a basic arrowhead design that would then be carved out in the CNC Milling machine. It turned out mostly clean, but there was some fray along the outer edge.
Nothing that was detrimental to the structure of the mold. I finished the chocolate mold by pouring a silicon based resin that drys into what I then used for my choclate mold.

Casting Tin and Pewter

 Here we used the laser cutter and or the CNC milling machines to create a mold that could withstand the several hundred degree temp. of molten metal.

Above is a picture of the casting tools, pewter and tin.

After the molds are made, powdered( to prevent sticking), and pressed together we poured in the metal and let them cool/ harden.

	Before casting and after the molds had cooled off and I opened it for the first time.

FILES

Arrowhead File

Back of the emblem

Front of the emblem

	Sprue

Back to index


text:
module Concurrent
  module Concern

    # Object references in Ruby are mutable. This can lead to serious problems when
    # the `#value` of a concurrent object is a mutable reference. Which is always the
    # case unless the value is a `Fixnum`, `Symbol`, or similar "primitive" data type.
    # Most classes in this library that expose a `#value` getter method do so using the
    # `Dereferenceable` mixin module.
    #
    # @!macro copy_options
    module Dereferenceable
      # NOTE: This module is going away in 2.0. In the mean time we need it to
      # play nicely with the synchronization layer. This means that the
      # including class SHOULD be synchronized and it MUST implement a
      # `#synchronize` method. Not doing so will lead to runtime errors.

      # Return the value this object represents after applying the options specified
      # by the `#set_deref_options` method.
      #
      # @return [Object] the current value of the object
      def value
        synchronize { apply_deref_options(@value) }
      end
      alias_method :deref, :value

      protected

      # Set the internal value of this object
      #
      # @param [Object] value the new value
      def value=(value)
        synchronize{ @value = value }
      end

      # @!macro dereferenceable_set_deref_options
      #   Set the options which define the operations #value performs before
      #   returning data to the caller (dereferencing).
      #
      #   @note Most classes that include this module will call `#set_deref_options`
      #     from within the constructor, thus allowing these options to be set at
      #     object creation.
      #
      #   @param [Hash] opts the options defining dereference behavior.
      #   @option opts [String] :dup_on_deref (false) call `#dup` before returning the data
      #   @option opts [String] :freeze_on_deref (false) call `#freeze` before returning the data
      #   @option opts [String] :copy_on_deref (nil) call the given `Proc` passing
      #     the internal value and returning the value returned from the proc
      def set_deref_options(opts = {})
        synchronize{ ns_set_deref_options(opts) }
      end

      # @!macro dereferenceable_set_deref_options
      # @!visibility private
      def ns_set_deref_options(opts)
        @dup_on_deref = opts[:dup_on_deref] || opts[:dup]
        @freeze_on_deref = opts[:freeze_on_deref] || opts[:freeze]
        @copy_on_deref = opts[:copy_on_deref] || opts[:copy]
        @do_nothing_on_deref = !(@dup_on_deref || @freeze_on_deref || @copy_on_deref)
        nil
      end

      # @!visibility private
      def apply_deref_options(value)
        return nil if value.nil?
        return value if @do_nothing_on_deref
        value = @copy_on_deref.call(value) if @copy_on_deref
        value = value.dup if @dup_on_deref
        value = value.freeze if @freeze_on_deref
        value
      end
    end
  end
end


text:
package com.urswolfer.gerrit.client.rest.http.changes;

import com.google.common.truth.Truth;
import com.google.gerrit.extensions.api.changes.DraftInput;
import com.google.gerrit.extensions.common.CommentInfo;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.urswolfer.gerrit.client.rest.http.GerritRestClient;
import com.urswolfer.gerrit.client.rest.http.common.AbstractParserTest;
import com.urswolfer.gerrit.client.rest.http.common.GerritRestClientBuilder;
import org.easymock.EasyMock;
import org.testng.annotations.Test;

/**
 * @author Urs Wolfer
 */
public class DraftsApiRestClientTest extends AbstractParserTest {
    private CommentsParser commentsParser = new CommentsParser(getGson());

    @Test
    public void testGettingDraftById() throws Exception {
        String draftId = "89233d9c_56013406";
        String revisionId = "ec047590bc7fb8db7ae03ebac336488bfc1c5e12";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", draftId);
        GerritRestClient gerritRestClient = new GerritRestClientBuilder()
            .expectGet("/changes/myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940/revisions/"
                + revisionId + "/drafts/" + draftId, jsonObject)
            .get();

        ChangeApiRestClient changeApiRestClient = new ChangeApiRestClient(gerritRestClient, null, null, commentsParser, null, null, null, null, null,
            "myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940");
        RevisionApiRestClient revisionApiRestClient = new RevisionApiRestClient(gerritRestClient, changeApiRestClient, commentsParser, null, null, revisionId);

        CommentInfo commentInfo = revisionApiRestClient.draft(draftId).get();

        Truth.assertThat(commentInfo.id).isEqualTo(draftId);
        EasyMock.verify(gerritRestClient);
    }

    @Test
    public void testGettingDraftByCommentInfo() throws Exception {
        String draftId = "89233d9c_56013406";
        String revisionId = "ec047590bc7fb8db7ae03ebac336488bfc1c5e12";
        GerritRestClient gerritRestClient = new GerritRestClientBuilder().get();

        CommentInfo expectedCommentInfo = new CommentInfo();
        expectedCommentInfo.id = draftId;

        ChangeApiRestClient changeApiRestClient = new ChangeApiRestClient(gerritRestClient, null, null, null, null, null, null, null, null,
            "myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940");
        RevisionApiRestClient revisionApiRestClient = new RevisionApiRestClient(gerritRestClient, changeApiRestClient, null, null, null, revisionId);
        DraftApiRestClient draftApiRestClient = new DraftApiRestClient(gerritRestClient, changeApiRestClient,
            revisionApiRestClient, null, expectedCommentInfo);

        CommentInfo commentInfo = draftApiRestClient.get();

        Truth.assertThat(commentInfo).isSameAs(expectedCommentInfo);
        EasyMock.verify(gerritRestClient);
    }

    @Test
    public void testUpdateDraft() throws Exception {
        String draftId = "89233d9c_56013406";
        String revisionId = "ec047590bc7fb8db7ae03ebac336488bfc1c5e12";
        JsonElement jsonElement = EasyMock.createMock(JsonElement.class);
        GerritRestClient gerritRestClient = new GerritRestClientBuilder()
            .expectPut("/changes/myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940/" +
                "revisions/" + revisionId + "/drafts/" + draftId, "{}", jsonElement)
            .expectGetGson()
            .get();

        ChangeApiRestClient changeApiRestClient = new ChangeApiRestClient(gerritRestClient, null, null, null, null, null, null, null, null,
            "myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940");
        RevisionApiRestClient revisionApiRestClient = new RevisionApiRestClient(gerritRestClient, changeApiRestClient, null, null, null, revisionId);
        DraftApiRestClient draftApiRestClient = new DraftApiRestClient(gerritRestClient, changeApiRestClient,
            revisionApiRestClient, commentsParser, "89233d9c_56013406");

        draftApiRestClient.update(new DraftInput());

        EasyMock.verify(gerritRestClient);
    }

    @Test
    public void testDeleteDraft() throws Exception {
        String draftId = "89233d9c_56013406";
        String revisionId = "ec047590bc7fb8db7ae03ebac336488bfc1c5e12";
        GerritRestClient gerritRestClient = new GerritRestClientBuilder()
            .expectDelete("/changes/myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940/" +
                "revisions/" + revisionId + "/drafts/" + draftId)
            .get();

        ChangeApiRestClient changeApiRestClient = new ChangeApiRestClient(gerritRestClient, null, null, null, null, null, null, null, null,
            "myProject~master~I8473b95934b5732ac55d26311a706c9c2bde9940");
        RevisionApiRestClient revisionApiRestClient = new RevisionApiRestClient(gerritRestClient, changeApiRestClient, null, null, null, revisionId);
        DraftApiRestClient draftApiRestClient = new DraftApiRestClient(gerritRestClient, changeApiRestClient,
            revisionApiRestClient, null, "89233d9c_56013406");

        draftApiRestClient.delete();

        EasyMock.verify(gerritRestClient);
    }
}


text:
package org.aries.jms.xa;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aries.jms.JMSTestContext;
import org.aries.jms.config.JmsConnectionDescripter;
import org.aries.jms.config.JmsSessionDescripter;

public class JmsXATestContext extends JMSTestContext {

	protected Log log = LogFactory.getLog(getClass());

	protected JmsConnectionDescripter connectionDescripter;

	protected JmsXAConnectionAdapter xaConnectionAdapter;

	protected JmsXAConnectionAdapter xaConnectionAdapter2;

	protected JmsSessionDescripter sessionDescripter;

	protected JmsXASessionAdapter xaSessionAdapter;

	protected JmsXASessionAdapter xaSessionAdapter2;

	public JmsXATestContext() {
		//nothing for now
	}

    public void setUp() throws Exception {
        super.setUp();
    }

	public void tearDown() throws Exception {
        super.tearDown();
    }

	public JmsXAConnectionAdapter getXAConnectionAdapter() {
		return xaConnectionAdapter;
	}

	public JmsXAConnectionAdapter getXAConnectionAdapter2() {
		return xaConnectionAdapter2;
	}

	public JmsXASessionAdapter getXASessionAdapter() {
		return xaSessionAdapter;
	}

	public JmsXASessionAdapter getXASessionAdapter2() {
		return xaSessionAdapter2;
	}

    protected void createConnectionSpecification() {
    	JmsConnectionDescripter specification = JmsXATestFixture.createConnectionDescripter("xaClientId");
		setConnectionDescripter(specification);
    }

    protected void createSessionSpecification() {
    	setSessionDescripter(JmsXATestFixture.createSessionDescripter(connectionDescripter));
    }

	protected void createConnectionAdapters() throws Exception {
		xaConnectionAdapter = JmsXATestFixture.createXAConnectionAdapter("xaClientId");
		xaConnectionAdapter2 = JmsXATestFixture.createXAConnectionAdapter("xaClientId2");
		setConnectionAdapter(xaConnectionAdapter);
		setConnectionAdapter2(xaConnectionAdapter2);
	}

    protected void createSessionAdapters() throws Exception {
    	xaSessionAdapter = JmsXATestFixture.createXASessionAdapter(xaConnectionAdapter);
    	xaSessionAdapter2 = JmsXATestFixture.createXASessionAdapter(xaConnectionAdapter2);
		setSessionAdapter(xaSessionAdapter);
		setSessionAdapter2(xaSessionAdapter2);
	}

}


text:
```plpgsql
CREATE OR REPLACE FUNCTION inventory.get_store_id_by_store_code(_store_code text)
RETURNS integer
```
* Schema : [inventory](../../schemas/inventory.md)
* Function Name : get_store_id_by_store_code
* Arguments : _store_code text
* Owner : frapid_db_user
* Result Type : integer
* Description :

**Source:**
```sql
CREATE OR REPLACE FUNCTION inventory.get_store_id_by_store_code(_store_code text)
 RETURNS integer
 LANGUAGE plpgsql
 STABLE
AS $function$
BEGIN
    RETURN
    (
        SELECT inventory.stores.store_id
        FROM inventory.stores
        WHERE inventory.stores.store_code=_store_code
        AND NOT inventory.stores.deleted
    );
END
$function$

```

### Related Contents
* [Schema List](../../schemas.md)
* [Function List](../../functions.md)
* [Trigger List](../../triggers.md)
* [Table of Contents](../../README.md)


text:
<!DOCTYPE html>

  <title>babble in the browser</title>


text:
package br.com.rogrs.batch;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import br.com.rogrs.model.CommandOutput;

@Service
public class RunShellCommand {

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

	public CommandOutput execute(String command) {
		CommandOutput output = new CommandOutput();
		log.info(String.format("Executando o comando %s",command));
		StringBuilder sb = new StringBuilder();

		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			log.info("output:", p.exitValue());
			BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

			String line = "";
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			output.setMsgOutput(sb.toString());
			output.setCode(p.exitValue());

		} catch (Exception e) {
			output.setMsgError(e.getMessage());
			log.error("Erro na execução do comando  " + command, e);
		}

		return output;

	}
}


text:
package org.openspaces.admin.internal.alert.bean;

import java.util.Map;

import org.openspaces.admin.Admin;
import org.openspaces.admin.alert.Alert;
import org.openspaces.admin.alert.AlertFactory;
import org.openspaces.admin.alert.AlertSeverity;
import org.openspaces.admin.alert.AlertStatus;
import org.openspaces.admin.alert.alerts.ReplicationRedoLogSizeAlert;
import org.openspaces.admin.alert.config.ReplicationRedoLogSizeAlertConfiguration;
import org.openspaces.admin.bean.BeanConfigurationException;
import org.openspaces.admin.internal.alert.InternalAlertManager;
import org.openspaces.admin.internal.alert.bean.util.AlertBeanUtils;
import org.openspaces.admin.space.ReplicationStatus;
import org.openspaces.admin.space.ReplicationTarget;
import org.openspaces.admin.space.SpaceInstance;
import org.openspaces.admin.space.events.SpaceInstanceRemovedEventListener;
import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEvent;
import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEventListener;

import com.gigaspaces.cluster.activeelection.SpaceMode;
import com.j_spaces.core.filters.ReplicationStatistics;

public class ReplicationRedoLogSizeAlertBean implements AlertBean, SpaceInstanceRemovedEventListener, SpaceInstanceStatisticsChangedEventListener {

    public static final String beanUID = "3f4bff98-52de6d72-b2b8-434b-aa18-d57c7554262a";
    public static final String ALERT_NAME = "Replication Redo log";

    private final ReplicationRedoLogSizeAlertConfiguration config = new ReplicationRedoLogSizeAlertConfiguration();

    private Admin admin;

    public ReplicationRedoLogSizeAlertBean() {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        validateProperties();
        admin.getSpaces().getSpaceInstanceRemoved().add(this);
        admin.getSpaces().getSpaceInstanceStatisticsChanged().add(this);
        admin.getSpaces().startStatisticsMonitor();
    }

    @Override
    public void destroy() throws Exception {
        admin.getSpaces().getSpaceInstanceRemoved().remove(this);
        admin.getSpaces().getSpaceInstanceStatisticsChanged().remove(this);
        admin.getSpaces().stopStatisticsMonitor();
    }

    @Override
    public Map<String, String> getProperties() {
        return config.getProperties();
    }

    @Override
    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    @Override
    public void setProperties(Map<String, String> properties) {
        config.setProperties(properties);
    }

    private void validateProperties() {

        if (config.getHighThresholdRedoLogSize() == null) {
            throw new BeanConfigurationException("High threshold property is null");
        }

        if (config.getLowThresholdRedoLogSize() == null) {
            throw new BeanConfigurationException("Low threshold property is null");
        }

        if (config.getHighThresholdRedoLogSize() < config.getLowThresholdRedoLogSize()) {
            throw new BeanConfigurationException("Low threshold [" + config.getLowThresholdRedoLogSize()
                    + "] must be less than high threshold value [" + config.getHighThresholdRedoLogSize() + "]");
        }

        if (config.getHighThresholdRedoLogSize() < 0) {
            throw new BeanConfigurationException("High threshold [" + config.getHighThresholdRedoLogSize()
                    + "] must greater than zero");
        }

        if (config.getLowThresholdRedoLogSize() < 0) {
            throw new BeanConfigurationException("Low threshold [" + config.getLowThresholdRedoLogSize()
                    + "] must greater or equal to zero");
        }
    }

    @Override
    public void spaceInstanceRemoved(SpaceInstance spaceInstance) {
        final String groupUid = generateGroupUid(spaceInstance.getUid());
        Alert[] alertsByGroupUid = ((InternalAlertManager)admin.getAlertManager()).getAlertRepository().getAlertsByGroupUid(groupUid);
        if (alertsByGroupUid.length != 0 && !alertsByGroupUid[0].getStatus().isResolved()) {
            AlertFactory factory = new AlertFactory();
            factory.name(ALERT_NAME);
            factory.groupUid(groupUid);
            factory.description("Replication redo log is unavailable; " + getSpaceName(spaceInstance) + " has been removed.");
            factory.severity(AlertSeverity.WARNING);
            factory.status(AlertStatus.NA);
            factory.componentUid(spaceInstance.getUid());
            factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(spaceInstance));
            factory.config(config.getProperties());

            Alert alert = factory.toAlert();
            admin.getAlertManager().triggerAlert( new ReplicationRedoLogSizeAlert(alert));
        }
    }

    @Override
    public void spaceInstanceStatisticsChanged(SpaceInstanceStatisticsChangedEvent event) {

        int highThreshold = config.getHighThresholdRedoLogSize();
        int lowThreshold = config.getLowThresholdRedoLogSize();

        final SpaceInstance source = event.getSpaceInstance();
        final ReplicationStatistics replicationStatistics = event.getStatistics().getReplicationStatistics();
        if (replicationStatistics == null) return;

        long redoLogSize = replicationStatistics.getOutgoingReplication().getRedoLogSize();

        if (redoLogSize > highThreshold) {
            final String groupUid = generateGroupUid(source.getUid());
            AlertFactory factory = new AlertFactory();
            factory.name(ALERT_NAME);
            factory.groupUid(groupUid);
            factory.description("Replication redo-log size crossed above a " + highThreshold + " threshold, with a size of " + redoLogSize + " for " + getSpaceName(source));
            factory.severity(AlertSeverity.WARNING);
            factory.status(AlertStatus.RAISED);
            factory.componentUid(source.getUid());
            factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(source));
            factory.config(config.getProperties());

            factory.putProperty(ReplicationRedoLogSizeAlert.HOST_ADDRESS, source.getMachine().getHostAddress());
            factory.putProperty(ReplicationRedoLogSizeAlert.HOST_NAME, source.getMachine().getHostName());
            factory.putProperty(ReplicationRedoLogSizeAlert.VIRTUAL_MACHINE_UID, source.getVirtualMachine().getUid());
            factory.putProperty(ReplicationRedoLogSizeAlert.CPU_UTILIZATION, String.valueOf(source.getOperatingSystem().getStatistics().getCpuPerc()*100.0));
            factory.putProperty(ReplicationRedoLogSizeAlert.HEAP_UTILIZATION, String.valueOf(source.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()));

            factory.putProperty(ReplicationRedoLogSizeAlert.REPLICATION_STATUS, getReplicationStatus(source));
            factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_SIZE, String.valueOf(redoLogSize));
            factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_MEMORY_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogMemoryPacketCount()));
            factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_SWAP_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogExternalStoragePacketCount()));

            Alert alert = factory.toAlert();
            admin.getAlertManager().triggerAlert( new ReplicationRedoLogSizeAlert(alert));

        } else if (redoLogSize <= lowThreshold) {
            final String groupUid = generateGroupUid(source.getUid());
            Alert[] alertsByGroupUid = ((InternalAlertManager)admin.getAlertManager()).getAlertRepository().getAlertsByGroupUid(groupUid);
            if (alertsByGroupUid.length != 0 && !alertsByGroupUid[0].getStatus().isResolved()) {
                AlertFactory factory = new AlertFactory();
                factory.name(ALERT_NAME);
                factory.groupUid(groupUid);
                factory.description("Replication redo-log size crossed below a " + lowThreshold + " threshold, with a size of " + redoLogSize + " for " + getSpaceName(source));
                factory.severity(AlertSeverity.WARNING);
                factory.status(AlertStatus.RESOLVED);
                factory.componentUid(event.getSpaceInstance().getUid());
                factory.componentDescription(AlertBeanUtils.getSpaceInstanceDescription(source));
                factory.config(config.getProperties());

                factory.putProperty(ReplicationRedoLogSizeAlert.HOST_ADDRESS, source.getMachine().getHostAddress());
                factory.putProperty(ReplicationRedoLogSizeAlert.HOST_NAME, source.getMachine().getHostName());
                factory.putProperty(ReplicationRedoLogSizeAlert.VIRTUAL_MACHINE_UID, source.getVirtualMachine().getUid());
                factory.putProperty(ReplicationRedoLogSizeAlert.CPU_UTILIZATION, String.valueOf(source.getOperatingSystem().getStatistics().getCpuPerc()*100.0));
                factory.putProperty(ReplicationRedoLogSizeAlert.HEAP_UTILIZATION, String.valueOf(source.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()));

                factory.putProperty(ReplicationRedoLogSizeAlert.REPLICATION_STATUS, getReplicationStatus(source));
                factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_SIZE, String.valueOf(redoLogSize));
                factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_MEMORY_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogMemoryPacketCount()));
                factory.putProperty(ReplicationRedoLogSizeAlert.REDO_LOG_SWAP_SIZE, String.valueOf(replicationStatistics.getOutgoingReplication().getRedoLogExternalStoragePacketCount()));

                Alert alert = factory.toAlert();
                admin.getAlertManager().triggerAlert(new ReplicationRedoLogSizeAlert(alert));
            }
        }
    }

    private String getReplicationStatus(SpaceInstance source) {
        for (ReplicationTarget target : source.getReplicationTargets()) {
            if (!ReplicationStatus.ACTIVE.equals(target.getReplicationStatus())) {
                return target.getReplicationStatus().name();
            }
        }
        return ReplicationStatus.ACTIVE.name();
    }

    private String getSpaceName(SpaceInstance source) {
        StringBuilder sb = new StringBuilder();
        SpaceMode sourceSpaceMode = source.getMode();
        sb.append(sourceSpaceMode.toString().toLowerCase()).append(" Space ");
        sb.append(source.getSpace().getName() + "." + source.getInstanceId() + " ["+(source.getBackupId()+1)+"]");
        return sb.toString();
    }

    private String generateGroupUid(String uid) {
        return beanUID.concat("-").concat(uid);
    }
}


text:
<?php
$menuLibPath = CakePlugin::path('Menu') . 'Lib';
require_once $menuLibPath . DS . 'MenuLib' . DS . 'MenuLibClassLoader.php';
$menuLibClassLoader = new MenuLibClassLoader('MenuLib', $menuLibPath);
$menuLibClassLoader->register();
?>


text:
import core
from core import *

import core.iconlistctrl as wxIconList

class DMIDE_RSCEditor(wxIconList.IconListCtrl):
		def __init__(self, root):
			wxIconList.IconListCtrl.__init__(self, root, style=wx.LC_ICON | wx.LC_VIRTUAL | wx.NO_BORDER | wx.CLIP_CHILDREN)

			self.initAll()
			self.initBinds()

		def initAll(self):
			self.last_pos = -1
			self.files = []
			self.images = None
			#self.image_list = None

		def initBinds(self):
			#self.Bind(wx.EVT_SIZE, self.OnSize)
			self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)

		def Open(self, rscfile):
			self.path = rscfile
			self.files = rsc.RSCREAD(rscfile, True)
			self.update()
			self.Refresh()

		def update(self):
			self.images = []
			#self.image_list = wx.ImageList(32, 32)
			art = wx.GetApp().art

			for file in self.files:
				img = art.getFromExt(os.path.splitext(file[0])[-1][1:], (32, 32))

				if type(img) == int:
					img = art.getFromWx(wx.ART_NORMAL_FILE, (32, 32))

				self.images.append(img)#self.image_list.Add(img))

			#self.AssignImageList(self.image_list, wx.IMAGE_LIST_NORMAL)
			self.SetItemCount(len(self.files))

		def OnGetItem(self, index):
			return ('%s\n%sB' % (self.files[index][0], self.files[index][1]), self.images[index])

		'''
		def OnGetItemText(self, index, col):
			try:
				return '%s\n%sB' % (self.files[index][0], self.files[index][1])
			except IndexError:
				return 'IndexError'

		def OnGetItemImage(self, index):
			try:
				return self.images[index]
			except IndexError:
				return 'IndexError'

		def OnGetItemAttr(self, index):
			return None
		'''

		#def OnSize(self, event):
		#	event.Skip()
		#	last_pos = self.GetItemRect(self.GetItemCount() - 1)
		#	if self.last_pos != last_pos:
		#		self.last_pos = last_pos
		#		self.Refresh(False)

		def OnKeyDown(self, event):
			print event.GetKeyCode()
			if event.GetKeyCode() == 72 and event.ControlDown():
				files = rsc.RSCREAD(self.path, False)

				dlg = wx.DirDialog(self, 'Choose a dir to save the files:', style=wx.DD_DEFAULT_STYLE)

				if dlg.ShowModal() == wx.ID_OK:
					path = os.path.abspath(dlg.GetPath())

					if not os.path.exists(path):
						os.mkdir(path)

					for file in files:
						open(os.path.join(path, file[0]), 'wb').write(file[2])

				dlg.Destroy()

if __name__ == '__main__':
	a = wx.App(0)
	w = Window()
	w.Show(True)
	a.MainLoop()


text:
import { useEffect } from 'react';

import { useLatestCallback } from './useLatestCallback.hook';

/**
 * A react hook which invokes a callback function on a specific millisecond interval.
 * Works just like setInterval(), but in a hook.
 *
 * If no callback is provided during a render (i.e. passing null or another falsey value)
 * then no interval will be set and the existing interval will be canceled if one is already running.
 * This is useful for components which only need to run an interval conditionally but not all the time.
 *
 * Passing a different/changed interval will reset the cycle with the new interval time.
 * *
 * @param callback the callback to be invoked at every interval, or null/undefined
 * for no interval at all
 * @param interval the length of time in milliseconds between each interval
 * @returns void
 */
export function useInterval(callback: () => any, interval: number): void {
  const stableCallback = useLatestCallback(callback);

  useEffect(() => {
    const id = !!callback && interval && setInterval(stableCallback, interval);

    return () => id && clearInterval(id);
  }, [!!callback, interval]);
}


text:
package org.elasticsearch.discovery.zen;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.DummyTransportAddress;
import org.elasticsearch.discovery.zen.elect.ElectMasterService;
import org.elasticsearch.test.ESTestCase;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ElectMasterServiceTests extends ESTestCase {

    ElectMasterService electMasterService() {
        return new ElectMasterService(Settings.EMPTY, Version.CURRENT);
    }

    List<DiscoveryNode> generateRandomNodes() {
        int count = scaledRandomIntBetween(1, 100);
        ArrayList<DiscoveryNode> nodes = new ArrayList<>(count);

        for (int i = 0; i < count; i++) {
            Set<DiscoveryNode.Role> roles = new HashSet<>();
            if (randomBoolean()) {
                roles.add(DiscoveryNode.Role.MASTER);
            }
            DiscoveryNode node = new DiscoveryNode("n_" + i, "n_" + i, DummyTransportAddress.INSTANCE, Collections.emptyMap(),
                    roles, Version.CURRENT);
            nodes.add(node);
        }

        Collections.shuffle(nodes, random());
        return nodes;
    }

    public void testSortByMasterLikelihood() {
        List<DiscoveryNode> nodes = generateRandomNodes();
        List<DiscoveryNode> sortedNodes = electMasterService().sortByMasterLikelihood(nodes);
        assertEquals(nodes.size(), sortedNodes.size());
        DiscoveryNode prevNode = sortedNodes.get(0);
        for (int i = 1; i < sortedNodes.size(); i++) {
            DiscoveryNode node = sortedNodes.get(i);
            if (!prevNode.isMasterNode()) {
                assertFalse(node.isMasterNode());
            } else if (node.isMasterNode()) {
                assertTrue(prevNode.getId().compareTo(node.getId()) < 0);
            }
            prevNode = node;
        }

    }

    public void testElectMaster() {
        List<DiscoveryNode> nodes = generateRandomNodes();
        ElectMasterService service = electMasterService();
        int min_master_nodes = randomIntBetween(0, nodes.size());
        service.minimumMasterNodes(min_master_nodes);

        int master_nodes = 0;
        for (DiscoveryNode node : nodes) {
            if (node.isMasterNode()) {
                master_nodes++;
            }
        }
        DiscoveryNode master = null;
        if (service.hasEnoughMasterNodes(nodes)) {
            master = service.electMaster(nodes);
        }

        if (master_nodes == 0) {
            assertNull(master);
        } else if (min_master_nodes > 0 && master_nodes < min_master_nodes) {
            assertNull(master);
        } else {
            assertNotNull(master);
            for (DiscoveryNode node : nodes) {
                if (node.isMasterNode()) {
                    assertTrue(master.getId().compareTo(node.getId()) <= 0);
                }
            }
        }
    }
}


text:
from __future__ import unicode_literals

import django.db.models.deletion
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0003_auto_20170607_1800"),
        ("studies", "0001_initial"),
    ]

    operations = [
        migrations.RemoveField(model_name="response", name="profile"),
        migrations.AddField(
            model_name="response",
            name="child",
            field=models.ForeignKey(
                default=1,
                on_delete=django.db.models.deletion.DO_NOTHING,
                to="accounts.Child",
            ),
            preserve_default=False,
        ),
    ]


text:
static JGProgressHUD *HUD;
static UIView *presentView;

@implementation CHXHUD

+ (void)showHUDWithMessage:(NSString *)message {
//    if (HUD.targetView) {
//        [HUD removeFromSuperview];
//    }

    JGProgressHUD *staticHUD = [self staticHUD];
    staticHUD.indicatorView = nil;
    staticHUD.textLabel.text = message;
    [staticHUD dismissAfterDelay:1.2f];
    [staticHUD showInView:presentView animated:YES];
}

+ (void)showHUDWithMessage:(NSString *)message fromView:(UIView *)view {
    if (!view.window) {
        return;
    }
    [self showHUDWithMessage:message];
}

+ (void)showLoadingHUDWithMessage:(NSString *)message {
//    if (HUD.targetView) {
//        [HUD removeFromSuperview];
//    }

    JGProgressHUD *staticHUD = [self staticHUD];
    staticHUD.interactionType = JGProgressHUDInteractionTypeBlockAllTouches;
    JGProgressHUDFadeZoomAnimation *animation = [JGProgressHUDFadeZoomAnimation animation];
    staticHUD.HUDView.layer.shadowColor = [UIColor blackColor].CGColor;
    staticHUD.HUDView.layer.shadowOffset = CGSizeZero;
    staticHUD.HUDView.layer.shadowOpacity = 0.4f;
    staticHUD.HUDView.layer.shadowRadius = 8.0f;
    staticHUD.animation = animation;
    staticHUD.textLabel.text = message.length ? message : @"加载中...";
    [staticHUD showInView:presentView animated:YES];
}

+ (void)showLoadingHUD {
//    if (HUD.targetView) {
//        [HUD removeFromSuperview];
//    }

    JGProgressHUD *staticHUD = [self staticHUD];
    [staticHUD showInView:presentView animated:YES];
}

+ (void)removeHUDIfExist {
    [HUD dismissAnimated:YES];
}

+ (JGProgressHUD *)staticHUD {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
        HUD.interactionType = JGProgressHUDInteractionTypeBlockNoTouches;
        HUD.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
        presentView = [UIApplication sharedApplication].keyWindow;
    });

    return HUD;
}

@end

#endif


text:
class Scene_End < Scene_MenuBase
  #--------------------------------------------------------------------------
  # * Start Processing
  #--------------------------------------------------------------------------
  def start
    super
    create_command_window
  end
  #--------------------------------------------------------------------------
  # * Pre-Termination Processing
  #--------------------------------------------------------------------------
  def pre_terminate
    super
    close_command_window
  end
  #--------------------------------------------------------------------------
  # * Create Background
  #--------------------------------------------------------------------------
  def create_background
    super
    @background_sprite.tone.set(0, 0, 0, 128)
  end
  #--------------------------------------------------------------------------
  # * Create Command Window
  #--------------------------------------------------------------------------
  def create_command_window
    @command_window = Window_GameEnd.new
    @command_window.set_handler(:to_title, method(:command_to_title))
    @command_window.set_handler(:shutdown, method(:command_shutdown))
    @command_window.set_handler(:cancel,   method(:return_scene))
  end
  #--------------------------------------------------------------------------
  # * Close Command Window
  #--------------------------------------------------------------------------
  def close_command_window
    @command_window.close
    update until @command_window.close?
  end
  #--------------------------------------------------------------------------
  # * [Go to Title] Command
  #--------------------------------------------------------------------------
  def command_to_title
    close_command_window
    fadeout_all
    SceneManager.goto(Scene_Title)
  end
  #--------------------------------------------------------------------------
  # * [Shut Down] Command
  #--------------------------------------------------------------------------
  def command_shutdown
    close_command_window
    fadeout_all
    SceneManager.exit
  end
end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('deal', '__first__'),
        ('UserProfile', '0006_auto_20141011_0745'),
    ]

    operations = [
        migrations.AddField(
            model_name='profile',
            name='bookmarks',
            field=models.ManyToManyField(related_name=b'bookmark', to='deal.Deal'),
            preserve_default=True,
        ),
    ]


text:
namespace EAN.Api.Messages.Request
{
    using System.Collections.Generic;

    public class HotelInformationRequest
    {
        public int HotelId { get; set; }
        public List<Options> Options { get; set; }
    }
}