text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using System.IO;

namespace BasicNHibernate
{
    class Program
    {
        static void Main(string[] args)
        {
            Configuration cfg = Configure();

            var diretorio = Directory.GetCurrentDirectory();

            ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();
            //ITransaction transaction = session.BeginTransaction();

            var usuario = CriarUsuario();

            session.Save(usuario);
            var usuarioRet = session.CreateCriteria<Usuario>().Add(Restrictions.Like("Nome", "%or%")).List();
            //transaction.Commit();
            session.Close();
        }

        private static Configuration Configure()
        {
            var cfg = new Configuration();
            cfg.Configure(@"..\..\NHConf\hibernate.cfg.xml");
            cfg.AddFile(@"..\..\NHConf\\Usuario.hbm.xml");

            return cfg;
        }

        public static Usuario CriarUsuario()
        {
            return new Usuario
            {
                Nome = "Phulano",
                Endereco = "Rua XXX, yyy",
                Idade = 20
            };
        }
    }
}


text:
package org.edx.mobile.module.db.impl;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import org.edx.mobile.logger.Logger;
import org.edx.mobile.module.db.DbStructure;

/**
 * This class is an implementation of {@link SQLiteOpenHelper} and handles
 * database upgrades.
 * @author rohan
 *
 */
class DbHelper extends SQLiteOpenHelper {

    private SQLiteDatabase sqliteDb;
    protected final Logger logger = new Logger(getClass().getName());

    public DbHelper(Context context) {
        super(context, DbStructure.NAME, null, DbStructure.VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE "                        + DbStructure.Table.DOWNLOADS
                + " ("
                + DbStructure.Column.ID                     + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + DbStructure.Column.USERNAME               + " TEXT, "
                + DbStructure.Column.VIDEO_ID               + " TEXT, "
                + DbStructure.Column.TITLE                  + " TEXT, "
                + DbStructure.Column.SIZE                   + " TEXT, "
                + DbStructure.Column.DURATION               + " LONG, "
                + DbStructure.Column.FILEPATH               + " TEXT, "
                + DbStructure.Column.URL                    + " TEXT, "
                + DbStructure.Column.URL_HIGH_QUALITY       + " TEXT, "
                + DbStructure.Column.URL_LOW_QUALITY        + " TEXT, "
                + DbStructure.Column.URL_YOUTUBE            + " TEXT, "
                + DbStructure.Column.WATCHED                + " INTEGER, "
                + DbStructure.Column.DOWNLOADED             + " INTEGER, "
                + DbStructure.Column.DM_ID                  + " INTEGER, "
                + DbStructure.Column.EID                    + " TEXT, "
                + DbStructure.Column.CHAPTER                + " TEXT, "
                + DbStructure.Column.SECTION                + " TEXT, "
                + DbStructure.Column.DOWNLOADED_ON          + " INTEGER, "
                + DbStructure.Column.LAST_PLAYED_OFFSET     + " INTEGER, "
                + DbStructure.Column.IS_COURSE_ACTIVE       + " BOOLEAN, "
                + DbStructure.Column.UNIT_URL               + " TEXT, "
                + DbStructure.Column.VIDEO_FOR_WEB_ONLY     + " BOOLEAN "
                + ")";
        db.execSQL(sql);

        createAssessmentTable(db);

        logger.debug("Database created");
    }

    private void createAssessmentTable(SQLiteDatabase db){
        String sql = "CREATE TABLE "                        + DbStructure.Table.ASSESSMENT
            + " ("
            + DbStructure.Column.ASSESSMENT_TB_ID       + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + DbStructure.Column.ASSESSMENT_TB_USERNAME + " TEXT, "
            + DbStructure.Column.ASSESSMENT_TB_UNIT_ID  + " TEXT, "
            + DbStructure.Column.ASSESSMENT_TB_UNIT_WATCHED + " BOOLEAN "
            + ")";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            String upgradeToV2 =
                    "ALTER TABLE "    + DbStructure.Table.DOWNLOADS + " ADD COLUMN "
                                      + DbStructure.Column.UNIT_URL + " TEXT ";

            String[] upgradeToV3 = new String[] {
                    "ALTER TABLE "    + DbStructure.Table.DOWNLOADS + " ADD COLUMN "
                                      + DbStructure.Column.URL_HIGH_QUALITY + " TEXT ",

                    "ALTER TABLE "    + DbStructure.Table.DOWNLOADS + " ADD COLUMN "
                                      + DbStructure.Column.URL_LOW_QUALITY + " TEXT ",

                    "ALTER TABLE "    + DbStructure.Table.DOWNLOADS + " ADD COLUMN "
                                      + DbStructure.Column.URL_YOUTUBE + " TEXT "};

            String upgradeToV4 =
                    "ALTER TABLE "    + DbStructure.Table.DOWNLOADS + " ADD COLUMN "
                            + DbStructure.Column.VIDEO_FOR_WEB_ONLY + " BOOLEAN ";

            if ( oldVersion == 1 ) {
                // upgrade from 1 to 2
                db.execSQL(upgradeToV2);
            }

            if ( oldVersion < 3 ) {
                // upgrade to version 3
                for (String query : upgradeToV3) {
                    db.execSQL(query);
                }
            }

            if ( oldVersion < 4 ) {
                // upgrade to version 4
                db.execSQL(upgradeToV4);
            }

            if ( oldVersion < 5 ){
                createAssessmentTable(db);
            }

            logger.debug("Database upgraded from " + oldVersion + " to " + newVersion);
        }catch(Exception e){
            logger.error(e);
        }
    }

    /**
     * Returns singleton writable {@link SQLiteDatabase} object.
     * @return
     */
    public SQLiteDatabase getDatabase() {
        if (sqliteDb == null) {
            sqliteDb = this.getWritableDatabase();
            logger.debug("Writable database handle opened");
        }
        return sqliteDb;
    }

    @Override
    public synchronized void close() {
        super.close();

        sqliteDb = null;
        logger.debug("Database closed");
    }
}

redpajama_set_name: RedPajamaGithub


