text:
// Copyright 2011 Ogilvy & Mather. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Plovr.Configuration;
using Plovr.Helpers;
using Plovr.Model;

namespace Plovr.Modules
{
	internal abstract class Handler
	{
		#region "Properties"

		/// <summary>
		/// The current Http Context.
		/// </summary>
		protected HttpContext Context { get; set; }

		/// <summary>
		/// the id key in the query string
		/// </summary>
		private const string IdQueryStringParam = "id";

		/// <summary>
		/// the mode key in the query string
		/// </summary>
		private const string ModeQueryStringParam = "mode";

		/// <summary>
		/// the current project settings that are loaded
		/// </summary>
		protected IPlovrProject CurrentProject;

		/// <summary>
		/// the current settings for plovr
		/// </summary>
		protected PlovrSettings CurrentSettings;

		/// <summary>
		/// An abstract method, every handler will implement this function and will be called after alll
		/// common pre-processing has occured.
		/// </summary>
		public abstract void Run();

		#endregion

		#region "Static Methods"

		/// <summary>
		/// Create a new instance of the specific route that is, this is a static method.
		/// </summary>
		/// <param name="typeStr">a string representation of the current route</param>
		/// <param name="context">the http context</param>
		/// <returns></returns>
		public static Handler CreateInstance(string typeStr, HttpContext context)
		{
			Type handlerType = Type.GetType(typeStr);

			if (handlerType == null)
			{
				handlerType = Type.GetType("Plovr.Modules.IndexHandler");
			}

			return (Handler)Activator.CreateInstance(handlerType, new object[] { context });

		}

		#endregion

		#region "Common Plovr Functions"

		/// <summary>
		/// Constructor, starts by initalizing the current project and settings properties.
		/// </summary>
		/// <param name="context"></param>
		protected Handler(HttpContext context)
		{
			this.Context = context;

			// get the project configuration and application settings
			this.InitSettings();
		}

		/// <summary>
		/// Using the HttpContext as the current website that is loaded, load the current project and settings.
		/// </summary>
		private void InitSettings()
		{
			this.CurrentSettings = PlovrConfiguration.GetCurrentPlovrSettings();

			// support %JAVA_HOME% env variable
			this.CurrentSettings.JavaPath = PathHelpers.ResolveJavaPath(CurrentSettings.JavaPath);
		}

		protected void InitCurrentProject()
		{
			// get the id from the QueryString
			string id = this.GetIdFromUri();

			this.CurrentProject = PlovrConfiguration.GetCurrentPlovrProjectById(id);

			// override the mode from the querystring if its passed
			this.CurrentProject.Mode = this.GetModeFromQueryString() ?? CurrentProject.Mode;

			string rootPath = Context.Request.MapPath("~");

			// reformat the base paths so we have full paths
			this.CurrentProject.Paths = PathHelpers.MakeAbsoluteFromUrlAndBasePath(CurrentProject.Paths,rootPath);
			this.CurrentProject.Inputs = PathHelpers.MakeAbsoluteFromUrlAndBasePath(CurrentProject.Inputs, rootPath);

			if (this.CurrentProject.Externs != null)
			{
				this.CurrentProject.Externs = CurrentProject.Externs.Select(x => PathHelpers.MakeAbsoluteFromUrlAndBasePath(x, rootPath));
			}
		}

		#endregion

		#region "Response Helpers"

		/// <summary>
		/// Show the response with the specified content type. The request will then end.
		/// </summary>
		/// <param name="response">the output</param>
		/// <param name="contentType">the content type</param>
		protected void ShowResponse(string response, string contentType)
		{
			Context.Response.ContentType = contentType;
			Context.Response.Write(response);
			Context.Response.End();
		}

		/// <summary>
		/// Show the response with a javascript content type.
		/// </summary>
		/// <param name="response">the output</param>
		protected void ShowJavaScriptResponse(string response)
		{
			this.ShowResponse(response, "application/x-javascript");
		}

		/// <summary>
		/// Show the resposne with the html content type.
		/// </summary>
		/// <param name="response"></param>
		protected void ShowHtmlResponse(string response)
		{
			this.ShowResponse(response, "text/html");
		}

		/// <summary>
		/// Show a file in the response and set the content type as javascript.
		/// </summary>
		/// <param name="file">the file to output</param>
		protected void ShowJavaScriptFileResponse(string file)
		{
			this.Context.Response.ContentType = "application/x-javascript";
			this.Context.Response.WriteFile(file);
			this.Context.Response.End();
		}

		#endregion

		#region "QueryString Helpers"

		/// <summary>
		/// The ID can be passed from the QueryString to override the DefaultProject flag.
		/// </summary>
		/// <remarks>Override in subclasses if you need to get it from path instead of QueryString</remarks>
		protected virtual string GetIdFromUri()
		{
			NameValueCollection queryString = Context.Request.QueryString;

			if (queryString.AllKeys.Contains(IdQueryStringParam))
			{
				return queryString[IdQueryStringParam];
			}

			return null;
		}

		/// <summary>
		/// Retrieves a mode override from the querystring, if it exists.
		/// </summary>
		/// <returns>the mode from the querystring as an enum if it exists</returns>
		private ClosureCompilerMode? GetModeFromQueryString()
		{
			NameValueCollection queryString = Context.Request.QueryString;

			if (queryString.AllKeys.Contains(IdQueryStringParam))
			{
				return Mappers.MapToEnum<ClosureCompilerMode>(queryString[ModeQueryStringParam]);
			}

			return null;
		}

		#endregion

		#region "Utilities"
		/// <summary>
		/// Convert closure compiler messages to JSON.
		/// </summary>
		/// <param name="output">the message output from the closure compiler</param>
		/// <returns></returns>
		protected string ToJson(List<ClosureCompilerMessage> output)
		{
			return JsonConvert.SerializeObject(output);
		}

		/// <summary>
		/// return a root url of the plovr handler, e.g. http://localhost:9810/Plovr.NET
		/// </summary>
		/// <returns>a url friendly absolute URL to the site-root</returns>
		protected string GetRootUrl()
		{
			StringBuilder builder = new StringBuilder();
			builder.Append(Context.Request.Url.Scheme);
			builder.Append("://");
			builder.Append(Context.Request.Url.Host);

			if (Context.Request.Url.Port != 80)
			{
				builder.Append(":");
				builder.Append(Context.Request.Url.Port);
			}

			builder.Append(PlovrHttpModule.PlovrUrlHandler);

			return builder.ToString();
		}

		/// <summary>
		/// Pass a full path and convert it to an input handler path
		/// </summary>
		/// <param name="fullPath">the full path to convert</param>
		/// <returns>the url of the input handler</returns>
		protected string ResolveInputPath(string fullPath)
		{
			if (fullPath.IndexOf("/$$/$$", StringComparison.Ordinal) > -1)
			{
				string inputPath = this.GetRootUrl() + "/input/" + CurrentProject.Id + fullPath;
				return inputPath;
			}

			foreach (string basePath in this.CurrentProject.Paths)
			{
				if (fullPath.StartsWith(basePath))
				{
					string relativeToBasePath = this.FixSlash(fullPath.Substring(basePath.Length + 1));
					string inputPath = this.GetRootUrl() + "/input/" + CurrentProject.Id + "/" + relativeToBasePath;
					return inputPath;
				}
			}

			throw new Exception("Matching base path not found.  Cannot resolve input path from full path.");
		}

		/// <summary>
		/// Windows file system slashes are \, URL's are in /, this makes things a little easier for us.
		/// </summary>
		/// <param name="str">the string we want to switch the slashes in</param>
		/// <returns>the slashes swapped</returns>
		protected string FixSlash(string str)
		{
			return str.Replace("\\", "/");
		}