text:
module ActiveRecord
  module ConnectionAdapters
    module PostgreSQL
      module SchemaStatements
        # Resets the sequence of a table's primary key to the maximum value.
        def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
          unless pk && sequence
            default_pk, default_sequence = pk_and_sequence_for(table)

            pk ||= default_pk
            sequence ||= default_sequence
          end

          if @logger && pk && !sequence
            @logger.warn "#{table} has primary key #{pk} with no default sequence."
          end

          if pk && sequence
            quoted_sequence = quote_table_name(sequence)
            max_pk = select_value("select MAX(#{quote_column_name pk}) from #{quote_table_name(table)}")
            if max_pk.nil?
              if postgresql_version >= 100000
                minvalue = select_value("SELECT seqmin from pg_sequence where seqrelid = '#{quoted_sequence}'::regclass")
              else
                minvalue = select_value("SELECT min_value FROM #{quoted_sequence}")
              end
            end

            select_value(<<-end_sql, "SCHEMA")
              SELECT setval('#{quoted_sequence}', #{max_pk ? max_pk : minvalue}, #{max_pk ? true : false})
            end_sql
          end
        end
      end
    end
  end
end


text:
FROM node:8

RUN npm install -g bower grunt-cli yarnpkg


text:
// Copyright (c) 2014, ultramailman
// This file is licensed under the MIT License.

#ifndef MATRIX_HASH_H
#define MATRIX_HASH_H
#include <climits>
template <class InType>
static bool parity(InType in)
{
	int bit = 0;
	while(in)
	{
		bit ^= in & 1;
		in >>= 1;
	}
	return bit != 0;
}

/* MatrixHash computes a hash by multiplying
a randomly generated bit matrix on the input bit vector.
*/
template < class InType, class OutType, class Gen >
class MatrixHash {
	static constexpr unsigned cols = sizeof(InType) * CHAR_BIT;
	static constexpr unsigned rows = sizeof(OutType) * CHAR_BIT;

	// the matrix is in column layout. (an array of column vectors)
	OutType cols_ [cols];

	// generate a bit string using the random generator
	OutType genString(Gen & gen)
	{
		OutType col = 0;

		for(unsigned i = 0; i < rows; i++)
		{
			auto num = gen();
			col |= parity(num);
			col <<= 1;
		}
		return col;
	}
public:
	MatrixHash (Gen & gen)
	{
		// initialize the matrix with random bits
		for(OutType & col: cols_)
		{
			col = genString(gen);
		}
	}

	// compute bit matrix multiplication on bit vector.
	OutType operator () (InType b) const
	{
		OutType x = 0;
		for(unsigned i = 0; i < cols; i++)
		{
			OutType bi = (b >> i) & 1;
			OutType mask = 0 - bi;
			OutType xi = cols_[i] & mask;
			x = x ^ xi;
		}
		return x;
	}
};
#endif


text:
namespace page_load_metrics {

namespace {
const int kInitialTimerDelayMillis = 50;
const int64_t kInputDelayAdjustmentMillis = int64_t(50);

mojom::UserInteractionType UserInteractionTypeForMojom(
    blink::UserInteractionType interaction_type) {
  switch (interaction_type) {
    case blink::UserInteractionType::kKeyboard:
      return mojom::UserInteractionType::kKeyboard;
    case blink::UserInteractionType::kTapOrClick:
      return mojom::UserInteractionType::kTapOrClick;
    case blink::UserInteractionType::kDrag:
      return mojom::UserInteractionType::kDrag;
  }
  // mojom::UserInteractionType should have the same interaction types as
  // blink::UserInteractionType does.
  NOTREACHED();
  return mojom::UserInteractionType::kMinValue;
}

}  // namespace

PageTimingMetricsSender::PageTimingMetricsSender(
    std::unique_ptr<PageTimingSender> sender,
    std::unique_ptr<base::OneShotTimer> timer,
    mojom::PageLoadTimingPtr initial_timing,
    const PageTimingMetadataRecorder::MonotonicTiming& initial_monotonic_timing,
    std::unique_ptr<PageResourceDataUse> initial_request)
    : sender_(std::move(sender)),
      timer_(std::move(timer)),
      last_timing_(std::move(initial_timing)),
      last_cpu_timing_(mojom::CpuTiming::New()),
      input_timing_delta_(mojom::InputTiming::New()),
      metadata_(mojom::FrameMetadata::New()),
      buffer_timer_delay_ms_(GetBufferTimerDelayMillis(TimerType::kRenderer)),
      metadata_recorder_(initial_monotonic_timing) {
  InitiateUserInteractionTiming();
  const auto resource_id = initial_request->resource_id();
  page_resource_data_use_.emplace(
      std::piecewise_construct, std::forward_as_tuple(resource_id),
      std::forward_as_tuple(std::move(initial_request)));
  if (!IsEmpty(*last_timing_)) {
    EnsureSendTimer();
  }
}

PageTimingMetricsSender::~PageTimingMetricsSender() {
  // Make sure we don't have any unsent data. If this assertion fails, then it
  // means metrics are somehow coming in between MetricsRenderFrameObserver's
  // ReadyToCommitNavigation and DidCommitProvisionalLoad.
  DCHECK(!timer_->IsRunning());
}

void PageTimingMetricsSender::DidObserveLoadingBehavior(
    blink::LoadingBehaviorFlag behavior) {
  if (behavior & metadata_->behavior_flags) {
    return;
  }
  metadata_->behavior_flags |= behavior;
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidObserveNewFeatureUsage(
    const blink::UseCounterFeature& feature) {
  if (feature_tracker_.TestAndSet(feature))
    return;

  new_features_.push_back(feature);
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidObserveLayoutShift(
    double score,
    bool after_input_or_scroll) {
  DCHECK(score > 0);
  render_data_.layout_shift_delta += score;
  render_data_.new_layout_shifts.push_back(
      mojom::LayoutShift::New(base::TimeTicks::Now(), score));
  if (!after_input_or_scroll)
    render_data_.layout_shift_delta_before_input_or_scroll += score;
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidObserveLayoutNg(uint32_t all_block_count,
                                                 uint32_t ng_block_count,
                                                 uint32_t all_call_count,
                                                 uint32_t ng_call_count) {
  render_data_.all_layout_block_count_delta += all_block_count;
  render_data_.ng_layout_block_count_delta += ng_block_count;
  render_data_.all_layout_call_count_delta += all_call_count;
  render_data_.ng_layout_call_count_delta += ng_call_count;
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidObserveMobileFriendlinessChanged(
    const blink::MobileFriendliness& mf) {
  mobile_friendliness_ = mf;
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidStartResponse(
    const GURL& response_url,
    int resource_id,
    const network::mojom::URLResponseHead& response_head,
    network::mojom::RequestDestination request_destination) {
  DCHECK(!base::Contains(page_resource_data_use_, resource_id));

  auto resource_it = page_resource_data_use_.emplace(
      std::piecewise_construct, std::forward_as_tuple(resource_id),
      std::forward_as_tuple(std::make_unique<PageResourceDataUse>()));
  resource_it.first->second->DidStartResponse(
      response_url, resource_id, response_head, request_destination);
}

void PageTimingMetricsSender::DidReceiveTransferSizeUpdate(
    int resource_id,
    int received_data_length) {
  // Transfer size updates are called in a throttled manner.
  auto resource_it = page_resource_data_use_.find(resource_id);

  // It is possible that resources are not in the map, if response headers were
  // not received or for failed/cancelled resources.
  if (resource_it == page_resource_data_use_.end()) {
    return;
  }

  resource_it->second->DidReceiveTransferSizeUpdate(received_data_length);
  modified_resources_.insert(resource_it->second.get());
  EnsureSendTimer();
}

void PageTimingMetricsSender::DidCompleteResponse(
    int resource_id,
    const network::URLLoaderCompletionStatus& status) {
  auto resource_it = page_resource_data_use_.find(resource_id);

  // It is possible that resources are not in the map, if response headers were
  // not received or for failed/cancelled resources. For data reduction proxy
  // purposes treat these as having no savings.
  if (resource_it == page_resource_data_use_.end()) {
    auto new_resource_it = page_resource_data_use_.emplace(
        std::piecewise_construct, std::forward_as_tuple(resource_id),
        std::forward_as_tuple(std::make_unique<PageResourceDataUse>()));
    resource_it = new_resource_it.first;
  }

  resource_it->second->DidCompleteResponse(status);
  EnsureSendTimer();
  modified_resources_.insert(resource_it->second.get());
}

void PageTimingMetricsSender::DidCancelResponse(int resource_id) {
  auto resource_it = page_resource_data_use_.find(resource_id);
  if (resource_it == page_resource_data_use_.end()) {
    return;
  }
  resource_it->second->DidCancelResponse();
}

void PageTimingMetricsSender::DidLoadResourceFromMemoryCache(
    const GURL& response_url,
    int request_id,
    int64_t encoded_body_length,
    const std::string& mime_type) {
  // In general, we should not observe the same resource being loaded twice in
  // the frame. This is possible due to an existing workaround in
  // ResourceFetcher::EmulateLoadStartedForInspector(). In this case, ignore
  // multiple resources being loaded in the document, as memory cache resources
  // are only reported once per context by design in all other cases.
  if (base::Contains(page_resource_data_use_, request_id))
    return;

  auto resource_it = page_resource_data_use_.emplace(
      std::piecewise_construct, std::forward_as_tuple(request_id),
      std::forward_as_tuple(std::make_unique<PageResourceDataUse>()));
  resource_it.first->second->DidLoadFromMemoryCache(
      response_url, request_id, encoded_body_length, mime_type);
  modified_resources_.insert(resource_it.first->second.get());
}

void PageTimingMetricsSender::OnMainFrameIntersectionChanged(
    const gfx::Rect& main_frame_intersection) {
  metadata_->intersection_update =
      mojom::FrameIntersectionUpdate::New(main_frame_intersection);
  EnsureSendTimer();
}

void PageTimingMetricsSender::UpdateResourceMetadata(
    int resource_id,
    bool reported_as_ad_resource,
    bool is_main_frame_resource,
    bool completed_before_fcp) {
  auto it = page_resource_data_use_.find(resource_id);
  if (it == page_resource_data_use_.end())
    return;

  // This can get called multiple times for a resource, and this flag will only
  // be true once.
  if (reported_as_ad_resource)
    it->second->SetReportedAsAdResource(reported_as_ad_resource);

  // This can get called multiple times for a resource, and this flag will only
  // be true once.
  if (completed_before_fcp)
    it->second->SetCompletedBeforeFCP(completed_before_fcp);

  it->second->SetIsMainFrameResource(is_main_frame_resource);
}

void PageTimingMetricsSender::SetUpSmoothnessReporting(
    base::ReadOnlySharedMemoryRegion shared_memory) {
  sender_->SetUpSmoothnessReporting(std::move(shared_memory));
}

void PageTimingMetricsSender::Update(
    mojom::PageLoadTimingPtr timing,
    const PageTimingMetadataRecorder::MonotonicTiming& monotonic_timing) {
  if (last_timing_->Equals(*timing)) {
    return;
  }

  // We want to make sure that each PageTimingMetricsSender is associated
  // with a distinct page navigation. Because we reset the object on commit,
  // we can trash last_timing_ on a provisional load before SendNow() fires.
  if (!last_timing_->navigation_start.is_null() &&
      last_timing_->navigation_start != timing->navigation_start) {
    return;
  }

  // We want to force sending the metrics quickly when FCP is reached.
  bool send_urgently =
      (!last_timing_->paint_timing ||
       !last_timing_->paint_timing->first_contentful_paint.has_value()) &&
      timing->paint_timing &&
      timing->paint_timing->first_contentful_paint.has_value();

  last_timing_ = std::move(timing);
  metadata_recorder_.UpdateMetadata(monotonic_timing);
  EnsureSendTimer(send_urgently);
}

void PageTimingMetricsSender::SendLatest() {
  if (!timer_->IsRunning())
    return;

  timer_->Stop();
  SendNow();
}

void PageTimingMetricsSender::UpdateCpuTiming(base::TimeDelta task_time) {
  last_cpu_timing_->task_time += task_time;
  EnsureSendTimer();
}

void PageTimingMetricsSender::EnsureSendTimer(bool urgent) {
  if (urgent)
    timer_->Stop();
  else if (timer_->IsRunning())
    return;

  int delay_ms;
  if (urgent) {
    // Send as soon as possible, but not synchronously, so that all pending
    // presentation callbacks for the current frame can run first.
    delay_ms = 0;
  } else if (have_sent_ipc_) {
    // This is the typical case.
    delay_ms = buffer_timer_delay_ms_;
  } else {
    // Send the first IPC eagerly to make sure the receiving side knows we're
    // sending metrics as soon as possible.
    delay_ms = kInitialTimerDelayMillis;
  }

  timer_->Start(FROM_HERE, base::Milliseconds(delay_ms),
                base::BindOnce(&PageTimingMetricsSender::SendNow,
                               base::Unretained(this)));
}

void PageTimingMetricsSender::SendNow() {
  have_sent_ipc_ = true;
  std::vector<mojom::ResourceDataUpdatePtr> resources;
  for (auto* resource : modified_resources_) {
    resources.push_back(resource->GetResourceDataUpdate());
    if (resource->IsFinishedLoading()) {
      page_resource_data_use_.erase(resource->resource_id());
    }
  }
  sender_->SendTiming(last_timing_, metadata_, std::move(new_features_),
                      std::move(resources), render_data_, last_cpu_timing_,
                      std::move(input_timing_delta_), mobile_friendliness_);
  input_timing_delta_ = mojom::InputTiming::New();
  mobile_friendliness_ = absl::nullopt;
  InitiateUserInteractionTiming();
  new_features_.clear();
  metadata_->intersection_update.reset();
  last_cpu_timing_->task_time = base::TimeDelta();
  modified_resources_.clear();
  render_data_.new_layout_shifts.clear();
  render_data_.layout_shift_delta = 0;
  render_data_.layout_shift_delta_before_input_or_scroll = 0;
  render_data_.all_layout_block_count_delta = 0;
  render_data_.ng_layout_block_count_delta = 0;
  render_data_.all_layout_call_count_delta = 0;
  render_data_.ng_layout_call_count_delta = 0;
}

void PageTimingMetricsSender::DidObserveInputDelay(
    base::TimeDelta input_delay) {
  input_timing_delta_->num_input_events++;
  input_timing_delta_->total_input_delay += input_delay;
  input_timing_delta_->total_adjusted_input_delay +=
      base::Milliseconds(std::max(int64_t(0), input_delay.InMilliseconds() -
                                                  kInputDelayAdjustmentMillis));
  EnsureSendTimer();
}

void PageTimingMetricsSender::InitiateUserInteractionTiming() {
  input_timing_delta_->max_event_durations =
      mojom::UserInteractionLatencies::NewUserInteractionLatencies({});
}

void PageTimingMetricsSender::DidObserveUserInteraction(
    base::TimeDelta max_event_duration,
    blink::UserInteractionType interaction_type) {
  input_timing_delta_->num_interactions++;
  input_timing_delta_->max_event_durations->get_user_interaction_latencies()
      .emplace_back(mojom::UserInteractionLatency::New(
          max_event_duration, UserInteractionTypeForMojom(interaction_type)));
  EnsureSendTimer();
}

}  // namespace page_load_metrics


text:
typedef enum {
    CVSStrokeComponentTypePoint,
    CVSStrokeComponentTypeCurve
} CVSStrokeComponentType;

@interface CVSStrokeComponent : NSManagedObject

@property (nonatomic, strong) NSNumber *typeNumber;
@property (nonatomic, strong) NSString *fromPointString;
@property (nonatomic, strong) NSString *toPointString;
@property (nonatomic, strong) NSString *controlPoint1String;
@property (nonatomic, strong) NSString *controlPoint2String;

@property (nonatomic) CVSStrokeComponentType type;
@property (nonatomic) CGPoint toPoint;
@property (nonatomic) CGPoint fromPoint;
@property (nonatomic) CGPoint controlPoint1;
@property (nonatomic) CGPoint controlPoint2;
@property (nonatomic, strong) NSManagedObject *stroke;

- (NSDictionary *)componentRepresentation;

@end


text:
class CreateAds < ActiveRecord::Migration[5.0]
  def change
    create_table :ads do |t|
      t.references :company, foreign_key: true
      t.references :run, foreign_key: true

      t.timestamps
    end
  end
end


text:
@implementation SmokeCOAlarmViewModel

@synthesize device;

#pragma mark Private

- (NSString *)_stringWithTitle:(NSString *)title alarmStateValue:(NestSDKSmokeCOAlarmAlarmState)value {
    NSString *alarmState = [self _alarmStateStringWithAlarmState:value];

    return [self stringWithTitle:title stringValue:alarmState];
}

- (NSString *)_alarmStateStringWithAlarmState:(NestSDKSmokeCOAlarmAlarmState)alarmState {
    switch (alarmState) {
        case NestSDKSmokeCOAlarmAlarmStateUndefined:
            return nil;

        case NestSDKSmokeCOAlarmAlarmStateOk:
            return @"OK";

        case NestSDKSmokeCOAlarmAlarmStateWarning:
            return @"Warning";

        case NestSDKSmokeCOAlarmAlarmStateEmergency:
            return @"Emergency";
    }

    return nil;
}

- (NSString *)_uiColorStateString {
    switch (self.device.uiColorState) {
        case NestSDKSmokeCOAlarmUIColorStateUndefined:
            return @"Undefined";

        case NestSDKSmokeCOAlarmUIColorStateGray:
            return @"Gray";

        case NestSDKSmokeCOAlarmUIColorStateGreen:
            return @"Green";

        case NestSDKSmokeCOAlarmUIColorStateYellow:
            return @"Yellow";

        case NestSDKSmokeCOAlarmUIColorStateRed:
            return @"Red";
    }

    return @"Undefined";
}

- (NSString *)_batteryHealthString {
    switch (self.device.batteryHealth) {
        case NestSDKSmokeCOAlarmBatteryHealthUndefined:
            return @"Undefined";

        case NestSDKSmokeCOAlarmBatteryHealthOk:
            return @"OK";

        case NestSDKSmokeCOAlarmBatteryHealthReplace:
            return @"Replace";
    }

    return @"Undefined";
}

#pragma mark Override

- (NSString *)localeText {
    return [self stringWithTitle:@"Locale:" stringValue:self.device.locale];
}

- (NSString *)lastConnectionText {
    return [self stringWithTitle:@"Last connection:" dateValue:self.device.lastConnection];
}

- (NSString *)coAlarmStateText {
    return [self _stringWithTitle:@"CO alarm state:" alarmStateValue:self.device.coAlarmState];
}

- (NSString *)smokeAlarmStateText {
    return [self _stringWithTitle:@"Smoke alarm state:" alarmStateValue:self.device.smokeAlarmState];
}

- (NSString *)isManualStateActiveText {
    return [self stringWithTitle:@"Manual state active:" boolValue:self.device.isManualTestActive];
}

- (NSString *)lastManualTestTimeText {
    return [self stringWithTitle:@"Last manual test:" dateValue:self.device.lastManualTestTime];
}

- (NSString *)batteryStatusText {
    NSString *batteryHealthString = [self _batteryHealthString];

    return [self stringWithTitle:@"Battery health:" stringValue:batteryHealthString];
}

- (NSString *)uiColorStateText {
    NSString *uiColorStateString = [self _uiColorStateString];

    return [self stringWithTitle:@"UI color:" stringValue:uiColorStateString];
}

- (SmokeCOAlarmIconViewColor)iconViewColor {
    switch (self.device.uiColorState) {
        case NestSDKSmokeCOAlarmUIColorStateUndefined:
            return SmokeCOAlarmIconViewColorUndefined;

        case NestSDKSmokeCOAlarmUIColorStateGray:
            return SmokeCOAlarmIconViewColorGray;

        case NestSDKSmokeCOAlarmUIColorStateGreen:
            return SmokeCOAlarmIconViewColorGreen;

        case NestSDKSmokeCOAlarmUIColorStateYellow:
            return SmokeCOAlarmIconViewColorYellow;

        case NestSDKSmokeCOAlarmUIColorStateRed:
            return SmokeCOAlarmIconViewColorRed;
    }

    return SmokeCOAlarmIconViewColorUndefined;
}

@end


text:
package com.motetronica.apptutores;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class RegistroCont extends AppCompatActivity {
    Spinner spinnerEdades;
    Spinner spinnerNivel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registro_cont);
        spinnerEdades = (Spinner) findViewById(R.id.spinnerEdad);
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.edades_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        spinnerEdades.setAdapter(adapter);

        spinnerNivel = (Spinner) findViewById(R.id.spinnerNivel);
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
                R.array.edades_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        spinnerEdades.setAdapter(adapter2);
    }
}


text:
fixture `speed`;

async function runSpeedTest (t) {
    const text = 'some text';

    // Setup
    await t.typeText('#input', text)
        .pressKey('tab');

    // With default speed setting (0.5)
    await t.typeText('#input', text, { replace: true })
        .pressKey('tab');

    const defaultSlowEditingTime = await t.eval(() => window.lastEditingTime);

    // Change test speed to 1
    await t
        .setTestSpeed(1)
        .typeText('#input', text, { replace: true })
        .pressKey('tab');

    const testFastSpeedEditingTime = await t.eval(() => window.lastEditingTime);

    // With specific action speed
    await t.typeText('#input', text, { speed: 0.5, replace: true })
        .pressKey('tab', { speed: 0.5 });

    const actionSlowEditingTime = await t.eval(() => window.lastEditingTime);

    // Check default speed was not changed
    await t
        .typeText('#input', text, { replace: true })
        .pressKey('tab');

    const testFastSpeedSecondEditingTime = await t.eval(() => window.lastEditingTime);

    await t
        .expect(defaultSlowEditingTime / testFastSpeedEditingTime).gte(2)
        .expect(actionSlowEditingTime / testFastSpeedEditingTime).gte(2)
        .expect(actionSlowEditingTime / testFastSpeedSecondEditingTime).gte(2);
}

test
    .page `http://localhost:3000/fixtures/api/es-next/speed/pages/index.html`
('Speed', async t => {
    await runSpeedTest(t);
});

test
    .page `http://localhost:3000/fixtures/api/es-next/speed/pages/iframe.html`
('Speed in iframe', async t => {
    await t.switchToIframe('iframe');
    await runSpeedTest(t);
});


text:
var fs = require('fs')
var path = require('path')

var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var test = require('tap').test
var common = require('../common-tap.js')

var pkg = path.resolve(__dirname, 'npm-global-edit')

var editorSrc = function () {/*
#!/usr/bin/env node
var fs = require('fs')
if (fs.existsSync(process.argv[2])) {
  console.log('success')
} else {
  console.log('error')
  process.exit(1)
}
*/}.toString().split('\n').slice(1, -1).join('\n')
var editorPath = path.join(pkg, 'editor')

test('setup', function (t) {
  cleanup(function (er) {
    t.ifError(er, 'old directory removed')

    mkdirp(pkg, '0777', function (er) {
      fs.writeFileSync(editorPath, editorSrc)
      fs.chmodSync(editorPath, '0777')
      t.ifError(er, 'created package directory correctly')
      t.end()
    })
  })
})

test('saving configs', function (t) {
  var opts = {
    cwd: pkg,
    env: {
      PATH: process.env.PATH,
      EDITOR: editorPath
    }
  }
  common.npm(
    [
      'config',
      '--prefix', pkg,
      '--global',
      'edit'
    ],
    opts,
    function (err, code, stdout, stderr) {
      t.ifError(err, 'command ran without issue')

      t.equal(stderr, '', 'got nothing on stderr')
      t.equal(code, 0, 'exit ok')
      t.equal(stdout, 'success\n', 'got success message')
      t.end()
    }
  )
})

test('cleanup', function (t) {
  cleanup(function (er) {
    t.ifError(er, 'test directory removed OK')
    t.end()
  })
})

function cleanup (cb) {
  rimraf(pkg, cb)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package org.apache.commons.collections4.set (Apache Commons Collections 4.0 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.commons.collections4.set

Packages that use org.apache.commons.collections4.set

Package
Description

org.apache.commons.collections4.map

This package contains implementations of the Map,
 IterableMap,
 OrderedMap and
 SortedMap interfaces.

org.apache.commons.collections4.set

This package contains implementations of the Set and
 SortedSet interfaces.

Classes in org.apache.commons.collections4.set used by org.apache.commons.collections4.map

Class and Description

AbstractSetDecorator

Decorates another Set to provide additional behaviour.

Classes in org.apache.commons.collections4.set used by org.apache.commons.collections4.set

Class and Description

AbstractSerializableSetDecorator

Serializable subclass of AbstractSetDecorator.

AbstractSetDecorator

Decorates another Set to provide additional behaviour.

AbstractSortedSetDecorator

Decorates another SortedSet to provide additional behaviour.

CompositeSet

Decorates a set of other sets to provide a single unified view.

CompositeSet.SetMutator

Define callbacks for mutation operations.

ListOrderedSet

Decorates another Set to ensure that the order of addition is
 retained and used by the iterator.

MapBackedSet

Decorates a Map to obtain Set behaviour.

PredicatedSet

Decorates another Set to validate that all additions
 match a specified predicate.

PredicatedSortedSet

Decorates another SortedSet to validate that all additions
 match a specified predicate.

TransformedSet

Decorates another Set to transform objects that are added.

TransformedSortedSet

Decorates another SortedSet to transform objects that are added.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001–2013 The Apache Software Foundation. All rights reserved.


text:
<?php

namespace Clue\Tests\React\Socks;

class TestCase extends \PHPUnit\Framework\TestCase
{
    protected function expectCallableOnce()
    {
        $mock = $this->createCallableMock();

        $mock
            ->expects($this->once())
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableOnceWith($arg)
    {
        $mock = $this->createCallableMock();

        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($arg);

        return $mock;
    }

    protected function expectCallableNever()
    {
        $mock = $this->createCallableMock();
        $mock
            ->expects($this->never())
            ->method('__invoke');

        return $mock;
    }

    protected function expectCallableOnceWithException($class, $message, $code)
    {
        return $this->expectCallableOnceWith($this->logicalAnd(
            $this->isInstanceOf($class),
            $this->callback(function (\Exception $e) use ($message, $code) {
                return strpos($e->getMessage(), $message) !== false && $e->getCode() === $code;
            })
        ));
    }

    /**
     * @link https://github.com/reactphp/react/blob/master/tests/React/Tests/Socket/TestCase.php (taken from reactphp/react)
     */
    protected function createCallableMock()
    {
        return $this->getMockBuilder('stdClass')->setMethods(array('__invoke'))->getMock();
    }

    protected function expectPromiseResolve($promise)
    {
        $this->assertInstanceOf('React\Promise\PromiseInterface', $promise);

        $that = $this;
        $promise->then(null, function($error) use ($that) {
            $that->assertNull($error);
            $that->fail('promise rejected');
        });
        $promise->then($this->expectCallableOnce(), $this->expectCallableNever());

        return $promise;
    }

    protected function expectPromiseReject($promise)
    {
        $this->assertInstanceOf('React\Promise\PromiseInterface', $promise);

        $that = $this;
        $promise->then(function($value) use ($that) {
            $that->assertNull($value);
            $that->fail('promise resolved');
        });

        $promise->then($this->expectCallableNever(), $this->expectCallableOnce());

        return $promise;
    }

    public function setExpectedException($exception, $message = '', $code = 0)
    {
        if (method_exists($this, 'expectException')) {
            $this->expectException($exception);
            if ($message !== '') {
                $this->expectExceptionMessage($message);
            }
            $this->expectExceptionCode($code);
        } else {
            parent::setExpectedException($exception, $message, $code);
        }
    }
}


text:
using CssColorExtractor.Core.Map;

namespace CssColorExtractor.Core.Generator
{
	public interface IGenerator
	{
		string GenerateColorsList(IColorsMap colorsMap);

		string UpdateStylesheets(IColorsMap colorsMap, string source);
	}
}


text:
define(function (require, exports, module) {
  var Templates = require('app/resources/Templates');
  var BasicView = require('app/view/View');
  var BasicModel = require('app/model/Model');
  var UserModel = require('app/model/UserModel');

  function UserView() {
    this.models = {
      Basic: BasicModel,
      User: UserModel
    }
    this.viewCls = 'view-user';
    this._BasicView = BasicView;

    var VIEW = this,
      isApp = Core.NativeBridge.isApp(),
      Tpl, els,
      tap = VIEW._BasicView.tapEvent;

    //注册model观察者
    VIEW.models.User.user.updated(render);

    function initEls() {
      if (els) {
        return;
      }
      var main = $('.view-user');
      els = {
        //body: $('body'),
        main: main,

        list: main.find('.list'),
        back: main.find('.back')
      }
      bindEvent();
    }//end initEls
    function initResources() {
      Tpl = new Templates.User;
      initEls();
    }

    this.getEls = function () {
      return els;
    }
    function bindEvent() {
      els.back.on(tap, Core.Router.back);
    }//end bindEvent

    this.show = function () {
      initResources();

      VIEW._BasicView.show(VIEW.viewCls);
    }
    this.hide = function () {
      if (!els) {
        return;
      }
    }
    function render(data) {
      initResources();

      data = data || VIEW.models.User.user.get();

      if (!data || !data.length) {
        return;
      }

      var list = [];
      data.forEach(function (key, index) {
        list.push(Tpl.list.item(key));
      });
      els.list.html(list.join(''));
      list = null;
    }//end render

  }//end View
  return new UserView();
});


text:
package org.opendatakraken.core.db;

public class SchemaCopier {

    // Declarations of bean properties
	// Source properties
    private DBConnection sourceCon = null;
    private String sourceSchema = "";

}


text:
BEGIN { FIELDWIDTHS = "9" } # ColHeaders:  Datatype
NR>1 {
   field_name=$1
   sub(/^  */, "", field_name)   # strip leading spaces
   sub(/ *$/, "", field_name)   # strip trailing spaces
   print field_name;
}


text:
require "helper"
require "jobs/hello_job"
require "jobs/enqueue_error_job"
require "active_support/core_ext/numeric/time"

class QueuingTest < ActiveSupport::TestCase
  setup do
    JobBuffer.clear
  end

  test "run queued job" do
    HelloJob.perform_later
    assert_equal "David says hello", JobBuffer.last_value
  end

  test "run queued job with arguments" do
    HelloJob.perform_later "Jamie"
    assert_equal "Jamie says hello", JobBuffer.last_value
  end

  test "run queued job later" do
    result = HelloJob.set(wait_until: 1.second.ago).perform_later "Jamie"
    assert result
  rescue NotImplementedError
    skip
  end

  test "job returned by enqueue has the arguments available" do
    job = HelloJob.perform_later "Jamie"
    assert_equal [ "Jamie" ], job.arguments
  end

  test "job returned by perform_at has the timestamp available" do
    job = HelloJob.set(wait_until: Time.utc(2014, 1, 1)).perform_later
    assert_equal Time.utc(2014, 1, 1).to_f, job.scheduled_at
  rescue NotImplementedError
    skip
  end

  test "job is yielded to block after enqueue with successfully_enqueued property set" do
    HelloJob.perform_later "John" do |job|
      assert_equal "John says hello", JobBuffer.last_value
      assert_equal [ "John" ], job.arguments
      assert_equal true, job.successfully_enqueued?
      assert_nil job.enqueue_error
    end
  end

  test "when enqueuing raises an EnqueueError job is yielded to block with error set on job" do
    EnqueueErrorJob.perform_later do |job|
      assert_equal false, job.successfully_enqueued?
      assert_equal ActiveJob::EnqueueError, job.enqueue_error.class
    end
  end
end


text:
package com.intellij.util.indexing.impl.forward;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.io.ByteArraySequence;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.*;
import com.intellij.util.indexing.impl.*;
import com.intellij.util.io.VoidDataExternalizer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

public class SingleEntryIndexForwardIndexAccessor<V> extends AbstractMapForwardIndexAccessor<Integer, V, Void> {
  private static final Logger LOG = Logger.getInstance(SingleEntryIndexForwardIndexAccessor.class);
  private final NotNullLazyValue<UpdatableIndex<Integer, V, ?>> myIndex;

  @SuppressWarnings("unchecked")
  public SingleEntryIndexForwardIndexAccessor(IndexExtension<Integer, V, ?> extension) {
    super(VoidDataExternalizer.INSTANCE);
    LOG.assertTrue(extension instanceof SingleEntryFileBasedIndexExtension);
    IndexId<?, ?> name = extension.getName();
    FileBasedIndexEx fileBasedIndex = (FileBasedIndexEx)FileBasedIndex.getInstance();
    myIndex = NotNullLazyValue.volatileLazy(() -> fileBasedIndex.getIndex((ID<Integer, V>)name));
  }

  @NotNull
  @Override
  public final InputDataDiffBuilder<Integer, V> getDiffBuilder(int inputId, @Nullable ByteArraySequence sequence) throws IOException {
    Map<Integer, V> data;
    try {
      data = ProgressManager.getInstance().computeInNonCancelableSection(() -> myIndex.getValue().getIndexedFileData(inputId));
    }
    catch (StorageException e) {
      throw new IOException(e);
    }
    return createDiffBuilderByMap(inputId, data);
  }

  @Nullable
  @Override
  public Void convertToDataType(@NotNull InputData<Integer, V> data) {
    return null;
  }

  @Override
  public @NotNull InputDataDiffBuilder<Integer, V> createDiffBuilderByMap(int inputId, @Nullable Map<Integer, V> map) throws IOException {
    return new SingleValueDiffBuilder<>(inputId, ContainerUtil.notNullize(map));
  }

  @Nullable
  @Override
  public final ByteArraySequence serializeIndexedData(@NotNull InputData<Integer, V> data) {
    return null;
  }

  @Override
  protected @Nullable Map<Integer, V> convertToMap(int inputId, @Nullable Void inputData) throws IOException {
    try {
      return ProgressManager.getInstance().computeInNonCancelableSection(() -> myIndex.getValue().getIndexedFileData(inputId));
    }
    catch (StorageException e) {
      throw new IOException(e);
    }
  }

  public static class SingleValueDiffBuilder<V> extends DirectInputDataDiffBuilder<Integer, V> {
    private final boolean myContainsValue;
    @Nullable
    private final V myCurrentValue;

    public SingleValueDiffBuilder(int inputId, @NotNull Map<Integer, V> currentData) {
      this(inputId, !currentData.isEmpty(), ContainerUtil.getFirstItem(currentData.values()));
    }

    private SingleValueDiffBuilder(int inputId, boolean containsValue, @Nullable V currentValue) {
      super(inputId);
      myContainsValue = containsValue;
      myCurrentValue = currentValue;
    }

    @Override
    public @NotNull Collection<Integer> getKeys() {
      return myContainsValue ? Collections.singleton(myInputId) : Collections.emptySet();
    }

    @Override
    public boolean differentiate(@NotNull Map<Integer, V> newData,
                                 @NotNull KeyValueUpdateProcessor<? super Integer, ? super V> addProcessor,
                                 @NotNull KeyValueUpdateProcessor<? super Integer, ? super V> updateProcessor,
                                 @NotNull RemovedKeyProcessor<? super Integer> removeProcessor) throws StorageException {
      boolean newValueExists = !newData.isEmpty();
      V newValue = ContainerUtil.getFirstItem(newData.values());
      if (myContainsValue) {
        if (!newValueExists) {
          removeProcessor.process(myInputId, myInputId);
          return true;
        } else if (Comparing.equal(myCurrentValue, newValue)) {
          return false;
        } else {
          updateProcessor.process(myInputId, newValue, myInputId);
          return true;
        }
      } else {
        if (newValueExists) {
          addProcessor.process(myInputId, newValue, myInputId);
          return true;
        } else {
          return false;
        }
      }
    }
  }
}


text: twistd --pidfile=server.pid -ny server.tac


text:
function g = netgrad(w, net, x, t)
%NETGRAD Evaluate network error gradient for generic optimizers
%
%	Description
%
%	G = NETGRAD(W, NET, X, T) takes a weight vector W and a network data
%	structure NET, together with the matrix X of input vectors and the
%	matrix T of target vectors, and returns the gradient of the error
%	function evaluated at W.
%
%	See also
%	MLP, NETERR, NETOPT
%

%	Copyright (c) Ian T Nabney (1996-2001)

gradstr = [net.type, 'grad'];

net = netunpak(net, w);

g = feval(gradstr, net, x, t);

end


text:
@interface PTBaseTableCell : UITableViewCell

@end


text:
module.exports = {
    webElements: {
        lblMsg: function () {
            return element(by.xpath("html/body/center/table/tbody/tr[3]/td/table/tbody/tr/td[2]/p"));
        }
    },

    getMessage: function () {
        return this.webElements.lblMsg().getText();
    }
};


text:
// +build !test_no_exec

package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/docker/docker/pkg/integration/checker"
	"github.com/go-check/check"
)

func (s *DockerSuite) TestCliExecBasic(c *check.C) {
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	pullImageIfNotExist("busybox")
	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "sh", "-c", "echo test > /tmp/file && top")

	out, _ := dockerCmd(c, "exec", "test", "cat", "/tmp/file")
	out = strings.Trim(out, "\r\n")
	c.Assert(out, checker.Equals, "test")

}

//TODO:FIX ExecInteractive WAITING TOO LONG
/*func (s *DockerSuite) TestCliExecInteractive(c *check.C) {
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "sh", "-c", "echo test > /tmp/file && top")

	execCmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", "-i", "test", "sh")
	stdin, err := execCmd.StdinPipe()
	c.Assert(err, checker.IsNil)
	stdout, err := execCmd.StdoutPipe()
	c.Assert(err, checker.IsNil)

	err = execCmd.Start()
	c.Assert(err, checker.IsNil)
	_, err = stdin.Write([]byte("cat /tmp/file\n"))
	c.Assert(err, checker.IsNil)

	r := bufio.NewReader(stdout)
	line, err := r.ReadString('\n')
	c.Assert(err, checker.IsNil)
	line = strings.TrimSpace(line)
	c.Assert(line, checker.Equals, "test")
	err = stdin.Close()
	c.Assert(err, checker.IsNil)
	errChan := make(chan error)
	go func() {
		errChan <- execCmd.Wait()
		close(errChan)
	}()
	select {
	case err := <-errChan:
		c.Assert(err, checker.IsNil)
	case <-time.After(10 * time.Second):
		c.Fatal("docker exec failed to exit on stdin close")
	}
}*/

func (s *DockerSuite) TestCliExecAfterContainerRestart(c *check.C) {
	printTestCaseName()
	defer printTestDuration(time.Now())

	pullImageIfNotExist("busybox")
	out, _ := runSleepingContainer(c, "-d")
	cleanedContainerID := strings.TrimSpace(out)
	c.Assert(waitRun(cleanedContainerID), check.IsNil)
	dockerCmd(c, "restart", cleanedContainerID)
	c.Assert(waitRun(cleanedContainerID), check.IsNil)

	out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello")
	outStr := strings.TrimSpace(out)
	c.Assert(outStr, checker.Equals, "hello")
}

//TODO:FIX TestExecEnv WAITING TOO LONG
/*func (s *DockerSuite) TestCliExecEnv(c *check.C) {
	// TODO Windows CI: This one is interesting and may just end up being a feature
	// difference between Windows and Linux. On Windows, the environment is passed
	// into the process that is launched, not into the machine environment. Hence
	// a subsequent exec will not have LALA set/
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	runSleepingContainer(c, "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "test")
	c.Assert(waitRun("test"), check.IsNil)

	out, _ := dockerCmd(c, "exec", "test", "env")
	c.Assert(out, checker.Not(checker.Contains), "LALA=value1")
	c.Assert(out, checker.Contains, "LALA=value2")
	c.Assert(out, checker.Contains, "HOME=/root")
}*/

func (s *DockerSuite) TestCliExecExitStatus(c *check.C) {
	printTestCaseName()
	defer printTestDuration(time.Now())

	runSleepingContainer(c, "-d", "--name", "top")

	// Test normal (non-detached) case first
	cmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", "top", "sh", "-c", "exit 23")
	ec, _ := runCommand(cmd)
	c.Assert(ec, checker.Equals, 23)
}

//TODO:FIX TestExecTTYCloseStdin WAITING TOO LONG SAME AS TestExecInteractive
/*func (s *DockerSuite) TestCliExecTTYCloseStdin(c *check.C) {
	// TODO Windows CI: This requires some work to port to Windows.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "-it", "--name", "test", "busybox")

	cmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", "-i", "test", "cat")
	stdinRw, err := cmd.StdinPipe()
	c.Assert(err, checker.IsNil)

	stdinRw.Write([]byte("test"))
	stdinRw.Close()

	out, _, err := runCommandWithOutput(cmd)
	c.Assert(err, checker.IsNil, check.Commentf(out))

	out, _ = dockerCmd(c, "top", "test")
	outArr := strings.Split(out, "\n")
	c.Assert(len(outArr), checker.LessOrEqualThan, 3, check.Commentf("exec process left running"))
	c.Assert(out, checker.Not(checker.Contains), "nsenter-exec")
}*/

func (s *DockerSuite) TestCliExecTTYWithoutStdin(c *check.C) {
	// TODO Windows CI: This requires some work to port to Windows.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	pullImageIfNotExist("busybox")
	out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox")
	id := strings.TrimSpace(out)
	c.Assert(waitRun(id), checker.IsNil)

	errChan := make(chan error)
	go func() {
		defer close(errChan)

		cmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", "-ti", id, "true")
		if _, err := cmd.StdinPipe(); err != nil {
			errChan <- err
			return
		}

		expected := "cannot enable tty mode"
		if out, _, err := runCommandWithOutput(cmd); err == nil {
			errChan <- fmt.Errorf("exec should have failed")
			return
		} else if !strings.Contains(out, expected) {
			errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected)
			return
		}
	}()

	select {
	case err := <-errChan:
		c.Assert(err, check.IsNil)
	case <-time.After(30 * time.Second):
		c.Fatal("exec is running but should have failed")
	}
}

func (s *DockerSuite) TestCliExecParseError(c *check.C) {
	// TODO Windows CI: Requires some extra work. Consider copying the
	// runSleepingContainer helper to have an exec version.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top")

	// Test normal (non-detached) case first
	cmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", "top")
	_, stderr, _, err := runCommandWithStdoutStderr(cmd)
	c.Assert(err, checker.NotNil)
	c.Assert(stderr, checker.Contains, "See '"+dockerBinary+" exec --help'")
}

func (s *DockerSuite) TestCliExecStopNotHanging(c *check.C) {
	// TODO Windows CI: Requires some extra work. Consider copying the
	// runSleepingContainer helper to have an exec version.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")

	err := exec.Command(dockerBinary, "exec", "--region="+os.Getenv("DOCKER_HOST"), "test", "top").Start()
	c.Assert(err, checker.IsNil)

	type dstop struct {
		out []byte
		err error
	}

	ch := make(chan dstop)
	go func() {
		out, err := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "stop", "test").CombinedOutput()
		ch <- dstop{out, err}
		close(ch)
	}()
	select {
	case <-time.After(30 * time.Second):
		c.Fatal("Container stop timed out")
	case s := <-ch:
		c.Assert(s.err, check.IsNil)
	}
}

func (s *DockerSuite) TestCliExecCgroup(c *check.C) {
	// Not applicable on Windows - using Linux specific functionality
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, NotUserNamespace)
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")

	out, _ := dockerCmd(c, "exec", "test", "cat", "/proc/1/cgroup")
	containerCgroups := sort.StringSlice(strings.Split(out, "\n"))

	var wg sync.WaitGroup
	var mu sync.Mutex
	execCgroups := []sort.StringSlice{}
	errChan := make(chan error)
	// exec a few times concurrently to get consistent failure
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			out, _, err := dockerCmdWithError("exec", "test", "cat", "/proc/self/cgroup")
			if err != nil {
				errChan <- err
				return
			}
			cg := sort.StringSlice(strings.Split(out, "\n"))

			mu.Lock()
			execCgroups = append(execCgroups, cg)
			mu.Unlock()
			wg.Done()
		}()
	}
	wg.Wait()
	close(errChan)

	for err := range errChan {
		c.Assert(err, checker.IsNil)
	}

	for _, cg := range execCgroups {
		if !reflect.DeepEqual(cg, containerCgroups) {
			fmt.Println("exec cgroups:")
			for _, name := range cg {
				fmt.Printf(" %s\n", name)
			}

			fmt.Println("container cgroups:")
			for _, name := range containerCgroups {
				fmt.Printf(" %s\n", name)
			}
			c.Fatal("cgroups mismatched")
		}
	}
}

func (s *DockerSuite) TestCliExecLinksPingLinkedContainersOnRename(c *check.C) {
	// Problematic on Windows as Windows does not support links
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	pullImageIfNotExist("busybox")
	var out string
	out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
	idA := strings.TrimSpace(out)
	c.Assert(idA, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", out))
	out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top")
	idB := strings.TrimSpace(out)
	c.Assert(idB, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", out))

	dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
	dockerCmd(c, "rename", "container1", "container-new")
	dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1")
}

func (s *DockerSuite) TestCliExecDir(c *check.C) {
	// TODO Windows CI. This requires some work to port as it uses execDriverPath
	// which is currently (and incorrectly) hard coded as a string assuming
	// the daemon is running Linux :(
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, SameHostDaemon, DaemonIsLinux)

	out, _ := runSleepingContainer(c, "-d")
	id := strings.TrimSpace(out)

	execDir := filepath.Join(execDriverPath, id)
	stateFile := filepath.Join(execDir, "state.json")

	{
		fi, err := os.Stat(execDir)
		c.Assert(err, checker.IsNil)
		if !fi.IsDir() {
			c.Fatalf("%q must be a directory", execDir)
		}
		fi, err = os.Stat(stateFile)
		c.Assert(err, checker.IsNil)
	}

	dockerCmd(c, "stop", id)
	{
		_, err := os.Stat(execDir)
		c.Assert(err, checker.NotNil)
		c.Assert(err, checker.NotNil, check.Commentf("Exec directory %q exists for removed container!", execDir))
		if !os.IsNotExist(err) {
			c.Fatalf("Error should be about non-existing, got %s", err)
		}
	}
	dockerCmd(c, "start", id)
	{
		fi, err := os.Stat(execDir)
		c.Assert(err, checker.IsNil)
		if !fi.IsDir() {
			c.Fatalf("%q must be a directory", execDir)
		}
		fi, err = os.Stat(stateFile)
		c.Assert(err, checker.IsNil)
	}
	dockerCmd(c, "rm", "-f", id)
	{
		_, err := os.Stat(execDir)
		c.Assert(err, checker.NotNil, check.Commentf("Exec directory %q exists for removed container!", execDir))
		if !os.IsNotExist(err) {
			c.Fatalf("Error should be about non-existing, got %s", err)
		}
	}
}

func (s *DockerSuite) TestCliExecRunMutableNetworkFiles(c *check.C) {
	// Not applicable on Windows to Windows CI.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, SameHostDaemon, DaemonIsLinux)
	pullImageIfNotExist("busybox")
	for _, fn := range []string{"resolv.conf", "hosts"} {
		deleteAllContainers()

		content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn)))
		c.Assert(err, checker.IsNil)

		c.Assert(strings.TrimSpace(string(content)), checker.Equals, "success", check.Commentf("Content was not what was modified in the container", string(content)))

		out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top")
		contID := strings.TrimSpace(out)
		netFilePath := containerStorageFile(contID, fn)

		f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
		c.Assert(err, checker.IsNil)

		if _, err := f.Seek(0, 0); err != nil {
			f.Close()
			c.Fatal(err)
		}

		if err := f.Truncate(0); err != nil {
			f.Close()
			c.Fatal(err)
		}

		if _, err := f.Write([]byte("success2\n")); err != nil {
			f.Close()
			c.Fatal(err)
		}
		f.Close()

		res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn)
		c.Assert(res, checker.Equals, "success2\n")
	}
}