		#endregion
	}
}


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN
namespace libmongoc {

#ifdef MONGOCXX_TESTING

#if defined(__GNUC__) && (__GNUC__ >= 6) && !defined(__clang__)
// See https://jira.mongodb.org/browse/CXX-1453 and
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81605 The basic issue
// is that GCC sees the visibility attributes on the mongoc functions,
// and considers them part of the type, and then emits a silly
// diagnostic stating that the attribute was ignored.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wignored-attributes"
#endif

#define MONGOCXX_LIBMONGOC_SYMBOL(name) \
    extern MONGOCXX_API mongocxx::test_util::mock<decltype(&mongoc_##name)>& name;
#include "libmongoc_symbols.hh"
#undef MONGOCXX_LIBMONGOC_SYMBOL

#if defined(__GNUC__) && (__GNUC__ >= 6) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif

#else
#define MONGOCXX_LIBMONGOC_SYMBOL(name) constexpr auto name = mongoc_##name;
#include "libmongoc_symbols.hh"
#undef MONGOCXX_LIBMONGOC_SYMBOL
#endif

}  // namespace libmongoc
MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/private/postlude.hh>

redpajama_set_name: RedPajamaGithub


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

<TITLE>
org.apache.axis.holders (Axis API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.axis.holders package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.axis.holders

Classes

DataHandlerHolder

DateHolder

DayHolder

DurationHolder

HexBinaryHolder

ImageHolder

MimeMultipartHolder

MonthDayHolder

MonthHolder

NegativeIntegerHolder

NonNegativeIntegerHolder

NonPositiveIntegerHolder

NormalizedStringHolder

OctetStreamHolder

PositiveIntegerHolder

SchemaHolder

SourceHolder

TimeHolder

TokenHolder

UnsignedByteHolder

UnsignedIntHolder

UnsignedLongHolder

UnsignedShortHolder

URIHolder

YearHolder

YearMonthHolder


text:
define(
   ({
    appCopyright: "All Rights Reserved",
    _widgetLabel: "Voettekst"
  })
);


text:
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Titter
{
    public class TitterService
    {
        private readonly string consumerKey;
        private readonly string consumerSecret;

        public TitterService(string cunsomerKey, string cunsomerSecret)
        {
            consumerKey = cunsomerKey;
            consumerSecret = cunsomerSecret;
        }

        public TwitterToken GetRequestToken()
        {
            var uri = new Uri("https://api.twitter.com/oauth/request_token");
            var oAuth = new OAuthBase();
            var timeStamp = oAuth.GenerateTimeStamp();
            var nonce = oAuth.GenerateNonce();
            string normUri;
            string normParams;
            var sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty,
                "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normUri, out normParams);
            var request_url =
              "https://api.twitter.com/oauth/request_token" + "?" +
              "oauth_consumer_key=" + consumerKey + "&" +
              "oauth_signature_method=" + "HMAC-SHA1" + "&" +
              "oauth_signature=" + sig + "&" +
              "oauth_timestamp=" + timeStamp + "&" +
              "oauth_nonce=" + nonce + "&" +
              "oauth_version=" + "1.0";

            var twitterToken = new TwitterToken();
            var Request = (HttpWebRequest)WebRequest.Create(request_url);
            try
            {
                var Response = (HttpWebResponse)Request.GetResponse();
                using (var Reader = new StreamReader(Response.GetResponseStream(), Encoding.GetEncoding(1251)))
                {
                    var outline = Reader.ReadToEnd();
                    char[] delimiterChars = { '&', '=' };
                    var words = outline.Split(delimiterChars);
                    twitterToken.OauthToken = words[1];
                    twitterToken.OauthTokenSecret = words[3];
                    var oauth_callback_confirmed = words[5];

                    return twitterToken;
                }

            }
            catch (Exception)
            {
                return twitterToken;
            }
        }

        public TwitterToken GetOauthToken(string verifier, string token)
        {
            var uri = new Uri("https://api.twitter.com/oauth/request_token");
            var oAuth = new OAuthBase();
            var timeStamp = oAuth.GenerateTimeStamp();
            var nonce = oAuth.GenerateNonce();
            string normUri;
            string normParams;
            var sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty,
                "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normUri, out normParams);
            var request_url =
              "https://api.twitter.com/oauth/access_token" + "?" +
              "oauth_consumer_key=" + consumerKey + "&" +
              "oauth_token=" + token + "&" +
              "oauth_signature_method=" + "HMAC-SHA1" + "&" +
              "oauth_signature=" + sig + "&" +
              "oauth_timestamp=" + timeStamp + "&" +
              "oauth_nonce=" + nonce + "&" +
              "oauth_version=" + "1.0" + "&" +
              "oauth_verifier=" + verifier;

            var Request = (HttpWebRequest)WebRequest.Create(request_url);
            try
            {
                var Response = (HttpWebResponse)Request.GetResponse();
                using (var Reader = new StreamReader(Response.GetResponseStream(), Encoding.GetEncoding(1251)))
                {
                    var twitterToken = new TwitterToken();
                    var outline = Reader.ReadToEnd();
                    char[] delimiterChars = { '&', '=' };
                    var words = outline.Split(delimiterChars);
                    twitterToken.OauthToken = words[1];
                    twitterToken.OauthTokenSecret = words[3];
                    twitterToken.UserId = words[5];
                    twitterToken.UserName = words[7];

                    return twitterToken;
                }

            }
            catch (Exception)
            {
                return null;
            }
        }

        public string SendMessage(string oauthToken, string oauthTokenSecret, string title, string description)
        {
            var sender = new TwitterUpdateWithMedia(consumerKey, consumerSecret, oauthToken, oauthTokenSecret);
            var pic = TwitterPicture.CreatePictureFromText(description);

            return sender.UpdateWithMedia(title, pic);
        }
    }
}


text:
require 'spec_helper'

describe ActiveInteraction::BooleanFilter, :filter do
  include_context 'filters'
  it_behaves_like 'a filter'

  describe '#process' do
    context 'falsey' do
      [false, '0', 'false', 'FALSE', 'off', 'OFF'].each do |value|
        it "returns false for #{value.inspect}" do
          expect(filter.process(value, nil).value).to be_falsey
        end
      end

      context 'with an implicit string' do
        let(:value) do
          Class.new do
            def to_str
              'false'
            end
          end.new
        end

        it 'returns false' do
          expect(filter.process(value, nil).value).to be_falsey
        end
      end
    end

    context 'truthy' do
      [true, '1', 'true', 'TRUE', 'on', 'ON'].each do |value|
        it "returns true for #{value.inspect}" do
          expect(filter.process(value, nil).value).to be_truthy
        end
      end

      context 'with an implicit string' do
        let(:value) do
          Class.new do
            def to_str
              'true'
            end
          end.new
        end

        it 'returns true' do
          expect(filter.process(value, nil).value).to be_truthy
        end
      end
    end

    context 'with a blank String' do
      let(:value) do
        Class.new do
          def to_str
            ' '
          end
        end.new
      end

      context 'optional' do
        include_context 'optional'

        it 'returns the default' do
          expect(filter.process(value, nil).value).to eql options[:default]
        end
      end

      context 'required' do
        include_context 'required'

        it 'indicates an error' do
          expect(
            filter.process(value, nil).error
          ).to be_an_instance_of ActiveInteraction::MissingValueError
        end
      end
    end
  end

  describe '#database_column_type' do
    it 'returns :boolean' do
      expect(filter.database_column_type).to eql :boolean
    end
  end
end


text:
namespace peloton {
namespace concurrency {

extern thread_local std::unordered_map<oid_t, std::unordered_set<oid_t>>
    eager_write_released_rdlock;

struct TxnList {
  txn_id_t txn_id_;
  TxnList *next;
  TxnList() : txn_id_(INVALID_TXN_ID), next(nullptr) {}
  TxnList(txn_id_t t) : txn_id_(t), next(nullptr) {}
};

struct EagerWriteTxnContext {
  //  Spinlock wait_list_lock_;
  volatile std::atomic<int> wait_for_counter_;
  std::unordered_set<txn_id_t> wait_list_;
  cid_t begin_cid_;

  EagerWriteTxnContext()
      : wait_for_counter_(0), wait_list_(), begin_cid_(INVALID_CID) {}
  ~EagerWriteTxnContext() {}
};

extern thread_local EagerWriteTxnContext *current_txn_ctx;

//===--------------------------------------------------------------------===//
// pessimistic+eager write concurrency control
//===--------------------------------------------------------------------===//
class EagerWriteTxnManager : public TransactionManager {
 public:
  EagerWriteTxnManager() : last_epoch_(0) {}
  virtual ~EagerWriteTxnManager() {}

  static EagerWriteTxnManager &GetInstance();

  virtual bool IsVisible(
      const storage::TileGroupHeader *const tile_group_header,
      const oid_t &tuple_id);

  virtual bool IsOwner(const storage::TileGroupHeader *const tile_group_header,
                       const oid_t &tuple_id);

  virtual bool IsOwnable(
      const storage::TileGroupHeader *const tile_group_header,
      const oid_t &tuple_id);

  virtual bool AcquireOwnership(
      const storage::TileGroupHeader *const tile_group_header,
      const oid_t &tile_group_id, const oid_t &tuple_id);

  virtual bool PerformInsert(const ItemPointer &location);

  virtual bool PerformRead(const ItemPointer &location);

  virtual void PerformUpdate(const ItemPointer &old_location,
                             const ItemPointer &new_location);

  virtual void PerformDelete(const ItemPointer &old_location,
                             const ItemPointer &new_location);

  virtual void PerformUpdate(const ItemPointer &location);

  virtual void PerformDelete(const ItemPointer &location);

  virtual Result CommitTransaction();

  virtual Result AbortTransaction();

  virtual Transaction *BeginTransaction() {
    txn_id_t txn_id = GetNextTransactionId();
    cid_t begin_cid = GetNextCommitId();
    Transaction *txn = new Transaction(txn_id, begin_cid);
    current_txn = txn;

    EagerWriteTxnContext *txn_ctx = new EagerWriteTxnContext();
    current_txn_ctx = txn_ctx;
    txn_ctx->begin_cid_ = begin_cid;

    {
      std::lock_guard<std::mutex> lock(running_txn_map_mutex_);
      running_txn_map_[txn_id] = txn_ctx;
    }

    auto eid = EpochManagerFactory::GetInstance().EnterEpoch(begin_cid);
    txn->SetEpochId(eid);

    return txn;
  }

  virtual void EndTransaction() {
    txn_id_t txn_id = current_txn->GetTransactionId();

    // Remove all reader
    RemoveReader();

    // Release all dependencies
    {
      std::lock_guard<std::mutex> lock(running_txn_map_mutex_);

      // No more dependency can be added.

      for (auto wtid : current_txn_ctx->wait_list_) {
        if (running_txn_map_.count(wtid) != 0) {
          running_txn_map_[wtid]->wait_for_counter_--;
          assert(running_txn_map_[wtid]->wait_for_counter_ >= 0);
        }
      }
      running_txn_map_.erase(txn_id);
    }

    EpochManagerFactory::GetInstance().ExitEpoch(current_txn->GetEpochId());

    delete current_txn;
    delete current_txn_ctx;
    current_txn = nullptr;
    current_txn_ctx = nullptr;
  }

 private:

  // init reserved area of a tuple
  // creator txnid | lock (for read list) | read list head
  // The txn_id could only be the cur_txn's txn id.
  void InitTupleReserved(const oid_t tile_group_id, const oid_t tuple_id) {

    auto tile_group_header = catalog::Manager::GetInstance()
        .GetTileGroup(tile_group_id)->GetHeader();

    auto reserved_area = tile_group_header->GetReservedFieldRef(tuple_id);

    new ((reserved_area + LOCK_OFFSET)) Spinlock();
    // Hack
    *(TxnList *)(reserved_area + LIST_OFFSET) = TxnList(0);
  }

  TxnList *GetEwReaderList(
      const storage::TileGroupHeader *const tile_group_header,
      const oid_t &tuple_id) {
    return (TxnList *)(tile_group_header->GetReservedFieldRef(tuple_id) +
                       LIST_OFFSET);
  }

  // Use to protect the reader list, not the reader count
  void GetEwReaderLock(const storage::TileGroupHeader *const tile_group_header,
                       const oid_t &tuple_id) {
    auto lock = (Spinlock *)(tile_group_header->GetReservedFieldRef(tuple_id) +
                             LOCK_OFFSET);
    lock->Lock();
  }

  void ReleaseEwReaderLock(
      const storage::TileGroupHeader *const tile_group_header,
      const oid_t tuple_id) {
    auto lock = (Spinlock *)(tile_group_header->GetReservedFieldRef(tuple_id) +
                             LOCK_OFFSET);
    lock->Unlock();
  }

  // Add the current txn into the reader list of a tuple
  // note: should be protected in EwReaderLock
  void AddReader(storage::TileGroupHeader *tile_group_header,
                 const oid_t &tuple_id) {
    auto txn_id = current_txn->GetTransactionId();
    LOG_INFO("Add reader %lu, tuple_id = %u", txn_id, tuple_id);

    TxnList *reader = new TxnList(txn_id);

    // GetEwReaderLock(tile_group_header, tuple_id);
    TxnList *headp = (TxnList *)(
        tile_group_header->GetReservedFieldRef(tuple_id) + LIST_OFFSET);
    reader->next = headp->next;
    headp->next = reader;
    // ReleaseEwReaderLock(tile_group_header, tuple_id);
  }

  // Remove reader from the reader list of a tuple
  void RemoveReader(storage::TileGroupHeader *tile_group_header,
                    const oid_t &tuple_id, txn_id_t txn_id) {
    LOG_INFO("Remove reader with txn_id = %lu", txn_id);
    GetEwReaderLock(tile_group_header, tuple_id);

    TxnList *headp = (TxnList *)(
        tile_group_header->GetReservedFieldRef(tuple_id) + LIST_OFFSET);

    auto next = headp->next;
    auto prev = headp;
    bool find = false;
    while (next != nullptr) {
      if (next->txn_id_ == txn_id) {
        find = true;
        prev->next = next->next;
        delete next;
        break;
      }
      prev = next;
      next = next->next;
    }

    ReleaseEwReaderLock(tile_group_header, tuple_id);
    if (find == false) {
      assert(false);
    }
  }

  void RemoveReader();

  bool CauseDeadLock();

  std::mutex running_txn_map_mutex_;
  std::unordered_map<txn_id_t, EagerWriteTxnContext *> running_txn_map_;
  static const int LOCK_OFFSET = 0;
  static const int LIST_OFFSET = (LOCK_OFFSET + sizeof(txn_id_t));
  cid_t last_epoch_;
  cid_t last_max_commit_cid_;
};
}
}


text:
Register

                <form novalidate (ngSubmit)="register(user)" [formGroup]="user">

                            Forename
                            <input type="text" placeholder="Forename" formControlName="forename">

Forename is required

                            Surname
                            <input type="text" placeholder="Surname" formControlName="surname">

Surname is required

                            Email Address
                            <input type="text" placeholder="Email" formControlName="email">

Email is required

This doesn't look like a valid email address

                            Password
                            <input type="password" placeholder="Password" formControlName="password">

Password is required

                            Confirm Password
                            <input type="password" placeholder="Confirm Password" formControlName="confirm_password">

Confirm Password is required

Please enter the same pasword

                            <button type="submit" class="btn btn-success btn-lg" [disabled]="user.invalid">Sign Up</button>
                            Already have an account?

                </form>


text:
[![Gem Version](https://badge.fury.io/rb/not_found.png)](http://badge.fury.io/rb/not_found)
[![Code Climate](https://codeclimate.com/github/krisleech/not_found.png)](https://codeclimate.com/github/krisleech/not_found)
[![Build Status](https://travis-ci.org/krisleech/not_found.png?branch=master)](https://travis-ci.org/krisleech/not_found)
[![Coverage Status](https://coveralls.io/repos/krisleech/not_found/badge.png?branch=master)](https://coveralls.io/r/krisleech/not_found?branch=master)

Allows you to rescue `ActiveRecord::RecordNotFound` for a specific model.

For example if you have a `User` model you can rescue `User::RecordNotFound`.

Code which rescue `ActiveRecord::Record` will still work as expected.

## Why?

Because a rescue block around code which rescues `ActiveRecord::RecordNotFound`
might work as expected today, but some time in the future when within that
block another model ends up raising `ActiveRecord::RecordNotFound` it leads to
unexpected behaviour which is diffcult to trace. This gem allows you to be
explicit about what you want to rescue.

## Installation

```ruby
gem 'not_found'
```

## Usage

Include the mixin for a single model

```ruby
class User < ActiveRecord::Base
  include NotFound::Mixin
end
```

or every model

```ruby
ActiveRecord::Base.class_eval { include NotFound::Mixin }
```

and rescue away like this

```ruby
begin
  user = User.find(id)
rescue User::RecordNotFound
  # handle missing user
end
```

or this

```ruby
begin
  user = User.find(id)
  post = Post.find(id)
rescue User::RecordNotFound
  # handle missing user
rescue Post::RecordNotFound
  # handle missing post
end
```

or this

```ruby
begin
  user = User.find(id)
  post = Post.find(id)
rescue User::RecordNotFound
  # handle missing user
rescue ActiveRecord::RecordNotFound
  # handle missing posts and other models
end
```

## Compatibility

Tested with MRI 2.x, JRuby and Rubinius.

See the [build status](https://travis-ci.org/krisleech/not_found) for details.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests.
You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`.
To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

### Running Specs

```
bundle exec rspec
```

To run the specs on code changes try [entr](http://entrproject.org/):

```
ls **/*.rb | entr bundle exec rspec
```

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/krisleech/not_found.
This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package storm2014.commands;

import edu.wpi.first.wpilibj.command.Command;
import storm2014.Robot;
/**
 * Shifts gears.
 */
public class Shift extends Command {
    private final boolean _high;

    public Shift(boolean high) {
        _high = high;
    }

    protected void initialize() {
        Robot.driveTrain.setHighGear(_high);
    }

    protected void execute() {}
    protected boolean isFinished() {
        return true;
    }

    protected void end() {}
    protected void interrupted() {}
}


text:
package com.nikita.movies_shmoovies.common.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;

public class RoundedImage extends FloatingActionButton {

    public RoundedImage(Context context) {
        super(context);
    }

    public RoundedImage(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImage(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        BitmapDrawable drawable = (BitmapDrawable) getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }

        Bitmap fullSizeBitmap = drawable.getBitmap();

        int scaledWidth = getMeasuredWidth();
        int scaledHeight = getMeasuredHeight();

        Bitmap mScaledBitmap;
        if (scaledWidth == fullSizeBitmap.getWidth()
                && scaledHeight == fullSizeBitmap.getHeight()) {
            mScaledBitmap = fullSizeBitmap;
        } else {
            mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap,
                    scaledWidth, scaledHeight, true );
        }

        Bitmap circleBitmap = getCircledBitmap(mScaledBitmap);

        canvas.drawBitmap(circleBitmap, 0, 0, null);

    }

    public Bitmap getRoundedCornerBitmap(Context context, Bitmap input,
                                         int pixels, int w, int h, boolean     squareTL, boolean squareTR,
                                         boolean squareBL, boolean squareBR) {

        Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final float densityMultiplier = context.getResources()
                .getDisplayMetrics().density;

        final int color = 0xff424242;

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);

        // make sure that our rounded corner is scaled appropriately
        final float roundPx = pixels * densityMultiplier;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        // draw rectangles over the corners we want to be square
        if (squareTL) {
            canvas.drawRect(0, 0, w / 2, h / 2, paint);
        }
        if (squareTR) {
            canvas.drawRect(w / 2, 0, w, h / 2, paint);
        }
        if (squareBL) {
            canvas.drawRect(0, h / 2, w / 2, h, paint);
        }
        if (squareBR) {
            canvas.drawRect(w / 2, h / 2, w, h, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(input, 0, 0, paint);

        return output;
    }

    Bitmap getCircledBitmap(Bitmap bitmap) {

        Bitmap result = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(result);

        int color = Color.BLUE;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2,     bitmap.getHeight()/2, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return result;
    }

}


text:
using System;
using System.Runtime.Serialization;
using Gallio.Common.Diagnostics;
using Gallio.Model;

namespace Gallio.Framework
{
    /// <summary>
    /// This exception type is used to signal that a test has failed to satisfy
    /// some predetermined condition established by the test author.
    /// </summary>
    /// <remarks>
    /// <para>
    /// For example, an assertion failure may be signaled using a <see cref="TestFailedException" />
    /// to distinguish it from other application or runtime errors that a test might encounter
    /// at runtime.
    /// </para>
    /// </remarks>
    [Serializable]
    public class TestFailedException : TestException
    {
        /// <summary>
        /// Creates an exception.
        /// </summary>
        public TestFailedException()
        {
        }

        /// <summary>
        /// Creates an exception.
        /// </summary>
        /// <param name="message">The message.</param>
        public TestFailedException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Creates an exception.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="innerException">The inner exception.</param>
        public TestFailedException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Creates an exception from serialization info.
        /// </summary>
        /// <param name="info">The serialization info.</param>
        /// <param name="context">The streaming context.</param>
        protected TestFailedException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Returns <see cref="TestOutcome.Failed" />.
        /// </summary>
        [SystemInternal]
        public sealed override TestOutcome Outcome
        {
            get { return TestOutcome.Failed; }
        }
    }
}


text:
describe('md-slider', function() {
  var $compile, $timeout, $log, $mdConstant, pageScope;

  beforeEach(module('ngAria'));
  beforeEach(module('material.components.slider'));

  beforeEach(inject(function($injector) {
    var $rootScope = $injector.get('$rootScope');
    pageScope = $rootScope.$new();

    $compile = $injector.get('$compile');
    $timeout = $injector.get('$timeout');
    $mdConstant = $injector.get('$mdConstant');
    $log = $injector.get('$log');
  }));

  function setup(attrs, dimensions) {
    var slider;

    slider = $compile('<md-slider ' + (attrs || '') + '>')(pageScope);
    spyOn(
      slider[0].querySelector('.md-track-container'),
      'getBoundingClientRect'
    ).and.returnValue(angular.extend({
      width: 100,
      height: 100,
      left: 0,
      right: 0,
      bottom: 0,
      top: 0
    }, dimensions || {}));

    return slider;
  }

  function setupContainer(attrs, sliderAttrs) {
    return $compile('<md-slider-container ' + (attrs || '') + '>' +
      '<md-slider ' + (sliderAttrs || '') + '></md-slider>' +
      '</md-slider-container>')(pageScope);
  }

  function getWrapper(slider) {
    return angular.element(slider[0].querySelector('.md-slider-wrapper'));
  }

  it('should not set model below the min', function() {
    var slider = setup('ng-model="value" min="0" max="100"');
    pageScope.$apply('value = -50');
    expect(slider.attr('aria-valuenow')).toEqual('0');
  });

  it('should not set model above the max', function() {
    var slider = setup('ng-model="value" min="0" max="100"');
    pageScope.$apply('value = 150');
    expect(slider.attr('aria-valuenow')).toEqual('100');
  });

  it('should set model on press', function() {
    var slider = setup('ng-model="value" min="0" max="100"');
    pageScope.$apply('value = 50');

    var wrapper = getWrapper(slider);

    wrapper.triggerHandler({type: '$md.pressdown', pointer: { x: 30 }});
    wrapper.triggerHandler({type: '$md.dragstart', pointer: { x: 30 }});
    $timeout.flush();
    expect(pageScope.value).toBe(30);

    // When going past max, it should clamp to max.
    wrapper.triggerHandler({type: '$md.drag', pointer: { x: 150 }});
    $timeout.flush();
    expect(pageScope.value).toBe(100);

    wrapper.triggerHandler({type: '$md.drag', pointer: { x: 50 }});
    $timeout.flush();
    expect(pageScope.value).toBe(50);
  });

  it('should increment model on right arrow', function() {
    var slider = setup('min="100" max="104" step="2" ng-model="model"');
    pageScope.$apply('model = 100');

    var wrapper = getWrapper(slider);

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(102);

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(104);

    // Stays at max.
    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(104);
  });

  it('should decrement model on left arrow', function() {
    var slider = setup('min="100" max="104" step="2" ng-model="model"');
    pageScope.$apply('model = 104');

    var wrapper = getWrapper(slider);

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(102);

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(100);

    // Stays at min.
    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
    });
    $timeout.flush();
    expect(pageScope.model).toBe(100);
  });

  describe('when raising max and model value equally beyond previous max simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="0" max="{{max}}" ng-model="model"');
      pageScope.max = 5;
      pageScope.model = 5;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('5');
      expect(slider.attr('aria-valuemax')).toEqual('5');
      pageScope.model = 6;
      pageScope.max = 6;
      pageScope.$apply();
    });

    it('should have updated max correctly', function () {
      expect(slider.attr('aria-valuemax')).toEqual('6');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('6');
    });

  });

  describe('when raising max and model value beyond previous max simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="0" max="{{max}}" ng-model="model"');
      pageScope.max = 4;
      pageScope.model = 3;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('3');
      expect(slider.attr('aria-valuemax')).toEqual('4');
      pageScope.model = 6;
      pageScope.max = 7;
      pageScope.$apply();
    });

    it('should have updated max correctly', function () {
      expect(slider.attr('aria-valuemax')).toEqual('7');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('6');
    });

  });

  describe('when raising max and setting model value below previous max simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="0" max="{{max}}" ng-model="model"');
      pageScope.max = 4;
      pageScope.model = 2;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('2');
      expect(slider.attr('aria-valuemax')).toEqual('4');
      pageScope.model = 3;
      pageScope.max = 5;
      pageScope.$apply();
    });

    it('should have updated max correctly', function () {
      expect(slider.attr('aria-valuemax')).toEqual('5');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('3');
    });

  });

  describe('when lowering min and model value equally below previous min simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="{{min}}" max="10" ng-model="model"');
      pageScope.min = 5;
      pageScope.model = 5;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('5');
      expect(slider.attr('aria-valuemin')).toEqual('5');
      pageScope.model = 2;
      pageScope.min = 2;
      pageScope.$apply();
    });

    it('should have updated min correctly', function () {
      expect(slider.attr('aria-valuemin')).toEqual('2');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('2');
    });

  });

  describe('when lowering min and model value below previous min simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="{{min}}" max="10" ng-model="model"');
      pageScope.min = 5;
      pageScope.model = 6;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('6');
      expect(slider.attr('aria-valuemin')).toEqual('5');
      pageScope.model = 3;
      pageScope.min = 2;
      pageScope.$apply();
    });

    it('should have updated min correctly', function () {
      expect(slider.attr('aria-valuemin')).toEqual('2');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('3');
    });

  });

  describe('when lowering min and setting model value above previous min simultaneously', function() {

    var slider = null;

    beforeEach(function() {
      slider = setup('min="{{min}}" max="10" ng-model="model"');
      pageScope.min = 5;
      pageScope.model = 7;
      pageScope.$apply();
      expect(slider.attr('aria-valuenow')).toEqual('7');
      expect(slider.attr('aria-valuemin')).toEqual('5');
      pageScope.model = 6;
      pageScope.min = 2;
      pageScope.$apply();
    });

    it('should have updated min correctly', function () {
      expect(slider.attr('aria-valuemin')).toEqual('2');
    });

    it('should have updated value correctly', function () {
      expect(slider.attr('aria-valuenow')).toEqual('6');
    });

  });

  it('should update the thumb text', function() {
    var slider = setup('ng-model="value" md-discrete min="0" max="100" step="1"');
    var wrapper = getWrapper(slider);

    pageScope.$apply('value = 30');
    expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('30');

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
    });
    $timeout.flush();
    expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('29');

    wrapper.triggerHandler({type: '$md.pressdown', pointer: { x: 30 }});
    expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('30');

    wrapper.triggerHandler({type: '$md.dragstart', pointer: { x: 31 }});
    wrapper.triggerHandler({type: '$md.drag', pointer: { x: 31 }});
    expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('31');
  });

  it('should update the thumb text with the model value when using ng-change', function() {
    pageScope.stayAt50 = function () {
      pageScope.value = 50;
    };

    var slider = setup('ng-model="value" min="0" max="100" ng-change="stayAt50()"');
    var wrapper = getWrapper(slider);

    wrapper.triggerHandler({type: '$md.pressdown', pointer: { x: 30 }});
    $timeout.flush();
    expect(pageScope.value).toBe(50);
    expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('50');
  });

  it('should call $log.warn if aria-label isn\'t provided', function() {
    spyOn($log, "warn");
    setup('min="100" max="104" step="2" ng-model="model"');
    expect($log.warn).toHaveBeenCalled();
  });

  it('should not call $log.warn if aria-label is provided', function() {
    spyOn($log, "warn");
    setup('aria-label="banana" min="100" max="104" step="2" ng-model="model"');
    expect($log.warn).not.toHaveBeenCalled();
  });

  it('should add aria attributes', function() {
    var slider = setup('min="100" max="104" step="2" ng-model="model"');
    var wrapper = getWrapper(slider);

    pageScope.$apply('model = 102');

    expect(slider.attr('role')).toEqual('slider');
    expect(slider.attr('aria-valuemin')).toEqual('100');
    expect(slider.attr('aria-valuemax')).toEqual('104');
    expect(slider.attr('aria-valuenow')).toEqual('102');

    wrapper.triggerHandler({
      type: 'keydown',
      keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
    });
    $timeout.flush();
    expect(slider.attr('aria-valuenow')).toEqual('100');
  });

  it('should ignore pressdown events when disabled', function() {
    pageScope.isDisabled = true;
    var slider = setup('ng-disabled="isDisabled"');
    var wrapper = getWrapper(slider);

    pageScope.$digest();

    // Doesn't add active class on pressdown when disabled
    wrapper.triggerHandler({
      type: '$md.pressdown',
      pointer: {}
    });
    expect(slider).not.toHaveClass('md-active');

    // Doesn't remove active class up on pressup when disabled
    slider.addClass('md-active');
    wrapper.triggerHandler({
      type: '$md.pressup',
      pointer: {}
    });
    expect(slider).toHaveClass('md-active');
  });

  it('should disable via the `disabled` attribute', function() {
    var slider = setup('disabled');
    var wrapper = getWrapper(slider);

    pageScope.$digest();

    // Check for disabled state by triggering the pressdown handler and asserting that
    // the slider is not active.
    wrapper.triggerHandler({
      type: '$md.pressdown',
      pointer: {}
    });
    expect(slider).not.toHaveClass('md-active');
  });

  it('should add active class on pressdown and remove on blur', function() {
    var slider = setup();
    var wrapper = getWrapper(slider);

    expect(slider).not.toHaveClass('md-active');

    wrapper.triggerHandler({
      type: '$md.pressdown',
      pointer: {}
    });
    expect(slider).toHaveClass('md-active');

    wrapper.triggerHandler({
      type: 'blur',
      pointer: {}
    });
    expect(slider).not.toHaveClass('md-active');
  });

  it('should add md-min class only when at min value', function() {
    var slider = setup('ng-model="model" min="0" max="30"');
    var wrapper = getWrapper(slider);

    pageScope.$apply('model = 0');
    expect(slider).toHaveClass('md-min');

    wrapper.triggerHandler({type: '$md.dragstart', pointer: {x: 0}});
    wrapper.triggerHandler({type: '$md.drag', pointer: {x: 10}});
    $timeout.flush();
    expect(slider).not.toHaveClass('md-min');
  });

  it('should add md-max class only when at max value', function() {
    var slider = setup('ng-model="model" min="0" max="30"');
    var wrapper = getWrapper(slider);

    pageScope.$apply('model = 30');
    expect(slider).toHaveClass('md-max');

    wrapper.triggerHandler({type: '$md.dragstart', pointer: {x: 30}});
    wrapper.triggerHandler({type: '$md.drag', pointer: {x: 10}});
    $timeout.flush();
    expect(slider).not.toHaveClass('md-max');
  });

  it('should increment at a predictable step', function() {

    buildSlider(0.1, 0, 1).drag({x:70});
    expect(pageScope.value).toBe(0.7);

    buildSlider(0.25, 0, 1).drag({x:45});
    expect(pageScope.value).toBe(0.5);

    buildSlider(0.25, 0, 1).drag({x:35});
    expect(pageScope.value).toBe(0.25);

    buildSlider(1, 0, 100).drag({x:90});
    expect(pageScope.value).toBe(90);

    buildSlider(20, 5, 45).drag({x:50});
    expect(pageScope.value).toBe(25);

    function buildSlider(step, min, max) {
      var slider = setup('ng-model="value" min="' + min + '" max="' + max + '" step="' + step + '"');
          pageScope.$apply('value = 0.5');

      var wrapper = getWrapper(slider);

      return {
        drag : function simulateDrag(drag) {

          wrapper.triggerHandler({type: '$md.pressdown', pointer: drag });
          wrapper.triggerHandler({type: '$md.dragstart', pointer: drag });

          $timeout.flush();
        }
      };
    }

  });

  describe('vertical', function () {
    it('should set model on press', function() {
      var slider = setup('md-vertical ng-model="value" min="0" max="100"');
      pageScope.$apply('value = 50');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({type: '$md.pressdown', pointer: { y: 70 }});
      wrapper.triggerHandler({type: '$md.dragstart', pointer: { y: 70 }});
      $timeout.flush();
      expect(pageScope.value).toBe(30);

      // When going past max, it should clamp to max.
      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 0 }});
      $timeout.flush();
      expect(pageScope.value).toBe(100);

      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 50 }});
      $timeout.flush();
      expect(pageScope.value).toBe(50);
    });

    it('should increment model on up arrow', function() {
      var slider = setup('md-vertical min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 100');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);

      // Stays at max.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);
    });

    it('should decrement model on down arrow', function() {
      var slider = setup('md-vertical min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 104');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);

      // Stays at min.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);
    });

    it('should update the thumb text', function() {
      var slider = setup('md-vertical ng-model="value" md-discrete min="0" max="100" step="1"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('value = 30');
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('30');

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('29');

      wrapper.triggerHandler({type: '$md.pressdown', pointer: { y: 70 }});
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('30');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: { y: 93 }});
      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 93 }});
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('7');
    });

    it('should add md-min class only when at min value', function() {
      var slider = setup('md-vertical ng-model="model" min="0" max="30"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('model = 0');
      expect(slider).toHaveClass('md-min');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: {y: 0}});
      wrapper.triggerHandler({type: '$md.drag', pointer: {y: 10}});
      $timeout.flush();
      expect(slider).not.toHaveClass('md-min');
    });

    it('should add md-max class only when at max value', function() {
      var slider = setup('md-vertical ng-model="model" min="0" max="30"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('model = 30');
      expect(slider).toHaveClass('md-max');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: {y: 30}});
      wrapper.triggerHandler({type: '$md.drag', pointer: {y: 10}});
      $timeout.flush();
      expect(slider).not.toHaveClass('md-max');
    });

    it('should increment at a predictable step', function() {

      buildSlider(0.1, 0, 1).drag({y:30});
      expect(pageScope.value).toBe(0.7);

      buildSlider(0.25, 0, 1).drag({y:45});
      expect(pageScope.value).toBe(0.5);

      buildSlider(0.25, 0, 1).drag({y:75});
      expect(pageScope.value).toBe(0.25);

      buildSlider(1, 0, 100).drag({y:10});
      expect(pageScope.value).toBe(90);

      buildSlider(20, 5, 45).drag({y:50});
      expect(pageScope.value).toBe(25);

      function buildSlider(step, min, max) {
        var slider = setup('md-vertical ng-model="value" min="' + min + '" max="' + max + '" step="' + step + '"');
        pageScope.$apply('value = 0.5');

        var wrapper = getWrapper(slider);

        return {
          drag : function simulateDrag(drag) {

            wrapper.triggerHandler({type: '$md.pressdown', pointer: drag });
            wrapper.triggerHandler({type: '$md.dragstart', pointer: drag });

            $timeout.flush();
          }
        };
      }

    });
  });

  describe('slider container', function () {

    it('should have `._md` class indicator', inject(function() {
      var element = setupContainer('disabled="disabled"');
      expect(element.hasClass('_md')).toBe(true);
    }));

    it('should disable via the `disabled` attribute', function() {
      var container = setupContainer('disabled="disabled"');
      var slider = angular.element(container[0].querySelector('md-slider'));
      var wrapper = getWrapper(container);

      // Check for disabled state by triggering the pressdown handler and asserting that
      // the slider is not active.
      wrapper.triggerHandler({
        type: '$md.pressdown',
        pointer: {}
      });
      expect(slider).not.toHaveClass('md-active');
    });

    it('should disable via the `ngDisabled` attribute', function() {
      var container = setupContainer('ng-disabled="isDisabled"');
      var slider = angular.element(container[0].querySelector('md-slider'));
      var wrapper = getWrapper(container);

      // Check for disabled state by triggering the pressdown handler and asserting that
      // the slider is not active.
      wrapper.triggerHandler({
        type: '$md.pressdown',
        pointer: {}
      });
      expect(slider).toHaveClass('md-active');

      // Removing focus from the slider
      wrapper.triggerHandler({
        type: 'blur',
        pointer: {}
      });

      pageScope.$apply('isDisabled = true');

      wrapper.triggerHandler({
        type: '$md.pressdown',
        pointer: {}
      });
      expect(slider).not.toHaveClass('md-active');
    });

    it('should disable related inputs', inject(function($compile) {
      var container = setupContainer('ng-disabled="isDisabled"');
      var slider = angular.element(container[0].querySelector('md-slider'));

      var inputContainer = $compile('<md-input-container><input /></md-input-container>')(pageScope);
      var input = angular.element(inputContainer[0].querySelector('input'));

      container.append(input);

      expect(input.attr('disabled')).toEqual(undefined);

      pageScope.$apply('isDisabled = true');

      expect(input.attr('disabled')).toEqual('disabled');
    }));

  });

  describe('invert', function () {
    it('should set model on press', function() {
      var slider = setup('md-vertical md-invert ng-model="value" min="0" max="100"');
      pageScope.$apply('value = 50');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({type: '$md.pressdown', pointer: { y: 70 }});
      wrapper.triggerHandler({type: '$md.dragstart', pointer: { y: 70 }});
      $timeout.flush();
      expect(pageScope.value).toBe(70);

      // When going past max, it should clamp to max.
      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 0 }});
      $timeout.flush();
      expect(pageScope.value).toBe(0);

      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 50 }});
      $timeout.flush();
      expect(pageScope.value).toBe(50);
    });

    it('should decrement model on up arrow', function() {
      var slider = setup('md-vertical md-invert min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 104');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);

      // Stays at min.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.UP_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);

    });

    it('should increment model on down arrow', function() {
      var slider = setup('md-vertical md-invert min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 100');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);

      // Stays at max.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);
    });

    it('should update the thumb text', function() {
      var slider = setup('md-vertical md-invert ng-model="value" md-discrete min="0" max="100" step="1"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('value = 30');
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('30');

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.DOWN_ARROW
      });
      $timeout.flush();
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('31');

      wrapper.triggerHandler({type: '$md.pressdown', pointer: { y: 70 }});
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('70');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: { y: 93 }});
      wrapper.triggerHandler({type: '$md.drag', pointer: { y: 93 }});
      expect(slider[0].querySelector('.md-thumb-text').textContent).toBe('93');
    });

    it('should add md-min class only when at min value', function() {
      var slider = setup('md-vertical md-invert ng-model="model" min="0" max="30"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('model = 0');
      expect(slider).toHaveClass('md-min');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: {y: 0}});
      wrapper.triggerHandler({type: '$md.drag', pointer: {y: 10}});
      $timeout.flush();
      expect(slider).not.toHaveClass('md-min');
    });

    it('should add md-max class only when at max value', function() {
      var slider = setup('md-vertical md-invert ng-model="model" min="0" max="30"');
      var wrapper = getWrapper(slider);

      pageScope.$apply('model = 30');
      expect(slider).toHaveClass('md-max');

      wrapper.triggerHandler({type: '$md.dragstart', pointer: {y: 30}});
      wrapper.triggerHandler({type: '$md.drag', pointer: {y: 10}});
      $timeout.flush();
      expect(slider).not.toHaveClass('md-max');
    });

    it('should increment at a predictable step', function() {

      buildSlider(0.1, 0, 1).drag({y:30});
      expect(pageScope.value).toBe(0.3);

      buildSlider(0.25, 0, 1).drag({y:45});
      expect(pageScope.value).toBe(0.5);

      buildSlider(0.25, 0, 1).drag({y:75});
      expect(pageScope.value).toBe(0.75);

      buildSlider(1, 0, 100).drag({y:10});
      expect(pageScope.value).toBe(10);

      buildSlider(20, 5, 45).drag({y:50});
      expect(pageScope.value).toBe(25);

      function buildSlider(step, min, max) {
        var slider = setup('md-vertical md-invert ng-model="value" min="' + min + '" max="' + max + '" step="' + step + '"');
        pageScope.$apply('value = 0.5');

        var wrapper = getWrapper(slider);

        return {
          drag : function simulateDrag(drag) {

            wrapper.triggerHandler({type: '$md.pressdown', pointer: drag });
            wrapper.triggerHandler({type: '$md.dragstart', pointer: drag });

            $timeout.flush();
          }
        };
      }

    });

    it('should increment model on left arrow', function() {
      var slider = setup('md-invert min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 100');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);

      // Stays at max.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.LEFT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(104);
    });

    it('should decrement model on right arrow', function() {
      var slider = setup('md-invert min="100" max="104" step="2" ng-model="model"');
      pageScope.$apply('model = 104');

      var wrapper = getWrapper(slider);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(102);

      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);

      // Stays at min.
      wrapper.triggerHandler({
        type: 'keydown',
        keyCode: $mdConstant.KEY_CODE.RIGHT_ARROW
      });
      $timeout.flush();
      expect(pageScope.model).toBe(100);
    });

  });

  it('should set a default tabindex', function() {
    var slider = setup();
    var wrapper = getWrapper(slider);

    expect(wrapper.attr('tabindex')).toBe('0');
  });

  it('should set a -1 tabindex to disabled slider', function() {
    var slider = setup('ng-disabled="isDisabled"');
    var wrapper = getWrapper(slider);

    expect(wrapper.attr('tabindex')).toBe('-1');
  });

  it('should not overwrite tabindex attribute', function() {
    var slider = setup('tabindex="2"');
    var wrapper = getWrapper(slider);

    expect(wrapper.attr('tabindex')).toBe('2');
  });

});