func (s *DockerSuite) TestCliExecStartFails(c *check.C) {
	// TODO Windows CI. This test should be portable. Figure out why it fails
	// currently.
	printTestCaseName()
	defer printTestDuration(time.Now())

	testRequires(c, DaemonIsLinux)
	name := "exec-15750"
	runSleepingContainer(c, "-d", "--name", name)
	c.Assert(waitRun(name), checker.IsNil)

	out, _, err := dockerCmdWithError("exec", name, "no-such-cmd")
	c.Assert(err, checker.NotNil, check.Commentf(out))
	c.Assert(out, checker.Contains, "exec failed: No such file or directory")
}

func (s *DockerSuite) TestCliExecInspectID(c *check.C) {
	printTestCaseName()
	defer printTestDuration(time.Now())

	pullImageIfNotExist("busybox")
	out, _ := runSleepingContainer(c, "-d")
	id := strings.TrimSuffix(out, "\n")

	out = inspectField(c, id, "ExecIDs")
	c.Assert(out, checker.Equals, "[]", check.Commentf("ExecIDs should be empty, got: %s", out))

	// Start an exec, have it block waiting so we can do some checking
	cmd := exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", id, "sh", "-c",
		"while ! test -e /execid1; do sleep 1; done")

	err := cmd.Start()
	c.Assert(err, checker.IsNil, check.Commentf("failed to start the exec cmd"))

	// Give the exec 10 chances/seconds to start then give up and stop the test
	tries := 10
	for i := 0; i < tries; i++ {
		// Since its still running we should see exec as part of the container
		out = strings.TrimSpace(inspectField(c, id, "ExecIDs"))

		if out != "[]" && out != "<no value>" {
			break
		}
		c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still empty after 10 second"))
		time.Sleep(1 * time.Second)
	}

	// Save execID for later
	execID, err := inspectFilter(id, "index .ExecIDs 0")
	c.Assert(err, checker.IsNil, check.Commentf("failed to get the exec id"))

	// End the exec by creating the missing file
	err = exec.Command(dockerBinary, "--region="+os.Getenv("DOCKER_HOST"), "exec", id,
		"sh", "-c", "touch /execid1").Run()

	c.Assert(err, checker.IsNil, check.Commentf("failed to run the 2nd exec cmd"))

	// Wait for 1st exec to complete
	cmd.Wait()

	// Give the exec 10 chances/seconds to stop then give up and stop the test
	for i := 0; i < tries; i++ {
		// Since its still running we should see exec as part of the container
		out = strings.TrimSpace(inspectField(c, id, "ExecIDs"))

		if out == "[]" {
			break
		}
		c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still not empty after 10 second"))
		time.Sleep(1 * time.Second)
	}

	// But we should still be able to query the execID
	sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil)
	c.Assert(sc, checker.Equals, http.StatusOK, check.Commentf("received status != 200 OK: %d\n%s", sc, body))

	//TODO: fix receive 500
	// Now delete the container and then an 'inspect' on the exec should
	// result in a 404 (not 'container not running')
	/*out, ec := dockerCmd(c, "rm", "-f", id)
	c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out))
	sc, body, err = sockRequest("GET", "/exec/"+execID+"/json", nil)
	c.Assert(sc, checker.Equals, http.StatusNotFound, check.Commentf("received status != 404: %d\n%s", sc, body))*/
}