text:
package org.elasticsearch.search.internal;

import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.search.RescoreDocIds;
import org.elasticsearch.search.dfs.AggregatedDfs;

import java.util.Objects;

public class LegacyReaderContext extends ReaderContext {
    private final ShardSearchRequest shardSearchRequest;
    private final ScrollContext scrollContext;
    private final Engine.Searcher searcher;

    private AggregatedDfs aggregatedDfs;
    private RescoreDocIds rescoreDocIds;

    public LegacyReaderContext(ShardSearchContextId id, IndexService indexService, IndexShard indexShard, Engine.SearcherSupplier reader,
                               ShardSearchRequest shardSearchRequest, long keepAliveInMillis) {
        super(id, indexService, indexShard, reader, keepAliveInMillis, false);
        assert shardSearchRequest.readerId() == null;
        assert shardSearchRequest.keepAlive() == null;
        assert id.getSearcherId() == null : "Legacy reader context must not have searcher id";
        this.shardSearchRequest = Objects.requireNonNull(shardSearchRequest);
        if (shardSearchRequest.scroll() != null) {
            // Search scroll requests are special, they don't hold indices names so we have
            // to reuse the searcher created on the request that initialized the scroll.
            // This ensures that we wrap the searcher's reader with the user's permissions
            // when they are available.
            final Engine.Searcher delegate = searcherSupplier.acquireSearcher("search");
            addOnClose(delegate);
            // wrap the searcher so that closing is a noop, the actual closing happens when this context is closed
            this.searcher = new Engine.Searcher(delegate.source(), delegate.getDirectoryReader(),
                delegate.getSimilarity(), delegate.getQueryCache(), delegate.getQueryCachingPolicy(), () -> {});
            this.scrollContext = new ScrollContext();
        } else {
            this.scrollContext = null;
            this.searcher = null;
        }
    }

    @Override
    public Engine.Searcher acquireSearcher(String source) {
        if (scrollContext != null) {
            assert Engine.SEARCH_SOURCE.equals(source) : "scroll context should not acquire searcher for " + source;
            return searcher;
        }
        return super.acquireSearcher(source);
    }

    @Override
    public ShardSearchRequest getShardSearchRequest(ShardSearchRequest other) {
        return shardSearchRequest;
    }

    @Override
    public ScrollContext scrollContext() {
        return scrollContext;
    }

    @Override
    public AggregatedDfs getAggregatedDfs(AggregatedDfs other) {
        return aggregatedDfs;
    }

    @Override
    public void setAggregatedDfs(AggregatedDfs aggregatedDfs) {
        this.aggregatedDfs = aggregatedDfs;
    }

    @Override
    public RescoreDocIds getRescoreDocIds(RescoreDocIds other) {
        return rescoreDocIds;
    }

    @Override
    public void setRescoreDocIds(RescoreDocIds rescoreDocIds) {
        this.rescoreDocIds = rescoreDocIds;
    }

    @Override
    public boolean singleSession() {
        return scrollContext == null || scrollContext.scroll == null;
    }
}


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 Interface ml.alternet.parser.Grammar.Repeatable.Minimal (Alternet Libs 1.0 API)</title>
<meta name="date" content="2020-01-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
ml.alternet.parser.Grammar.Repeatable.Minimal