text:
PANEL = 'ec2'
# The slug of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'aws'
# The slug of the panel group the PANEL is associated with.
PANEL_GROUP = 'compute'

# Python panel class of the PANEL to be added.
ADD_PANEL = 'aws_dashboard.content.aws.access_and_security.panel.AccessAndSecurity'


text:
.. _build/messages/226:

========================================================================================
226 - missingProfile
========================================================================================

:Message Number: 226
:Message: missingProfile
:Text: A package without a profile could throw errors or warnings.
:Type: Warning


text:
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');

var RelayRequest = require('tchannel/relay_handler').RelayRequest;

module.exports = RingpopHandler;

function RingpopHandler(options) {
    /*eslint max-statements: [2, 25]*/
    if (!(this instanceof RingpopHandler)) {
        return new RingpopHandler(options);
    }

    var self = this;

    self.realHandler = options.realHandler;
    assert(
        typeof self.realHandler === 'object',
        'expected options.realHandler'
    );

    self.ringpop = options.ringpop;
    assert(typeof self.ringpop === 'object', 'expected options.ringpop');

    self.channel = options.channel;
    assert(typeof self.channel === 'object', 'expected options.channel');

    self.logger = options.logger;
    assert(typeof self.logger === 'object', 'expected options.logger');

    // Blacklist of methods that will not be 'auto-sharded' but instead will
    // be passed thru to the handler. Object mapping names to boolean.
    self.blacklist = options.blacklist || null;
    if (self.blacklist) {
        assert(
            typeof self.blacklist === 'object',
            'expected options.blacklist to be an object'
        );

        var blackListKeys = Object.keys(self.blacklist);
        for (var i = 0; i < blackListKeys.length; i++) {
            var key = blackListKeys[i];
            assert(typeof self.blacklist[key] === 'boolean',
                'expected options.blacklist item to be boolean'
            );
        }
    }
}