Packages that use Grammar.Repeatable.Minimal

Package
Description

ml.alternet.parser

Allow to design grammar, parse input and generate a custom data structure.

Uses of Grammar.Repeatable.Minimal in ml.alternet.parser

Classes in ml.alternet.parser that implement Grammar.Repeatable.Minimal

Modifier and Type
Class and Description

static class
Grammar.AtLeast

Make a rule repeatable.

static class
Grammar.Bounds

Make a rule repeatable in bounds.

static class
Grammar.Optional

Make a rule optional.

static class
Grammar.ZeroOrMore

Make a rule optional repeatable.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020 Alternet. All rights reserved.


text:
<?php

namespace Go\Aop;

use Go\Aop\Advice;

/**
 * Tag class for all before advices either for field access or method calling
 * @author Lissachenko Alexander
 */
interface AdviceBefore extends Advice
{

}


text:
  function observableDelayRelative(source, dueTime, scheduler) {
    return new AnonymousObservable(function (o) {
      var active = false,
        cancelable = new SerialDisposable(),
        exception = null,
        q = [],
        running = false,
        subscription;
      subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
        var d, shouldRun;
        if (notification.value.kind === 'E') {
          q = [];
          q.push(notification);
          exception = notification.value.error;
          shouldRun = !running;
        } else {
          q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
          shouldRun = !active;
          active = true;
        }
        if (shouldRun) {
          if (exception !== null) {
            o.onError(exception);
          } else {
            d = new SingleAssignmentDisposable();
            cancelable.setDisposable(d);
            d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) {
              var e, recurseDueTime, result, shouldRecurse;
              if (exception !== null) {
                return;
              }
              running = true;
              do {
                result = null;
                if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
                  result = q.shift().value;
                }
                if (result !== null) {
                  result.accept(o);
                }
              } while (result !== null);
              shouldRecurse = false;
              recurseDueTime = 0;
              if (q.length > 0) {
                shouldRecurse = true;
                recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
              } else {
                active = false;
              }
              e = exception;
              running = false;
              if (e !== null) {
                o.onError(e);
              } else if (shouldRecurse) {
                self(null, recurseDueTime);
              }
            }));
          }
        }
      });
      return new BinaryDisposable(subscription, cancelable);
    }, source);
  }

  function observableDelayAbsolute(source, dueTime, scheduler) {
    return observableDefer(function () {
      return observableDelayRelative(source, dueTime - scheduler.now(), scheduler);
    });
  }

  function delayWithSelector(source, subscriptionDelay, delayDurationSelector) {
    var subDelay, selector;
    if (isFunction(subscriptionDelay)) {
      selector = subscriptionDelay;
    } else {
      subDelay = subscriptionDelay;
      selector = delayDurationSelector;
    }
    return new AnonymousObservable(function (o) {
      var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();

      function start() {
        subscription.setDisposable(source.subscribe(
          function (x) {
            var delay = tryCatch(selector)(x);
            if (delay === errorObj) { return o.onError(delay.e); }
            var d = new SingleAssignmentDisposable();
            delays.add(d);
            d.setDisposable(delay.subscribe(
              function () {
                o.onNext(x);
                delays.remove(d);
                done();
              },
              function (e) { o.onError(e); },
              function () {
                o.onNext(x);
                delays.remove(d);
                done();
              }
            ));
          },
          function (e) { o.onError(e); },
          function () {
            atEnd = true;
            subscription.dispose();
            done();
          }
        ));
      }

      function done () {
        atEnd && delays.length === 0 && o.onCompleted();
      }

      if (!subDelay) {
        start();
      } else {
        subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start));
      }

      return new BinaryDisposable(subscription, delays);
    }, this);
  }

  /**
   *  Time shifts the observable sequence by dueTime.
   *  The relative time intervals between the values are preserved.
   *
   * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
   * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
   * @returns {Observable} Time-shifted sequence.
   */
  observableProto.delay = function () {
    var firstArg = arguments[0];
    if (typeof firstArg === 'number' || firstArg instanceof Date) {
      var dueTime = firstArg, scheduler = arguments[1];
      isScheduler(scheduler) || (scheduler = defaultScheduler);
      return dueTime instanceof Date ?
        observableDelayAbsolute(this, dueTime, scheduler) :
        observableDelayRelative(this, dueTime, scheduler);
    } else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
      return delayWithSelector(this, firstArg, arguments[1]);
    } else {
      throw new Error('Invalid arguments');
    }
  };


text:
package foo.bar;

public enum Enum1 {

}


text:
// -----------------------------------------------------------------------
// <copyright file="ReadLinkedEntryListResponse.cs" company="SugarCrm + PocoGen + REST">
// Copyright (c) SugarCrm + PocoGen + REST. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace SugarRestSharp.Responses
{
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using RestApiCalls.Responses;
    using RestApiCalls.Responses.Extensions;

    /// <summary>
    /// Represents ReadLinkedEntryListResponse class
    /// </summary>
    internal class ReadLinkedEntryListResponse : BaseResponse
    {
        /// <summary>
        /// Gets the entity list returned from SugarCrm to json array objects
        /// </summary>
        public JArray EntityList
        {
            get
            {
                if (this.EntryList == null)
                {
                    return null;
                }

                var entityList = new JArray();
                int count = this.EntryList.Count;
                for (int i = 0; i < count; i++)
                {
                    JObject entity = this.EntryList[i].Entity;
                    entity.SetModuleLinkedList(this.RelationshipList[i]);
                    entityList.Add(entity);
                }

                return entityList;
            }
        }

        /// <summary>
        /// Gets or sets the number of entries returned
        /// </summary>
        [JsonProperty(PropertyName = "result_count")]
        public int Count { get; set; }

        /// <summary>
        /// Gets or sets the total count of entries available
        /// </summary>
        [JsonProperty(PropertyName = "total_count")]
        public string TotalCount { get; set; }

        /// <summary>
        /// Gets or sets the next offset
        /// </summary>
        [JsonProperty(PropertyName = "next_offset")]
        public int NextOffset { get; set; }

        /// <summary>
        /// Gets or sets the entry list in json
        /// </summary>
        [JsonProperty(PropertyName = "entry_list")]
        public List<EntryListArray> EntryList { get; set; }

        /// <summary>
        /// Gets or sets the relationship link entry list in json
        /// </summary>
        [JsonProperty(PropertyName = "relationship_list")]
        public List<LinkedListModule> RelationshipList { get; set; }
    }
}


text:
layout: archive
permalink: 'tags/zsh/'
redirect_from: 'archive/tags/zsh/'
title: 'zsh'
tag: 'zsh'
---


text:
package backtype.storm.testing;

import backtype.storm.Config;
import backtype.storm.topology.OutputFieldsDeclarer;

import java.util.Map;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;

import java.util.HashMap;
import java.util.Random;

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

public class TestWordSpout extends BaseRichSpout {
	/**
	 *
	 */
	private static final long serialVersionUID = 5486125685367336665L;
	public static Logger LOG = LoggerFactory.getLogger(TestWordSpout.class);
	boolean _isDistributed;
	SpoutOutputCollector _collector;

	public TestWordSpout() {
		this(true);
	}

	public TestWordSpout(boolean isDistributed) {
		_isDistributed = isDistributed;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void open(Map conf, TopologyContext context,
			SpoutOutputCollector collector) {
		_collector = collector;
	}

	@Override
	public void close() {

	}

	@Override
	public void nextTuple() {
		Utils.sleep(100);
		final String[] words = new String[] { "nathan", "mike", "jackson",
				"golda", "bertels" };
		final Random rand = new Random();
		final String word = words[rand.nextInt(words.length)];
		_collector.emit(new Values(word));
	}

	@Override
	public void ack(Object msgId) {

	}

	@Override
	public void fail(Object msgId) {

	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer declarer) {
		declarer.declare(new Fields("word"));
	}

	@Override
	public Map<String, Object> getComponentConfiguration() {
		if (!_isDistributed) {
			Map<String, Object> ret = new HashMap<String, Object>();
			ret.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 1);
			return ret;
		} else {
			return null;
		}
	}
}


text:
<?php

/* MatrixBundle:HorarioGrupo:new.html.twig */
class __TwigTemplate_d5924cf3b947e1f5f184809d4b63db0876e24b8a10bda6600274b3613c7ed7e0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("::base.html.twig", "MatrixBundle:HorarioGrupo:new.html.twig", 1);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
HorarioGrupo creation

    ";
        // line 6
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : null), 'form');
        echo "

\t

            env->getExtension('routing')->getPath("horariogrupo");
        echo "\">
                <button class=\"button-new btn btn-primary\">Volver a la lista</button>

";
    }

    public function getTemplateName()
    {
        return "MatrixBundle:HorarioGrupo:new.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  42 => 10,  35 => 6,  31 => 4,  28 => 3,  11 => 1,);
    }
}


text:
title: String.prototype.indexOf
---
## String.prototype.indexOf
The `indexOf()` method returns the first index at which a given element can be found in the array. If the element is not present, it returns -1.

**Syntax**
```javascript
str.indexOf(searchValue[, fromIndex])
```

### Parameters
*   **searchValue** Substring for which you are looking. If this is empty (`''`) and there is no `fromIndex` parameter, this will return 0.

*   **fromIndex** Optional. The index at which you want to start the search. If the `fromIndex` value is greater than or equal to the string's length, the string is not searched and the method returns -1. If the `searchValue` is an empty string (`''`) and the `fromIndex` is less than the string's length, it will return the `fromIndex`; otherwise, it will return the string's length. (A negative number will be treated as though there is no argument.)

### Description
The `indexOf()` method checks the string from left to right. The index of the first character is 0; the index of the last character is ``string.length - 1``. The method checks each substring against `searchValue` using strict equality (`===`), which means this method is case sensitive. Once it finds a substring that returns `true`, it returns the index of its first character.

### Examples
```javascript
'Blue Whale'.indexOf('Blue');     // returns  0
'Blue Whale'.indexOf('Blute');    // returns -1
'Blue Whale'.indexOf('Whale', 0); // returns  5
'Blue Whale'.indexOf('Whale', 5); // returns  5
'Blue Whale'.indexOf('Whale', 7); // returns -1
'Blue Whale'.indexOf('');         // returns  0
'Blue Whale'.indexOf('', 9);      // returns  9
'Blue Whale'.indexOf('', 10);     // returns 10
'Blue Whale'.indexOf('', 11);     // returns 10
'Blue Whale'.indexOf('blue');     // returns -1
```

### More Information:
- MDN documentation: MDN
- MSDN documentation: MSDN


text:
.. :changelog:

History
-------

1.0.0 (2014-08-26)
++++++++++++++++++

* Updated to the 1.0 API.
* NB: The semantics of delete_track() have changed. delete_track() now takes an href to a track. To delte a track by index you now need to call delete_track_at_index().

0.9.0 (2014-06-16)
++++++++++++++++++

* Removed 'source' attribute from bundle.

0.8.0 (2014-05-04)
++++++++++++++++++

* Simplified initialization (and removed threading restriction).
* Separated REST cover and object libraries.
* Moved configuration variables into module's __init__.py file.

0.7.0 (2014-04-30)
++++++++++++++++++

* New repo name.

0.3.0 (2014-04-26)
++++++++++++++++++

* Code cleanup.
* get_bundle_href() changed to get_self_href().
* Switched to new style classes.

0.1.0 (2014-04-20)
++++++++++++++++++

* First release.


text:
from django.conf.urls.defaults import *
import os.path

app_path = os.path.dirname(__file__)
app_dir = os.path.basename(app_path)
theme_dir = os.path.join(app_path, 'static', 'theme')

urlpatterns = patterns('%s.views' % app_dir,
    # put your custom views here
)

# Appends a static url for your theme
urlpatterns += patterns('',
    url(r'^static/themes/%s/(?P<path>.*)/?$' % app_dir, 'django.views.static.serve',
        kwargs={ 'document_root': theme_dir }),
)


text:
#include "TestStep.hpp"
#include "TestStage.hpp"

#include <memory>
#include <vector>

namespace ut11
{
	namespace detail
	{
		class TestStageBuilder
		{
		public:
			virtual ~TestStageBuilder();

			virtual void PushGiven(TestStep given) = 0;
			virtual void PushWhen(TestStep when) = 0;
			virtual void PushThen(TestStep then) = 0;
			virtual void PushFinally(TestStep finally) = 0;
			virtual std::vector< std::shared_ptr<TestStage> > Build() = 0;
		};
	}
}

#endif // UNITTEST11_DETAIL_TESTSTAGEBUILDER_HPP


text:
package org.codehaus.groovy.transform;

import groovy.transform.ExternalizeMethods;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.tools.GenericsUtils;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;

import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod;
import static org.codehaus.groovy.ast.ClassHelper.make;
import static org.codehaus.groovy.ast.tools.GeneralUtils.assignS;
import static org.codehaus.groovy.ast.tools.GeneralUtils.callX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.castX;
import static org.codehaus.groovy.ast.tools.GeneralUtils.getInstanceNonPropertyFields;
import static org.codehaus.groovy.ast.tools.GeneralUtils.getInstancePropertyFields;
import static org.codehaus.groovy.ast.tools.GeneralUtils.param;
import static org.codehaus.groovy.ast.tools.GeneralUtils.params;
import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt;
import static org.codehaus.groovy.ast.tools.GeneralUtils.varX;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveBoolean;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveByte;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveDouble;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveFloat;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveInt;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveLong;
import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveShort;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_TRANSIENT;