RingpopHandler.prototype.type = 'tchannel.endpoint-handler';

RingpopHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;

    if (self.blacklist && self.blacklist[req.endpoint]) {
        return self.realHandler.handleRequest(req, buildRes);
    }

    var shardKey = req.headers.sk;
    if (!shardKey) {
        self.logger.warn('Ringpop got request without a shardKey', {
            socketRemoteAddr: req.remoteAddr,
            serviceName: req.serviceName,
            endpoint: req.endpoint,
            callerName: req.headers.cn,
            headers: req.headers,
            local: self.ringpop.whoami()
        });
        return buildRes().sendError(
            'BadRequest',
            '[ringpop] Request does not have sk header set'
        );
    }

    var dest = self.resolveHost(shardKey);
    if (self.ringpop.whoami() === dest) {
        return self.realHandler.handleRequest(req, buildRes);
    }

    var peer = self.channel.peers.add(dest);
    var outreq = new RelayRequest(self.channel, peer, req, buildRes);
    outreq.createOutRequest();
};

RingpopHandler.prototype.resolveHost =
function resolveHost(shardKey) {
    var self = this;

    return self.ringpop.lookup(shardKey);
};

RingpopHandler.prototype.register = function register(arg1, fn) {
    var self = this;

    self.realHandler.register(arg1, fn);
};