/**
 * Handles generation of code for the @ExternalizeMethods annotation.
 */
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class ExternalizeMethodsASTTransformation extends AbstractASTTransformation {
    static final Class MY_CLASS = ExternalizeMethods.class;
    static final ClassNode MY_TYPE = make(MY_CLASS);
    static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage();
    private static final ClassNode EXTERNALIZABLE_TYPE = make(Externalizable.class);
    private static final ClassNode OBJECTOUTPUT_TYPE = make(ObjectOutput.class);
    private static final ClassNode OBJECTINPUT_TYPE = make(ObjectInput.class);

    @Override
    public void visit(ASTNode[] nodes, SourceUnit source) {
        init(nodes, source);
        AnnotatedNode parent = (AnnotatedNode) nodes[1];
        AnnotationNode anno = (AnnotationNode) nodes[0];
        if (!MY_TYPE.equals(anno.getClassNode())) return;

        if (parent instanceof ClassNode) {
            ClassNode cNode = (ClassNode) parent;
            if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;
            cNode.addInterface(EXTERNALIZABLE_TYPE);
            boolean includeFields = memberHasValue(anno, "includeFields", true);
            List<String> excludes = getMemberStringList(anno, "excludes");
            if (!checkPropertyList(cNode, excludes, "excludes", anno, MY_TYPE_NAME, includeFields)) return;
            List<FieldNode> list = getInstancePropertyFields(cNode);
            if (includeFields) {
                list.addAll(getInstanceNonPropertyFields(cNode));
            }
            createWriteExternal(cNode, excludes, list);
            createReadExternal(cNode, excludes, list);
        }
    }

    private static void createWriteExternal(ClassNode cNode, List<String> excludes, List<FieldNode> list) {
        final BlockStatement body = new BlockStatement();
        Parameter out = param(OBJECTOUTPUT_TYPE, "out");
        for (FieldNode fNode : list) {
            if (excludes != null && excludes.contains(fNode.getName())) continue;
            if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue;
            MethodCallExpression writeObject = callX(varX(out), "write" + suffixForField(fNode), varX(fNode));
            writeObject.setImplicitThis(false);
            body.addStatement(stmt(writeObject));
        }
        ClassNode[] exceptions = {make(IOException.class)};
        addGeneratedMethod(cNode, "writeExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, params(out), exceptions, body);
    }

    private static void createReadExternal(ClassNode cNode, List<String> excludes, List<FieldNode> list) {
        final BlockStatement body = new BlockStatement();
        Parameter oin = param(OBJECTINPUT_TYPE, "oin");
        for (FieldNode fNode : list) {
            if (excludes != null && excludes.contains(fNode.getName())) continue;
            if ((fNode.getModifiers() & ACC_TRANSIENT) != 0) continue;
            String suffix = suffixForField(fNode);
            MethodCallExpression readObject = callX(varX(oin), "read" + suffix);
            readObject.setImplicitThis(false);
            body.addStatement(assignS(varX(fNode), suffix.equals("Object") ? castX(GenericsUtils.nonGeneric(fNode.getType()), readObject) : readObject));
        }
        addGeneratedMethod(cNode, "readExternal", ACC_PUBLIC, ClassHelper.VOID_TYPE, params(oin), ClassNode.EMPTY_ARRAY, body);
    }

    private static String suffixForField(FieldNode fNode) {
        // use primitives for efficiency
        if (isPrimitiveInt(fNode.getType())) return "Int";
        if (isPrimitiveBoolean(fNode.getType())) return "Boolean";
//        currently char isn't found due to a bug, so go with Object
//        if (isPrimitiveChar(fNode.getType())) return "Character";
        if (isPrimitiveLong(fNode.getType())) return "Long";
        if (isPrimitiveShort(fNode.getType())) return "Short";
        if (isPrimitiveByte(fNode.getType())) return "Byte";
        if (isPrimitiveFloat(fNode.getType())) return "Float";
        if (isPrimitiveDouble(fNode.getType())) return "Double";
        return "Object";
    }
}


text:
topic: "Hardware and Data Mining, part 2"
desc: "One more lecture each from Diba and Miles"
lecture_date: 2016-08-18 09:00:00.00-7:00
week: "3"
---

# Morning:

8:45: Hardware/Robotics part 2 (Diba)
* Intro to raspberry pi
* Basics of breadboards
* Intro to Pi's GPIO pins
	* Blinking a LED
	* Communicating with sensors and actuators

* Lecture material based on from notes [lab08](http://ucsd-cse-spis-2016.github.io/lab/lab08/)

[FSM lecture by Diba](https://github.com/ucsd-cse-spis-2016/spis16-lecture-0818-FSM-Diba)

10:15: Working with Data  (Phill and Miles)

* [Public github repo with notes](https://github.com/ucsd-cse-spis-2016/spis16-lecture-0809)

# Afternoon

1:15-2:45:
* Niral, Taylor and Yvonne's teams: Hardware Lab, location TBA
* Everyone else: open lab (continue work on [lab06](/lab/lab06/),
    [lab07](/lab/lab07/), and start [lab08](/lab/lab08/)


text:
from .slackclient._util import SearchList
from .slackclient._user import User

class FakeServer(object):
    def __init__(self, slack=None, config=None, hooks=None, db=None):
        self.slack = slack or FakeSlack()
        self.config = config
        self.hooks = hooks
        self.db = db

    def query(self, sql, *params):
        # XXX: what to do with this?
        return None

class FakeSlack(object):
    def __init__(self, server=None, users=None):
        self.server = server or FakeSlackServer(users=users)

class FakeSlackServer(object):
    def __init__(self, botname="limbo_test", users=None):
        self.login_data = {
            "self": {
                "name": botname,
            }
        }

        if  users:
            self.users = users
        else:
            self.users = SearchList([
                User(self, "limbo_test", 1, "", 0),
                User(self, "msguser", 2, "", 0),
                User(self, "slackbot", 3, "", 0),
            ])


text:
SET(AVPCLLIB_ROOT "" CACHE STRING "Location of the BC7 Export library from NVTT")

IF(NOT AVPCLLIB_ROOT STREQUAL "")
  IF(NOT EXISTS "${AVPCLLIB_ROOT}/src/CMakeLists.txt")
    CONFIGURE_FILE(
      "${CMAKE_CURRENT_LIST_DIR}/bc7_export/CMakeLists.txt"
      "${AVPCLLIB_ROOT}/src"
      COPYONLY)
  ENDIF()
  ADD_SUBDIRECTORY(${AVPCLLIB_ROOT}/src ${CMAKE_CURRENT_BINARY_DIR}/bc7_export)
  set(AVPCLLIB_INCLUDE_DIR ${AVPCLLIB_ROOT}/src )
  SET(FOUND_NVTT_BPTC_EXPORT TRUE)
ENDIF()

mark_as_advanced( FORCE AVPCLLIB_ROOT AVPCLLIB_INCLUDE_DIR )


text:
<?php

namespace Drupal\KernelTests\Core\Entity;

use Drupal\entity_test\Entity\EntityTestMulRev;
use Drupal\language\Entity\ConfigurableLanguage;

/**
 * Tests proper revision propagation of entities.
 *
 * @group Entity
 */
class EntityRevisionTranslationTest extends EntityKernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = ['language'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Enable an additional language.
    ConfigurableLanguage::createFromLangcode('de')->save();

    $this->installEntitySchema('entity_test_mulrev');
  }

  /**
   * Tests if the translation object has the right revision id after new revision.
   */
  public function testNewRevisionAfterTranslation() {
    $user = $this->createUser();

    // Create a test entity.
    $entity = EntityTestMulRev::create([
      'name' => $this->randomString(),
      'user_id' => $user->id(),
      'language' => 'en',
    ]);
    $entity->save();
    $old_rev_id = $entity->getRevisionId();

    $translation = $entity->addTranslation('de');
    $translation->setNewRevision();
    $translation->save();

    $this->assertTrue($translation->getRevisionId() > $old_rev_id, 'The saved translation in new revision has a newer revision id.');
    $this->assertTrue($this->reloadEntity($entity)->getRevisionId() > $old_rev_id, 'The entity from the storage has a newer revision id.');
  }

  /**
   * Tests if the translation object has the right revision id after new revision.
   */
  public function testRevertRevisionAfterTranslation() {
    $user = $this->createUser();
    $storage = $this->entityManager->getStorage('entity_test_mulrev');

    // Create a test entity.
    $entity = EntityTestMulRev::create([
      'name' => $this->randomString(),
      'user_id' => $user->id(),
      'language' => 'en',
    ]);
    $entity->save();
    $old_rev_id = $entity->getRevisionId();

    $translation = $entity->addTranslation('de');
    $translation->setNewRevision();
    $translation->save();

    $entity = $this->reloadEntity($entity);

    $this->assertTrue($entity->hasTranslation('de'));

    $entity = $storage->loadRevision($old_rev_id);

    $entity->setNewRevision();
    $entity->isDefaultRevision(TRUE);
    $entity->save();

    $entity = $this->reloadEntity($entity);

    $this->assertFalse($entity->hasTranslation('de'));
  }

  /**
   * Tests the translation values when saving a forward revision.
   */
  public function testTranslationValuesWhenSavingForwardRevisions() {
    $user = $this->createUser();
    $storage = $this->entityManager->getStorage('entity_test_mulrev');

    // Create a test entity and a translation for it.
    $entity = EntityTestMulRev::create([
      'name' => 'default revision - en',
      'user_id' => $user->id(),
      'language' => 'en',
    ]);
    $entity->addTranslation('de', ['name' => 'default revision - de']);
    $entity->save();

    // Create a forward revision for the entity and change a field value for
    // both languages.
    $forward_revision = $this->reloadEntity($entity);

    $forward_revision->setNewRevision();
    $forward_revision->isDefaultRevision(FALSE);

    $forward_revision->name = 'forward revision - en';
    $forward_revision->save();

    $forward_revision_translation = $forward_revision->getTranslation('de');
    $forward_revision_translation->name = 'forward revision - de';
    $forward_revision_translation->save();

    $forward_revision_id = $forward_revision->getRevisionId();
    $forward_revision = $storage->loadRevision($forward_revision_id);

    // Change the value of the field in the default language, save the forward
    // revision and check that the value of the field in the second language is
    // also taken from the forward revision, *not* from the default revision.
    $forward_revision->name = 'updated forward revision - en';
    $forward_revision->save();

    $forward_revision = $storage->loadRevision($forward_revision_id);

    $this->assertEquals($forward_revision->name->value, 'updated forward revision - en');
    $this->assertEquals($forward_revision->getTranslation('de')->name->value, 'forward revision - de');
  }

  /**
   * Tests changing the default revision flag is propagated to all translations.
   */
  public function testDefaultRevision() {
    // Create a test entity with a translation, which will internally trigger
    // entity cloning for the new translation and create references for some of
    // the entity properties.
    $entity = EntityTestMulRev::create([
      'name' => 'original',
      'language' => 'en',
    ]);
    $translation = $entity->addTranslation('de');
    $entity->save();

    // Assert that the entity is in the default revision.
    $this->assertTrue($entity->isDefaultRevision());
    $this->assertTrue($translation->isDefaultRevision());

    // Change the default revision flag on one of the entity translations and
    // assert that the change is propagated to all entity translation objects.
    $translation->isDefaultRevision(FALSE);
    $this->assertFalse($entity->isDefaultRevision());
    $this->assertFalse($translation->isDefaultRevision());
  }

}


text:
static size_t bytes_total;
static size_t bytes_read;

int main(void)
{
	const char *path = "/usr/share/dict/words";
	struct stat sb;

	test_start("Dispatch Source Read");

	int infd = open(path, O_RDONLY);
	if (infd == -1) {
		perror(path);
		exit(EXIT_FAILURE);
	}
	if (fstat(infd, &sb) == -1) {
		perror(path);
		exit(EXIT_FAILURE);
	}
	bytes_total = sb.st_size;

	if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) {
		perror(path);
		exit(EXIT_FAILURE);
	}

	dispatch_queue_t main_q = dispatch_get_main_queue();
	test_ptr_notnull("dispatch_get_main_queue", main_q);

	dispatch_source_attr_t attr = dispatch_source_attr_create();
	test_ptr_notnull("dispatch_source_attr_create", attr);

	dispatch_source_attr_set_finalizer(attr, ^(dispatch_source_t ds) {
		test_ptr_notnull("finalizer ran", ds);
		int res = close(infd);
		test_errno("close", res == -1 ? errno : 0, 0);
		test_stop();
	});

	dispatch_source_t reader = dispatch_source_read_create(infd, attr,
		main_q, ^(dispatch_event_t ev) {
			long err_val;
			long err_dom = dispatch_event_get_error(ev, &err_val);
			if (!err_dom) {
				size_t estimated = dispatch_event_get_bytes_available(ev);
				printf("bytes available: %zu\n", estimated);
				const ssize_t bufsiz = 1024*500; // 500 KB buffer
				static char buffer[1024*500];	// 500 KB buffer
				ssize_t actual = read(infd, buffer, sizeof(buffer));
				bytes_read += actual;
				printf("bytes read: %zd\n", actual);
				if (actual < bufsiz) {
					actual = read(infd, buffer, sizeof(buffer));
					bytes_read += actual;
					// confirm EOF condition
					test_long("EOF", actual, 0);
					dispatch_release(dispatch_event_get_source(ev));
				}
			} else {
				test_long("Error domain", err_dom, DISPATCH_ERROR_DOMAIN_POSIX);
				test_long("Error value", err_val, ECANCELED);
				test_long("Bytes read", bytes_read, bytes_total);
			}
		});

	printf("reader = %p\n", reader);
	assert(reader);

	dispatch_release(attr);

	dispatch_main();
}