text:
W, H = display.contentWidth, display.contentHeight

-- startup the physics engine
local physics = require("physics")
physics.start()

-- load sounds
local wheee = audio.loadSound("wheee.wav")
local ouch = audio.loadSound("ouch.wav")
local gotcha = audio.loadSound("gotcha.wav")

-- sky background
local sky = display.newImageRect("sky.jpg", W, H)
sky.x, sky.y = W/2, H/2

-- draw a circle
local circle = display.newImageRect( "ms_lura.png", 40, 40 )
circle.x, circle.y = 100, H/2
physics.addBody(circle, "dynamic", {radius=20, density=0.5, friction=1, bounce=0.35})

-- draw a floor
local floor = display.newImageRect("grass.jpg", W, 30)
floor.x, floor.y = W/2, H-15
physics.addBody(floor, "static", {density=1.0, friction=1, bounce=0.65})

-- touch event for the circle to kick the ball
function circle:touch(event)
	if (event.phase == "began") then
		self:applyLinearImpulse(10, -5, self.x, self.y)
		audio.play(wheee)
	end
end
circle:addEventListener("touch", circle)

-- make some blocks to knock down
for i=1, 4 do
	local block = display.newImageRect("crate.jpg", 30, 30)
	block.x, block.y = W-100, H-30-30*i
	physics.addBody(block, "dynamic", {density=0.5, friction=1, bounce=0.35})
end

for i=1, 4 do
	local block = display.newImageRect("crate.jpg", 30, 30)
	block.x, block.y = W-200, H-30-30*i
	physics.addBody(block, "dynamic", {density=0.5, friction=1, bounce=0.35})
end

-- add a roof
local roof = display.newImageRect("crate.jpg", 130, 20)
roof.x, roof.y = W-150, H-300
physics.addBody(roof, "dynamic")

-- add a target circle
local target = display.newImageRect( "ms_lanzot.png", 60, 60 )
target.x, target.y = W-150, H-100
physics.addBody(target, "dynamic", {radius=30, density=0.5, friction=1, bounce=0.35})

-- ouch on collision with target
function onCollision(event)
	if (event.phase == "began") then
		if (event.object1 == circle and event.object2 == target) then
			audio.play(gotcha)
		end
		if (event.object1 ~= circle and event.object1 ~= floor and event.object2 == target) then
			audio.play(ouch)
		end
	end
end
Runtime:addEventListener("collision", onCollision);


text:
package org.apache.commons.math4.legacy.ode.nonstiff;

import org.apache.commons.math4.legacy.ode.sampling.StepInterpolator;

/**
 * This class implements a step interpolator for the classical fourth
 * order Runge-Kutta integrator.
 *
 *
This interpolator allows to compute dense output inside the last
 * step computed. The interpolation equation is consistent with the
 * integration scheme :
 *

 *
Using reference point at step start:

 *   y(tn + θ h) = y (tn)
 *                    + θ (h/6) [  (6 - 9 θ + 4 θ2) y'1
 *                                     + (    6 θ - 4 θ2) (y'2 + y'3)
 *                                     + (   -3 θ + 4 θ2) y'4
 *                                    ]
 *

 *
Using reference point at step end:

 *   y(tn + θ h) = y (tn + h)
 *                    + (1 - θ) (h/6) [ (-4 θ^2 + 5 θ - 1) y'1
 *                                          +(4 θ^2 - 2 θ - 2) (y'2 + y'3)
 *                                          -(4 θ^2 +   θ + 1) y'4
 *                                        ]
 *

 *

 *
 * where θ belongs to [0 ; 1] and where y'1 to y'4 are the four
 * evaluations of the derivatives already computed during the
 * step.
 *
 * @see ClassicalRungeKuttaIntegrator
 * @since 1.2
 */

class ClassicalRungeKuttaStepInterpolator
    extends RungeKuttaStepInterpolator {

    /** Serializable version identifier. */
    private static final long serialVersionUID = 20111120L;

    /** Simple constructor.
     * This constructor builds an instance that is not usable yet, the
     * {@link RungeKuttaStepInterpolator#reinitialize} method should be
     * called before using the instance in order to initialize the
     * internal arrays. This constructor is used only in order to delay
     * the initialization in some cases. The {@link RungeKuttaIntegrator}
     * class uses the prototyping design pattern to create the step
     * interpolators by cloning an uninitialized model and latter initializing
     * the copy.
     */
    // CHECKSTYLE: stop RedundantModifier
    // the public modifier here is needed for serialization
    public ClassicalRungeKuttaStepInterpolator() {
    }
    // CHECKSTYLE: resume RedundantModifier

    /** Copy constructor.
     * @param interpolator interpolator to copy from. The copy is a deep
     * copy: its arrays are separated from the original arrays of the
     * instance
     */
    ClassicalRungeKuttaStepInterpolator(final ClassicalRungeKuttaStepInterpolator interpolator) {
        super(interpolator);
    }

    /** {@inheritDoc} */
    @Override
    protected StepInterpolator doCopy() {
        return new ClassicalRungeKuttaStepInterpolator(this);
    }

    /** {@inheritDoc} */
    @Override
    protected void computeInterpolatedStateAndDerivatives(final double theta,
                                            final double oneMinusThetaH) {

        final double oneMinusTheta  = 1 - theta;
        final double oneMinus2Theta = 1 - 2 * theta;
        final double coeffDot1     = oneMinusTheta * oneMinus2Theta;
        final double coeffDot23    = 2 * theta * oneMinusTheta;
        final double coeffDot4     = -theta * oneMinus2Theta;
        if (previousState != null && theta <= 0.5) {
            final double fourTheta2     = 4 * theta * theta;
            final double s             = theta * h / 6.0;
            final double coeff1        = s * ( 6 - 9 * theta + fourTheta2);
            final double coeff23       = s * ( 6 * theta - fourTheta2);
            final double coeff4        = s * (-3 * theta + fourTheta2);
            for (int i = 0; i < interpolatedState.length; ++i) {
                final double yDot1  = yDotK[0][i];
                final double yDot23 = yDotK[1][i] + yDotK[2][i];
                final double yDot4  = yDotK[3][i];
                interpolatedState[i] =
                        previousState[i] + coeff1  * yDot1 + coeff23 * yDot23 + coeff4  * yDot4;
                interpolatedDerivatives[i] =
                        coeffDot1 * yDot1 + coeffDot23 * yDot23 + coeffDot4 * yDot4;
            }
        } else {
            final double fourTheta      = 4 * theta;
            final double s             = oneMinusThetaH / 6.0;
            final double coeff1        = s * ((-fourTheta + 5) * theta - 1);
            final double coeff23       = s * (( fourTheta - 2) * theta - 2);
            final double coeff4        = s * ((-fourTheta - 1) * theta - 1);
            for (int i = 0; i < interpolatedState.length; ++i) {
                final double yDot1  = yDotK[0][i];
                final double yDot23 = yDotK[1][i] + yDotK[2][i];
                final double yDot4  = yDotK[3][i];
                interpolatedState[i] =
                        currentState[i] + coeff1  * yDot1 + coeff23 * yDot23 + coeff4  * yDot4;
                interpolatedDerivatives[i] =
                        coeffDot1 * yDot1 + coeffDot23 * yDot23 + coeffDot4 * yDot4;
            }
        }
    }
}


text:
package org.ovirt.engine.core.common.businessentities;

import java.util.HashMap;
import java.util.Map;

public enum VmPauseStatus {
    NONE(0),
    EOTHER(1),
    EIO(2),
    ENOSPC(3),
    EPERM(4),
    NOERR(5);

    private static Map<Integer, VmPauseStatus> mappings = new HashMap<Integer, VmPauseStatus>();
    private int value;

    static {
        mappings = new HashMap<Integer, VmPauseStatus>();
        mappings.put(0, NONE);
        mappings.put(1, EOTHER);
        mappings.put(2, EIO);
        mappings.put(3, ENOSPC);
        mappings.put(4, EPERM);
        mappings.put(5, NOERR);
    }

    VmPauseStatus(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public static VmPauseStatus forValue(int value) {
        return mappings.get(value);
    }

}


text:
/*jslint node: true*/
/*jslint expr: true*/
/*global describe, it*/
"use strict";

var should = require('should');
var kaomoji = require('../index');

describe("kaomoji.js", function () {
  it("should return an kaomoji code", function () {
   var lenny = kaomoji.lenny[3];
   should.exist(lenny);
   lenny.should.be.exactly('(^・ω・^ )');
  });
});